pylon-db-core 0.1.0

The Pylon compiler: PyQL parsing, IR, SQL emission, schema export and migration diffing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
//
// This source file is part of the Pylon open source project.
//
// Copyright (c) 2026 Jaldis B.V.
//
// Licensed under the MIT OR Apache-2.0 license (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://opensource.org/licenses/MIT
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use crate::error::{
    Position, PyQLError, PyQLResolutionError, PyQLTypeError, PyQLUnknownFieldError, PyQLUnknownTypeError,
};
use crate::parse::ast::{self, Expr, Literal, NonesOrder, ShapeElement, ShapeOp, SortDirection, Stmt};
use crate::schema::{
    FunctionDescriptor, LinkDescriptor, MultiLinkDescriptor, PropertyDescriptor, SchemaDescriptor, SearchBackend,
    TypeDescriptor,
};

use std::collections::{HashMap, HashSet};

use super::{
    IrArraySource, IrAssertedPointer, IrBinOp, IrComputedGlobalCte, IrComputedPointer, IrConflict, IrCteDef, IrDelete,
    IrExpr, IrFor, IrForIterator, IrFreeExpr, IrFtsSearch, IrFunctionCall, IrFunctionSelect, IrGlobalCte, IrGroup,
    IrGroupOutput, IrGroupProjection, IrIfElse, IrInsert, IrLinkProp, IrLiteral, IrLockClause, IrLockStrength,
    IrLockWait, IrMultiLinkClear, IrMultiLinkJoin, IrMultiLinkMutation, IrMultiLinkPointer, IrMultiLinkValueSource,
    IrMultiLinkValues, IrNulls, IrOutput, IrPathJoin, IrPathResult, IrPathSelect, IrPolyFanout, IrPolyImplementor,
    IrRowSource, IrScalarPointer, IrScalarSetPointer, IrSelect, IrSessionGlobalCte, IrShapePointer,
    IrSingleLinkCorrelation, IrSingleLinkPointer, IrSort, IrSortDir, IrSource, IrStmt, IrTypeCast, IrUnaryOp, IrUpdate,
    IrVectorSearch, SearchEnqueueInfo, TupleCastShape, VectorEnqueueInfo,
};

// ── Compiled-clause tuples ──────────────────────────────────────────────────────
//
// The three helpers that pull a statement's trailing clauses apart all return
// the same shape: the pieces in source order, each optional because a query
// need not spell any of them out. Named here so the signatures read as one
// concept rather than as an anonymous 4-tuple repeated three times.

/// `(filter, order_by, offset, limit)` — a plain `select`'s trailing clauses.
type SelectModifiers = (Option<IrExpr>, Vec<IrSort>, Option<IrExpr>, Option<IrExpr>);

/// `(filter, distance/rank direction, offset, limit)` — the trailing clauses of
/// a `vector::search`/`fts::search` select, where `order by` is constrained to
/// the search score rather than an arbitrary sort list.
type SearchModifiers = (Option<IrExpr>, Option<IrSortDir>, Option<IrExpr>, Option<IrExpr>);

/// `(type name, shape elements, sub-statement, link-property alias)` — the
/// parts of an expression that names a type and optionally shapes it.
type TypeAndShape<'e> = (String, &'e [ShapeElement], Option<&'e Stmt>, Option<String>);

// ── Public entry point ──────────────────────────────────────────────────────────

/// Compile a parsed PyQL statement against the schema, using default session
/// config (see `crate::ir::SessionConfig`) — used throughout this crate's own
/// tests and schema-time compilation, which never has a live client-supplied
/// config to honor. `compile_with_config` is the real entry a live query
/// request uses.
/// Returns the IR plan and the ordered list of parameter names (matching $1, $2, …).
pub fn compile(stmt: &Stmt, schema: &SchemaDescriptor) -> Result<IrOutput, PyQLError> {
    compile_with_config(stmt, schema, &crate::ir::SessionConfig::default())
}

/// Like `compile`, but honors a caller-supplied `SessionConfig` (e.g.
/// `allow_user_specified_id`) for this one statement.
pub fn compile_with_config(
    stmt: &Stmt,
    schema: &SchemaDescriptor,
    config: &crate::ir::SessionConfig,
) -> Result<IrOutput, PyQLError> {
    let mut c = Compiler::with_config(schema, config.clone());

    // Unwrap top-level WITH block: compile each CTE binding, then the main statement.
    let (ctes, ir) = if let Stmt::With(w) = stmt {
        // Special case: `with search := vector::search(…); select search { … } …`
        // Merge into a single IrVectorSearch rather than going through the CTE machinery.
        if let Some(ir) = try_compile_vs_with_pattern(&mut c, w)? {
            return Ok(IrOutput {
                subtype_fanouts: c.subtype_fanouts(),
                stmt: ir,
                params: c.params,
                ctes: vec![],
                global_ctes: c.global_ctes,
                warnings: c.warnings,
                uses_globals_arg: c.used_globals_arg,
            });
        }
        // Special case: `with search := fts::search(…); select search { … } …`
        if let Some(ir) = try_compile_fts_with_pattern(&mut c, w)? {
            return Ok(IrOutput {
                subtype_fanouts: c.subtype_fanouts(),
                stmt: ir,
                params: c.params,
                ctes: vec![],
                global_ctes: c.global_ctes,
                warnings: c.warnings,
                uses_globals_arg: c.used_globals_arg,
            });
        }

        let mut cte_defs = vec![];
        for alias in &w.aliases {
            if let Some(declared) = declared_pointers_of(&alias.expr) {
                c.cte_declared_pointers.insert(alias.name.clone(), declared);
            }
            if c.bind_group(&alias.name, &alias.expr)? {
                continue;
            }
            let ir_stmt = compile_cte_binding(&mut c, &alias.expr)?;
            let sql_name = c.claim_cte_sql_name(&alias.name);
            let type_name = c.register_cte(&alias.name, &ir_stmt);
            // What the binding hoisted (`p := existing ?? (insert …)`) goes
            // right before it: a CTE only sees the ones ahead of it.
            cte_defs.append(&mut c.hoisted_ctes);
            cte_defs.push(IrCteDef {
                name: sql_name,
                stmt: ir_stmt,
                type_name,
                correlated_to: None,
            });
        }
        let main = c.compile_stmt(&w.stmt)?;
        (cte_defs, main)
    } else {
        (vec![], c.compile_stmt(stmt)?)
    };

    let mut ctes = ctes;
    ctes.extend(std::mem::take(&mut c.hoisted_ctes));
    Ok(IrOutput {
        subtype_fanouts: c.subtype_fanouts(),
        stmt: ir,
        params: c.params,
        ctes,
        global_ctes: c.global_ctes,
        warnings: c.warnings,
        uses_globals_arg: c.used_globals_arg,
    })
}

/// Detect `with <var> := vector::search(Type, $vec); select <var> { object { … }, distance }`.
/// When matched, compile the whole thing to a single `IrVectorSearch`.
fn try_compile_vs_with_pattern(c: &mut Compiler<'_>, w: &ast::WithStmt) -> Result<Option<IrStmt>, PyQLError> {
    // Only handle exactly one alias that is a bare function call (not a subquery).
    if w.aliases.len() != 1 {
        return Ok(None);
    }
    let alias_def = &w.aliases[0];
    let fc = match &alias_def.expr {
        Expr::FunctionCall(fc) => fc,
        _ => return Ok(None),
    };
    if fc.module.as_deref() != Some("vector") || fc.name != "search" {
        return Ok(None);
    }

    // Main statement must be `select <alias_name> { … }`.
    let select_stmt = match w.stmt.as_ref() {
        Stmt::Select(s) => s,
        _ => return Ok(None),
    };
    // Unwrap optional Shape wrapper around the result expression.
    let (elements, result_inner): (&[ast::ShapeElement], &Expr) = match &select_stmt.result {
        Expr::Shape(sh) => {
            let inner = sh.expr.as_ref().unwrap_or(&select_stmt.result);
            (sh.elements.as_slice(), inner)
        }
        other => (&[], other),
    };
    // The inner expression should be a path referencing the WITH alias.
    match result_inner {
        Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
            if let ast::PathStep::Name(n) = &p.steps[0] {
                if n != &alias_def.name {
                    return Ok(None);
                }
            } else {
                return Ok(None);
            }
        }
        _ => return Ok(None),
    }

    if let Some(ir) = c.try_compile_vector_search(fc, elements, select_stmt)? {
        Ok(Some(IrStmt::VectorSearch(ir)))
    } else {
        Ok(None)
    }
}

fn try_compile_fts_with_pattern(c: &mut Compiler<'_>, w: &ast::WithStmt) -> Result<Option<IrStmt>, PyQLError> {
    if w.aliases.len() != 1 {
        return Ok(None);
    }
    let alias_def = &w.aliases[0];
    let fc = match &alias_def.expr {
        Expr::FunctionCall(fc) => fc,
        _ => return Ok(None),
    };
    if fc.module.as_deref() != Some("fts") || fc.name != "search" {
        return Ok(None);
    }

    let select_stmt = match w.stmt.as_ref() {
        Stmt::Select(s) => s,
        _ => return Ok(None),
    };
    let (elements, result_inner): (&[ast::ShapeElement], &Expr) = match &select_stmt.result {
        Expr::Shape(sh) => {
            let inner = sh.expr.as_ref().unwrap_or(&select_stmt.result);
            (sh.elements.as_slice(), inner)
        }
        other => (&[], other),
    };
    match result_inner {
        Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
            if let ast::PathStep::Name(n) = &p.steps[0] {
                if n != &alias_def.name {
                    return Ok(None);
                }
            } else {
                return Ok(None);
            }
        }
        _ => return Ok(None),
    }

    if let Some(ir) = c.try_compile_fts_search(fc, elements, select_stmt)? {
        Ok(Some(IrStmt::FtsSearch(ir)))
    } else {
        Ok(None)
    }
}

/// How many times a path may expand a computed pointer into its own path
/// before we call it a cycle. Chains are normal (a computed over a computed);
/// a chain this long is a schema that refers to itself.
/// AND a path traversal's own FILTER together with whatever conditions the
/// computed pointers spliced into it contributed. Every join in a path
/// select is inner, so a spliced computed's filter means the same thing as a
/// WHERE condition on the whole traversal.
/// `__subject__.p ?? (insert T { … })` — a rewrite that fills `p` with a new
/// object when the statement gives it none. The insert has no place in an
/// expression, so on insert it becomes `p := (insert …)` instead; `None`
/// for any other rewrite.
fn subject_default_insert(handler: &str, pointer: &str) -> Option<Expr> {
    fn holds_insert(expr: &Expr) -> bool {
        match expr {
            Expr::SubQuery(stmt) => match stmt.as_ref() {
                Stmt::Insert(_) => true,
                Stmt::Select(sel) => holds_insert(&sel.result),
                _ => false,
            },
            _ => false,
        }
    }
    let Ok(Expr::BinOp(b)) = crate::parse::parse_pointer_expr(handler) else {
        return None;
    };
    let reads_itself = matches!(&b.left, Expr::Path(p) if matches!(p.steps.as_slice(),
        [ast::PathStep::Name(subject), ast::PathStep::Name(name)] if subject == "__subject__" && name == pointer));
    (matches!(b.op, ast::BinOpKind::Coalesce) && reads_itself && holds_insert(&b.right)).then_some(b.right)
}

/// A sub-select's own `limit 1`: what makes it one object rather than a set.
fn limits_to_one(sel: Option<&ast::SelectStmt>) -> bool {
    sel.is_some_and(|sel| matches!(sel.limit, Some(Expr::Literal(ast::Literal::Int(1)))))
}

/// True when a select can yield at most one row: `limit 1`, or a filter that
/// pins an exclusive property (`.id = …`) in one of its `and`-ed conditions.
fn selects_at_most_one(sel: &ast::SelectStmt, td: &TypeDescriptor) -> bool {
    fn pins_exclusive(expr: &Expr, td: &TypeDescriptor) -> bool {
        let Expr::BinOp(b) = expr else { return false };
        match b.op {
            ast::BinOpKind::And => pins_exclusive(&b.left, td) || pins_exclusive(&b.right, td),
            ast::BinOpKind::Eq => [&b.left, &b.right].into_iter().any(|side| {
                matches!(side, Expr::Path(p) if p.partial
                    && matches!(p.steps.as_slice(), [ast::PathStep::Name(name)]
                        if td.properties.iter().any(|d| &d.name == name && (d.is_exclusive || d.is_pk))))
            }),
            _ => false,
        }
    }
    matches!(sel.limit, Some(Expr::Literal(ast::Literal::Int(1))))
        || sel.filter.as_ref().is_some_and(|f| pins_exclusive(f, td))
}

/// `(select .teams … limit 1) if cond else {}` as `(select .teams filter cond …
/// limit 1)`, carrying along a shape written on the branch or on the whole
/// if/else. `None` unless exactly one branch is empty and the other is a
/// relative walk or a select over one, and `cond` reads no relative path --
/// moved into the branch's filter, one would read the branch's rows instead.
fn guarded_object_branch(expr: &Expr) -> Option<Expr> {
    fn reads_relative(expr: &Expr) -> bool {
        match expr {
            Expr::Path(p) => p.partial,
            Expr::Literal(_) | Expr::Parameter(_) | Expr::Global(_) => false,
            Expr::BinOp(b) => reads_relative(&b.left) || reads_relative(&b.right),
            Expr::UnaryOp(u) => reads_relative(&u.operand),
            Expr::TypeCast(c) => reads_relative(&c.expr),
            Expr::FunctionCall(f) => f.args.iter().chain(f.kwargs.iter().map(|(_, v)| v)).any(reads_relative),
            Expr::IfElse(ie) => {
                reads_relative(&ie.if_expr) || reads_relative(&ie.condition) || reads_relative(&ie.else_expr)
            }
            _ => true,
        }
    }
    fn empty(expr: &Expr) -> bool {
        match expr {
            Expr::Set(items) => items.is_empty(),
            Expr::TypeCast(c) => matches!(&c.expr, Expr::Set(items) if items.is_empty()),
            _ => false,
        }
    }
    let (ie, outer_shape) = match expr {
        Expr::IfElse(ie) => (ie.as_ref(), None),
        Expr::Shape(sh) => match sh.expr.as_ref()? {
            Expr::IfElse(ie) => (ie.as_ref(), Some(sh.elements.clone())),
            _ => return None,
        },
        _ => return None,
    };
    if reads_relative(&ie.condition) {
        return None;
    }
    let (branch, condition) = match (empty(&ie.if_expr), empty(&ie.else_expr)) {
        (false, true) => (&ie.if_expr, ie.condition.clone()),
        (true, false) => (
            &ie.else_expr,
            Expr::UnaryOp(Box::new(ast::UnaryOp {
                op: ast::UnaryOpKind::Not,
                operand: ie.condition.clone(),
            })),
        ),
        _ => return None,
    };
    let (branch, branch_shape) = match branch {
        Expr::Shape(sh) => (sh.expr.as_ref()?, Some(sh.elements.clone())),
        other => (other, None),
    };
    let mut select = match branch {
        Expr::Path(p) if p.partial => ast::SelectStmt {
            result: branch.clone(),
            filter: None,
            order_by: vec![],
            offset: None,
            limit: None,
            lock: None,
        },
        Expr::SubQuery(stmt) => match stmt.as_ref() {
            Stmt::Select(sel) if matches!(&sel.result, Expr::Path(p) if p.partial) => sel.clone(),
            _ => return None,
        },
        _ => return None,
    };
    select.filter = Some(match select.filter.take() {
        Some(filter) => Expr::BinOp(Box::new(ast::BinOp {
            left: filter,
            op: ast::BinOpKind::And,
            right: condition,
        })),
        None => condition,
    });
    let guarded = Expr::SubQuery(Box::new(Stmt::Select(select)));
    Some(match outer_shape.or(branch_shape) {
        Some(elements) => Expr::Shape(Box::new(ast::ShapeExpr {
            expr: Some(guarded),
            elements,
            marker_offset: None,
        })),
        None => guarded,
    })
}

/// `.grants.account = a and not .grants.deleted` as the multi-link `grants`
/// and the condition on one of its elements (`.account = a and not
/// .deleted`, a bare `.grants` becoming the element's `.id`). `None` unless
/// every relative path in the condition walks that same multi-link — one
/// reading the outer row would rebind to the element inside the sub-select —
/// and the condition holds no sub-statement.
fn per_element_of_one_multilink(condition: &Expr, td: &TypeDescriptor) -> Option<(Vec<ast::PathStep>, Expr)> {
    // The steps that reach the elements: a link name, or a backlink with the
    // type intersection that narrows it (`.<brand[is Assignment]`).
    fn prefix_len(steps: &[ast::PathStep]) -> Option<usize> {
        match steps {
            [ast::PathStep::Name(_), ..] => Some(1),
            [ast::PathStep::Backlink(_), ast::PathStep::TypeIntersection(_), ..] => Some(2),
            _ => None,
        }
    }
    fn rewrite(expr: &Expr, link: &mut Option<Vec<ast::PathStep>>) -> Option<Expr> {
        Some(match expr {
            Expr::Path(p) if p.partial => {
                let split = prefix_len(&p.steps)?;
                let prefix = p.steps[..split].to_vec();
                if *link.get_or_insert_with(|| prefix.clone()) != prefix {
                    return None;
                }
                // The link itself (`.posts = p`) already compares per element.
                let rest = p.steps[split..].to_vec();
                if rest.is_empty() {
                    return None;
                }
                Expr::Path(ast::Path {
                    steps: rest,
                    partial: true,
                })
            }
            Expr::Path(_) | Expr::Literal(_) | Expr::Parameter(_) | Expr::Global(_) => expr.clone(),
            Expr::BinOp(b) => Expr::BinOp(Box::new(ast::BinOp {
                left: rewrite(&b.left, link)?,
                op: b.op.clone(),
                right: rewrite(&b.right, link)?,
            })),
            Expr::UnaryOp(u) => Expr::UnaryOp(Box::new(ast::UnaryOp {
                op: u.op.clone(),
                operand: rewrite(&u.operand, link)?,
            })),
            Expr::TypeCast(c) => Expr::TypeCast(Box::new(ast::TypeCast {
                expr: rewrite(&c.expr, link)?,
                ty: c.ty.clone(),
            })),
            Expr::TypeIs { expr, ty } => Expr::TypeIs {
                expr: Box::new(rewrite(expr, link)?),
                ty: ty.clone(),
            },
            // A set-returning call (`array_unpack`) is a second set the
            // quantifier ranges over, so turning the condition into one asked
            // per link element would change what it asks.
            Expr::FunctionCall(f)
                if crate::stdlib::lookup(f.module.as_deref().unwrap_or("std"), &f.name)
                    .iter()
                    .any(|d| d.returns_set()) =>
            {
                return None;
            }
            Expr::FunctionCall(f) => Expr::FunctionCall(ast::FunctionCall {
                module: f.module.clone(),
                name: f.name.clone(),
                args: f.args.iter().map(|a| rewrite(a, link)).collect::<Option<_>>()?,
                kwargs: f
                    .kwargs
                    .iter()
                    .map(|(k, v)| Some((k.clone(), rewrite(v, link)?)))
                    .collect::<Option<_>>()?,
            }),
            _ => return None,
        })
    }
    let mut link = None;
    let element_condition = rewrite(condition, &mut link)?;
    let link = link?;
    let many = match link.first()? {
        ast::PathStep::Name(name) => td.multilinks.iter().any(|m| &m.name == name),
        ast::PathStep::Backlink(_) => true,
        _ => false,
    };
    many.then_some((link, element_condition))
}

/// A shape's subject written in a longer form than it needs, rewritten to the
/// form the select routes already take; `None` when there is nothing to
/// rewrite.
///
/// - `(select E) { … }` with no clauses of its own is `E { … }`, for the
///   subjects only a select over them spells: an if/else, a union, a shape.
/// - `X { a := … } { a: { … } }` is one shape. The outer one says what comes
///   back; a name it lists that the inner one computed keeps that computation
///   and takes the outer one's nested shape and modifiers.
fn flatten_shape_subject(expr: &Expr) -> Option<Expr> {
    let Expr::Shape(outer) = expr else { return None };
    match outer.expr.as_ref()? {
        Expr::SubQuery(stmt) => {
            let Stmt::Select(sel) = stmt.as_ref() else { return None };
            let bare = sel.filter.is_none()
                && sel.order_by.is_empty()
                && sel.offset.is_none()
                && sel.limit.is_none()
                && sel.lock.is_none();
            if !bare || !matches!(sel.result, Expr::IfElse(_) | Expr::Union(_, _) | Expr::Shape(_)) {
                return None;
            }
            let mut flat = outer.as_ref().clone();
            flat.expr = Some(sel.result.clone());
            Some(Expr::Shape(Box::new(flat)))
        }
        Expr::Shape(inner) => {
            let elements = outer
                .elements
                .iter()
                .map(|el| {
                    let declared = match (&el.compexpr, el.path.steps.as_slice()) {
                        (None, [ast::PathStep::Name(name)]) => inner.elements.iter().find(|d| {
                            d.compexpr.is_some()
                                && matches!(d.path.steps.as_slice(), [ast::PathStep::Name(n)] if n == name)
                        }),
                        _ => None,
                    };
                    match declared {
                        Some(d) => ShapeElement {
                            nested: el.nested.clone().or_else(|| d.nested.clone()),
                            filter: el.filter.clone().or_else(|| d.filter.clone()),
                            order_by: if el.order_by.is_empty() {
                                d.order_by.clone()
                            } else {
                                el.order_by.clone()
                            },
                            offset: el.offset.clone().or_else(|| d.offset.clone()),
                            limit: el.limit.clone().or_else(|| d.limit.clone()),
                            ..d.clone()
                        },
                        None => el.clone(),
                    }
                })
                .collect();
            Some(Expr::Shape(Box::new(ast::ShapeExpr {
                expr: inner.expr.clone(),
                elements,
                marker_offset: inner.marker_offset,
            })))
        }
        _ => None,
    }
}

/// The name `.key.<name>` of a group is read through while its shape
/// compiles — not one a query can spell, so it shadows nothing.
fn group_key_binding(name: &str) -> String {
    format!("<group key {name}>")
}

fn and_conditions(filter: Option<IrExpr>, extra: Vec<IrExpr>) -> Option<IrExpr> {
    extra.into_iter().fold(filter, |acc, cond| match acc {
        Some(existing) => Some(IrExpr::BinOp(Box::new(IrBinOp {
            left: existing,
            op: ast::BinOpKind::And,
            right: cond,
        }))),
        None => Some(cond),
    })
}

const MAX_COMPUTED_SPLICES: usize = 32;

/// `sum`, `any`, `all` and `array_agg` over no rows: SQL gives NULL, Gel the
/// empty set's own value. `'{}'` rather than `ARRAY[]`, whose element type
/// PostgreSQL cannot infer on its own — inside a `coalesce` it takes the one
/// the aggregate already carries.
fn aggregate_over_nothing_sql(name: &str) -> Option<&'static str> {
    match name {
        "sum" => Some("0"),
        "any" => Some("false"),
        "all" => Some("true"),
        "array_agg" => Some("'{}'"),
        _ => None,
    }
}

fn aggregate_over_nothing(name: &str, aggregate: IrExpr) -> IrExpr {
    let Some(value) = aggregate_over_nothing_sql(name) else {
        return aggregate;
    };
    IrExpr::FunctionCall(IrFunctionCall {
        return_pg_type: None,
        schema: None,
        name: "coalesce".to_string(),
        args: vec![aggregate, IrExpr::RawSql(value.to_string())],
        sql_template: None,
    })
}

/// An expression whose value is a whole set, gathered as an array.
/// A set-valued walk gathered as an array, read back as a scalar subquery
/// instead — what an ordering comparison against a single value needs.
///
/// `(.installation.<installation[is RateLimitState].backoff_until < now) ?? true`
/// is conduit's backoff gate, and Gel evaluates it element-wise: empty set →
/// `{}` → the `??` supplies `true`. Rendered as an array the comparison is
/// `timestamptz[] < timestamptz`, which PostgreSQL has no operator for, so the
/// statement failed outright. As a scalar subquery the empty case is NULL, the
/// comparison is NULL, and `COALESCE` supplies the default — matching Gel for
/// the nought-or-one sets these walks actually produce (an `exclusive`
/// constraint guarantees it here). A genuinely many-valued walk now raises
/// PostgreSQL's own "more than one row returned by a subquery" rather than
/// comparing element-wise as Gel would; that is a narrower gap than emitting
/// SQL that cannot run at all.
fn set_walk_as_scalar(expr: IrExpr) -> IrExpr {
    match expr {
        IrExpr::ArrayFromSelect(source) => match *source {
            IrArraySource::PathSelect(ps) => IrExpr::PathSubquery(ps),
            other => IrExpr::ArrayFromSelect(Box::new(other)),
        },
        other => other,
    }
}

fn yields_array(expr: &IrExpr) -> bool {
    match expr {
        IrExpr::ArrayFromSelect(_) => true,
        IrExpr::IfElse(ie) => {
            (yields_array(&ie.if_) || matches!(ie.if_, IrExpr::Null))
                && (yields_array(&ie.else_) || matches!(ie.else_, IrExpr::Null))
                && !(matches!(ie.if_, IrExpr::Null) && matches!(ie.else_, IrExpr::Null))
        }
        _ => false,
    }
}

/// Look through the `coalesce` an aggregate over no rows is wrapped in — see
/// `aggregate_over_nothing`. The default only stands in for the aggregate, so
/// the type is the aggregate's.
fn through_coalesce(expr: &IrExpr) -> &IrExpr {
    match expr {
        IrExpr::FunctionCall(f) if f.schema.is_none() && f.name == "coalesce" => {
            f.args.first().map(through_coalesce).unwrap_or(expr)
        }
        other => other,
    }
}

fn ir_value_type_name(expr: &IrExpr) -> String {
    let expr = through_coalesce(expr);
    if let IrExpr::Array(elements) = expr {
        let element = elements.first().and_then(infer_ir_type).unwrap_or("text");
        return format!("{}[]", literal_sentinel_to_pg(element));
    }
    // `ids := array_agg(r.id)` binds an array of what it aggregates, which
    // is what lets `contains(ids, .id)` pick the array overload over `str`'s.
    if let IrExpr::FunctionCall(f) = expr
        && f.schema.is_none()
        && f.name == "array_agg"
        && let Some(element) = f.args.first().and_then(infer_ir_type)
    {
        return format!("{}[]", literal_sentinel_to_pg(element));
    }
    infer_ir_type(expr).map(|t| t.to_string()).unwrap_or_default()
}

/// The computed pointers a `with` binding's own shape declares, if any.
fn declared_pointers_of(expr: &Expr) -> Option<Vec<ShapeElement>> {
    // `(select T { x := … }) if cond else {}` declares what its select does.
    if let Expr::IfElse(ie) = expr {
        return declared_pointers_of(&ie.if_expr).or_else(|| declared_pointers_of(&ie.else_expr));
    }
    let Expr::SubQuery(stmt) = expr else {
        return None;
    };
    let shape = match innermost_select(stmt)? {
        ast::SelectStmt {
            result: Expr::Shape(sh),
            ..
        } => sh,
        _ => return None,
    };
    let declared: Vec<ShapeElement> = shape
        .elements
        .iter()
        .filter(|el| el.compexpr.is_some())
        .cloned()
        .collect();
    (!declared.is_empty()).then_some(declared)
}

/// The select a statement ultimately is, past any `with` blocks.
fn innermost_select(stmt: &Stmt) -> Option<&ast::SelectStmt> {
    match stmt {
        Stmt::Select(sel) => Some(sel),
        Stmt::With(w) => innermost_select(&w.stmt),
        _ => None,
    }
}

fn cte_stmt_type(stmt: &IrStmt) -> String {
    match stmt {
        IrStmt::Insert(ins) => ins.target.type_name.clone(),
        IrStmt::Update(upd) => upd.target.type_name.clone(),
        IrStmt::Delete(del) => del.target.type_name.clone(),
        IrStmt::Select(sel) => match sel.rows.first() {
            Some(IrRowSource::Bound { source, .. }) => source.type_name.clone(),
            // Infer the scalar pg_type from the first free item so the type
            // is available for UNION mismatch error messages. Returns empty
            // string if unknown.
            Some(IrRowSource::Free(IrFreeExpr::Scalar(expr))) => ir_value_type_name(expr),
            _ => String::new(),
        },
        // What a path select *yields*, not what it starts from: `with xs :=
        // (select Person.name)` binds text, not `default::Person`, and the
        // difference decides whether a reference to it reads the CTE's
        // `result` column or its `id` (see `resolve_name_ref`).
        IrStmt::PathSelect(ps) => match &ps.result {
            IrPathResult::Scalar(expr, _) => ir_value_type_name(expr),
            IrPathResult::Object { type_name, .. } => type_name.clone(),
        },
        IrStmt::For(f) => cte_stmt_type(&f.body),
        IrStmt::ScalarUnion(branches) => branches.first().map(cte_stmt_type).unwrap_or_default(),
        IrStmt::Group(g) => g.source.type_name.clone(),
        IrStmt::FunctionSelect(fs) => fs.type_name.clone(),
        IrStmt::VectorSearch(vs) => format!("__vs__{}", vs.source.type_name),
        IrStmt::FtsSearch(fs) => format!("__fts__{}", fs.source.type_name),
    }
}

/// Compile a WITH binding value: a subquery becomes its statement; any other
/// expression is wrapped in a synthetic `select expr` so it can be used as a CTE.
fn compile_cte_binding(c: &mut Compiler<'_>, expr: &Expr) -> Result<IrStmt, PyQLError> {
    let stmt = compile_cte_binding_stmt(c, expr)?;
    Ok(hoist_binding_dml(c, stmt))
}

/// `g := (insert T { … }) if cond else {}` — the binding's value compiles to a
/// select *over* a mutation. A data-modifying statement may only sit at the top
/// level of a `WITH`, never inside another CTE's body, so the mutation becomes a
/// CTE of its own ahead of this binding — where `g := existing ?? (insert T { …
/// })` already puts one — and the binding reads its rows back from there.
/// Emitted as-is, the mutation was dropped and the binding read the whole table.
fn hoist_binding_dml(c: &mut Compiler<'_>, stmt: IrStmt) -> IrStmt {
    let IrStmt::Select(mut select) = stmt else {
        return stmt;
    };
    let Some(dml) = select
        .dml_source
        .take_if(|dml| matches!(dml.as_ref(), IrStmt::Insert(_) | IrStmt::Update(_) | IrStmt::Delete(_)))
    else {
        return IrStmt::Select(select);
    };
    let cte_name = c.fresh_nested_cte_name();
    for row in &mut select.rows {
        if let IrRowSource::Bound { source, .. } = row {
            source.table = format!("@cte:{cte_name}");
            // The CTE's rows are already the concrete ones the mutation
            // touched, each carrying its own `__type__`.
            source.poly = None;
        }
    }
    c.hoisted_ctes.push(IrCteDef {
        name: cte_name,
        type_name: cte_stmt_type(&dml),
        stmt: *dml,
        correlated_to: None,
    });
    IrStmt::Select(select)
}

fn compile_cte_binding_stmt(c: &mut Compiler<'_>, expr: &Expr) -> Result<IrStmt, PyQLError> {
    if let Expr::SubQuery(s) = expr {
        let stmt = c.compile_stmt(s)?;
        if let IrStmt::Group(grp) = &stmt
            && !matches!(grp.output, IrGroupOutput::Elements)
        {
            return Err(c.type_err("a `group` cannot be bound in a `with` except to iterate it with `for`"));
        }
        return Ok(stmt);
    }
    // `existing ?? (insert Tag { … })` — on sets `A ?? B` is `A if exists A
    // else B`, the upsert idiom the if/else route already guards the
    // mutation for.
    let expr = match expr {
        Expr::BinOp(b)
            if b.op == ast::BinOpKind::Coalesce
                && matches!(&b.right, Expr::SubQuery(s) if matches!(s.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_))) =>
        {
            &Expr::IfElse(Box::new(ast::IfElse {
                if_expr: b.left.clone(),
                condition: Expr::UnaryOp(Box::new(ast::UnaryOp {
                    op: ast::UnaryOpKind::Exists,
                    operand: b.left.clone(),
                })),
                else_expr: b.right.clone(),
            }))
        }
        other => other,
    };
    // Non-statement expression (e.g. `<default::Company><uuid>'...'`):
    // treat as `select expr`.
    let fake_sel = ast::SelectStmt {
        result: expr.clone(),
        filter: None,
        order_by: vec![],
        offset: None,
        limit: None,
        lock: None,
    };
    c.compile_stmt(&Stmt::Select(fake_sel))
}

/// Qualified names of the functions that take `GLOBALS_ARG`.
///
/// A function needs it when its body reads a session global, *or* when it calls
/// a function that needs it — so this is a fixpoint, not a single pass: the
/// first pass finds the direct readers, later passes find their callers. A body
/// that fails to compile is skipped; that failure is reported by validation,
/// and guessing at its globals here would only produce a second, worse error.
pub fn functions_needing_globals(schema: &SchemaDescriptor) -> &std::collections::HashSet<String> {
    schema
        .functions_needing_globals
        .get_or_init(|| find_functions_needing_globals(schema))
}

fn find_functions_needing_globals(schema: &SchemaDescriptor) -> std::collections::HashSet<String> {
    let mut needs: std::collections::HashSet<String> = std::collections::HashSet::new();
    loop {
        let mut changed = false;
        for fd in &schema.functions {
            let qualified = format!("{}::{}", fd.module, fd.name);
            if needs.contains(&qualified) {
                continue;
            }
            if let Ok(out) = compile_fn_body_with(fd, schema, &needs)
                && out.uses_globals_arg
            {
                needs.insert(qualified);
                changed = true;
            }
        }
        if !changed {
            return needs;
        }
    }
}

/// Compile the PyQL body of a user-defined function for DDL emission.
///
/// Sets `fn_params` on the compiler so that parameter names resolve as `FnParam`
/// nodes rather than raising "expression is not valid in free SELECT context".
pub fn compile_fn_body(
    fn_desc: &crate::schema::FunctionDescriptor,
    schema: &SchemaDescriptor,
) -> Result<super::IrOutput, crate::error::PyQLError> {
    compile_fn_body_with(fn_desc, schema, functions_needing_globals(schema))
}

/// `compile_fn_body` with the globals-argument set supplied, so the fixpoint in
/// `functions_needing_globals` can call this without recursing into itself.
pub fn compile_fn_body_with(
    fn_desc: &crate::schema::FunctionDescriptor,
    schema: &SchemaDescriptor,
    fns_needing_globals: &std::collections::HashSet<String>,
) -> Result<super::IrOutput, crate::error::PyQLError> {
    use crate::parse;
    use crate::parse::ast::Stmt;

    let body = fn_desc.body.trim().to_string();
    // A body that is already a statement stands on its own; only a bare
    // expression needs the `select` that turns it into one. Wrapping a
    // statement instead would bury it as a sub-select and lose its clauses.
    let starts_a_stmt = ["select", "with", "for", "group", "insert", "update", "delete"]
        .iter()
        .any(|keyword| {
            body.len() > keyword.len()
                && body[..keyword.len()].eq_ignore_ascii_case(keyword)
                && !body.as_bytes()[keyword.len()].is_ascii_alphanumeric()
                && body.as_bytes()[keyword.len()] != b'_'
        });
    let body = if starts_a_stmt {
        body
    } else {
        format!("select {}", body)
    };

    let ast = parse::parse(&body)?;
    let mut c = Compiler::new(schema);
    c.in_fn_body = true;
    c.fns_needing_globals = Some(fns_needing_globals.clone());
    for p in &fn_desc.params {
        c.fn_params.insert(p.name.clone(), p.pg_type.clone());
    }

    let (ctes, ir) = if let Stmt::With(w) = &ast {
        let mut cte_defs = vec![];
        for alias in &w.aliases {
            let ir_stmt = compile_cte_binding(&mut c, &alias.expr)?;
            let type_name = cte_stmt_type(&ir_stmt);
            c.cte_types.insert(alias.name.clone(), type_name.clone());
            c.note_cte_cardinality(&alias.name, &ir_stmt);
            cte_defs.push(super::IrCteDef {
                name: alias.name.clone(),
                stmt: ir_stmt,
                type_name,
                correlated_to: None,
            });
        }
        let main = c.compile_stmt(&w.stmt)?;
        (cte_defs, main)
    } else {
        (vec![], c.compile_stmt(&ast)?)
    };

    let mut ctes = ctes;
    ctes.extend(std::mem::take(&mut c.hoisted_ctes));
    Ok(super::IrOutput {
        subtype_fanouts: c.subtype_fanouts(),
        stmt: ir,
        params: c.params,
        ctes,
        global_ctes: c.global_ctes,
        warnings: c.warnings,
        uses_globals_arg: c.used_globals_arg,
    })
}

/// Compile a schema `Trigger`'s `handler` PyQL statement for DDL emission —
/// same shape as `compile_fn_body`, but instead of `fn_params` this binds
/// `__new__`/`__old__` as the inserted/updated/deleted row (see
/// `Compiler::special_anchors`'s own doc comment), gated by `on_mask`
/// (Pylon's `On` bitmask: 1=Insert, 2=Update, 4=Delete): `__old__` is bound whenever
/// `on_mask` does *not* include Insert (so Update-only, Delete-only, and
/// Update+Delete all get it — but never a mask that includes Insert, even
/// combined with Update, since a shared trigger function has no old row on
/// the Insert branch of that combination); `__new__` is bound whenever
/// `on_mask` does *not* include Delete, by the mirror-image argument. A
/// mask combining Insert and Delete (with no Update) legally binds
/// neither. Referencing an anchor that isn't bound is a compile error, not
/// a runtime NULL.
/// One compiled rewrite: the column it writes and the value it writes there.
pub struct RewriteAssignment {
    pub pointer: String,
    pub column: String,
    pub ir: IrExpr,
    pub sql: String,
}

/// A type's rewrites for one event (`on_mask`: 1 = insert, 2 = update), each
/// compiled against the row being written (`NEW`) as `(column, SQL)`, for
/// the `BEFORE` trigger that applies them. Evaluated on the row as the
/// statement left it, every rewrite sees the others' inputs, not their
/// results — as Gel evaluates them.
pub fn compile_rewrite_assignments(
    type_name: &str,
    on_mask: u8,
    schema: &SchemaDescriptor,
) -> Result<Vec<RewriteAssignment>, crate::error::PyQLError> {
    let mut c = Compiler::new(schema);
    c.in_fn_body = true;
    let owner_td = c.resolve_type(type_name)?;
    c.special_anchors
        .insert("__new__".to_string(), (owner_td, "NEW".to_string()));
    if on_mask & 1 == 0 {
        c.special_anchors
            .insert("__old__".to_string(), (owner_td, "OLD".to_string()));
    }
    let pointers = owner_td
        .properties
        .iter()
        .map(|p| (p.name.clone(), p.name.clone(), &p.rewrites))
        .chain(
            owner_td
                .links
                .iter()
                .filter(|l| !l.is_junction_backed())
                .map(|l| (l.name.clone(), format!("{}_id", l.name), &l.rewrites)),
        );
    let fanouts = c.subtype_fanouts();
    let mut out = Vec::new();
    for (name, column, rewrites) in pointers {
        for rw in rewrites.iter().filter(|rw| rw.on & on_mask != 0) {
            // Carried out by `compile_insert` as an assignment.
            if on_mask == 1 && subject_default_insert(&rw.handler, &name).is_some() {
                continue;
            }
            let expr = crate::parse::parse_pointer_expr(&rw.handler)?;
            let ir = c.compile_expr(&expr, owner_td, "NEW")?;
            if !c.params.is_empty() || !c.hoisted_ctes.is_empty() {
                return Err(PyQLError::Type(PyQLTypeError {
                    message: format!(
                        "the rewrite of '{type_name}.{name}' has nowhere to bind a parameter or a binding"
                    ),
                    position: Position { line: 0, col: 0 },
                }));
            }
            let sql = crate::sql::emit_expr_with_fanouts(&ir, &fanouts);
            out.push(RewriteAssignment {
                pointer: name.clone(),
                column: column.clone(),
                ir,
                sql,
            });
        }
    }
    Ok(out)
}

pub fn compile_trigger_handler(
    handler: &str,
    type_name: &str,
    on_mask: u8,
    schema: &SchemaDescriptor,
) -> Result<super::IrOutput, crate::error::PyQLError> {
    use crate::parse;
    use crate::parse::ast::Stmt;

    let ast = parse::parse(handler.trim())?;
    let mut c = Compiler::new(schema);
    // A trigger has no parameters to bind a session global to; it reads them
    // from `GLOBALS_ARG`, which its function declares from `pylon.globals`.
    c.in_fn_body = true;
    // The trigger's own type — `__new__`/`__old__` always resolve against
    // this, regardless of what type happens to be the ambient `td` where
    // the anchor is textually used (e.g. inside `insert Note { note :=
    // __new__.name }`, the ambient td at that point is `Note`, not this).
    let owner_td = c.resolve_type(type_name)?;
    if on_mask & 4 == 0 {
        c.special_anchors
            .insert("__new__".to_string(), (owner_td, "NEW".to_string()));
    }
    if on_mask & 1 == 0 {
        c.special_anchors
            .insert("__old__".to_string(), (owner_td, "OLD".to_string()));
    }

    let (ctes, ir) = if let Stmt::With(w) = &ast {
        let mut cte_defs = vec![];
        for alias in &w.aliases {
            // `resolved := (__new__.status = …)` — a value read off the row
            // the trigger fired for, which a CTE has no way to see; it
            // stands in for its value wherever the name is used.
            if !matches!(alias.expr, ast::Expr::SubQuery(_)) {
                let anchor = if on_mask & 4 == 0 { "NEW" } else { "OLD" };
                let value = c.compile_expr(&alias.expr, owner_td, anchor)?;
                c.inline_bindings.insert(alias.name.clone(), value);
                continue;
            }
            let ir_stmt = compile_cte_binding(&mut c, &alias.expr)?;
            let sql_name = c.claim_cte_sql_name(&alias.name);
            let cte_type_name = cte_stmt_type(&ir_stmt);
            c.cte_types.insert(alias.name.clone(), cte_type_name.clone());
            c.note_cte_cardinality(&alias.name, &ir_stmt);
            cte_defs.push(super::IrCteDef {
                name: sql_name,
                stmt: ir_stmt,
                type_name: cte_type_name,
                correlated_to: None,
            });
        }
        let main = c.compile_stmt(&w.stmt)?;
        (cte_defs, main)
    } else {
        (vec![], c.compile_stmt(&ast)?)
    };

    let recursive_kind = recursive_dml_event(&ir, type_name)
        .or_else(|| ctes.iter().find_map(|cte| recursive_dml_event(&cte.stmt, type_name)));
    if let Some(kind) = recursive_kind
        && kind & on_mask != 0
    {
        return Err(crate::error::PyQLError::Fragment(crate::error::PyQLFragmentError {
            message: format!(
                "trigger on {type_name} is recursive: its handler {}s its own type, \
                     which this trigger also fires on",
                dml_event_word(kind),
            ),
            context: type_name.to_string(),
            position: crate::error::Position { line: 0, col: 0 },
        }));
    }

    let mut ctes = ctes;
    ctes.extend(std::mem::take(&mut c.hoisted_ctes));
    Ok(super::IrOutput {
        subtype_fanouts: c.subtype_fanouts(),
        stmt: ir,
        params: c.params,
        ctes,
        global_ctes: c.global_ctes,
        warnings: c.warnings,
        uses_globals_arg: c.used_globals_arg,
    })
}

fn dml_event_word(kind: u8) -> &'static str {
    match kind {
        1 => "insert",
        2 => "update",
        4 => "delete",
        _ => "mutate",
    }
}

/// Walks a compiled trigger handler's IR looking for a nested `INSERT`/
/// `UPDATE`/`DELETE` targeting `owner_type` — the same type the trigger
/// itself is declared on. Returns that DML's own event bit (1/2/4) the
/// first time one is found, so the caller can check it against the
/// trigger's own `on_mask`: a handler that inserts into its own type only
/// matters if this trigger *also* fires on Insert — the mask determines
/// what would actually refire, not just "does it touch itself at all".
///
/// Deliberately not exhaustive: covers the direct statement, a `SELECT
/// (INSERT/UPDATE/DELETE …) { … }` wrapper, and `for x in … union (…)`
/// loop bodies — the shapes every trigger handler in this codebase's own
/// test suite actually uses. A DML nested inside a free tuple/set literal
/// (`select { (insert A {...}), (insert B {...}) }`) isn't walked; a
/// handler written that way relies on Postgres's own runtime recursion-
/// depth guard instead, same fallback as before this check existed.
fn recursive_dml_event(stmt: &IrStmt, owner_type: &str) -> Option<u8> {
    match stmt {
        IrStmt::Insert(ins) if ins.target.type_name == owner_type => Some(1),
        IrStmt::Update(upd) if upd.target.type_name == owner_type => Some(2),
        IrStmt::Delete(del) if del.target.type_name == owner_type => Some(4),
        IrStmt::Select(sel) => sel
            .dml_source
            .as_deref()
            .and_then(|inner| recursive_dml_event(inner, owner_type)),
        IrStmt::For(for_stmt) => recursive_dml_event(&for_stmt.body, owner_type),
        _ => None,
    }
}

/// Compile a single PyQL expression in the context of a named type.
/// Used for schema fragments: computed pointers, rewrite handlers, constraint exprs.
pub fn compile_expr_in_type(
    expr: &Expr,
    type_name: &str,
    schema: &SchemaDescriptor,
) -> Result<(IrExpr, Vec<String>), PyQLError> {
    let mut c = Compiler::new(schema);
    let td = c.resolve_type(type_name)?;
    let alias = c.fresh_alias();
    let ir = c.compile_expr(expr, td, &alias)?;
    Ok((ir, c.params))
}

/// Compile a schema-declared computed pointer the same way a shape that
/// included it would, for validation.
///
/// Returns the scalar expression when the computed is scalar-valued, and
/// `None` when it compiles to an object (link) pointer — `(select .emails
/// filter .primary limit 1)` and friends, which have no scalar type for a
/// declared return type to be checked against.
pub fn compile_computed_in_type(
    cd: &crate::schema::ComputedDescriptor,
    type_name: &str,
    schema: &SchemaDescriptor,
) -> Result<Option<IrExpr>, PyQLError> {
    let mut c = Compiler::new(schema);
    let td = c.resolve_type(type_name)?;
    let module = td.module.clone();
    let alias = c.fresh_alias();
    match c.compile_declared_computed(cd, td, &alias, &module, None, &[])? {
        IrShapePointer::Computed(p) => Ok(Some(p.expr)),
        _ => Ok(None),
    }
}

/// Like `compile_expr_in_type` but uses an empty table alias, so that column
/// references emit as bare column names (`"col"` rather than `"a1"."col"`).
/// Used for fill expressions in migration UPDATE SET clauses.
pub fn compile_expr_unaliased(
    expr: &Expr,
    type_name: &str,
    schema: &SchemaDescriptor,
) -> Result<(IrExpr, Vec<String>), PyQLError> {
    let mut c = Compiler::new(schema);
    let td = c.resolve_type(type_name)?;
    let ir = c.compile_expr(expr, td, "")?;
    Ok((ir, c.params))
}

/// Compile a PyQL scalar expression to a SQL string for use as a column DEFAULT.
///
/// Wraps the expression in `SELECT <expr>`, compiles it as a free scalar, and
/// returns the emitted SQL expression (without the SELECT wrapper).
pub fn compile_scalar_default(pyql: &str, schema: &SchemaDescriptor) -> Result<String, String> {
    compile_scalar_default_typed(pyql, schema).map(|(sql, _ir)| sql)
}

/// Like `compile_scalar_default`, but also returns the compiled `IrExpr` —
/// used by schema-type-consistency validation (`crate::validate`) to infer
/// the default's actual produced type via `infer_ir_type`.
/// Compile a PyQL boolean expression in a type's context into the SQL a CHECK
/// constraint needs.
///
/// Columns emit unqualified (via `compile_expr_unaliased`), which is what a
/// table-level CHECK wants — it has no alias to qualify against.
pub fn compile_constraint_expr(
    pyql: &str,
    type_name: &str,
    schema: &SchemaDescriptor,
) -> Result<String, crate::error::PyQLError> {
    use crate::parse::ast::Stmt;
    let ast = crate::parse::parse(&format!("SELECT {pyql}"))?;
    let Stmt::Select(sel) = &ast else {
        return Err(PyQLError::Type(PyQLTypeError {
            message: "constraint expression must be an expression".into(),
            position: Position { line: 0, col: 0 },
        }));
    };
    let (ir, _params) = compile_expr_unaliased(&sel.result, type_name, schema)?;
    Ok(crate::sql::emit_expr(&ir))
}

pub fn compile_scalar_default_typed(pyql: &str, schema: &SchemaDescriptor) -> Result<(String, IrExpr), String> {
    use crate::parse::ast::Stmt;
    let full = format!("SELECT {}", pyql);
    let ast = crate::parse::parse(&full).map_err(|e| e.message)?;
    let Stmt::Select(sel) = &ast else {
        return Err("default expression must be a select statement".into());
    };
    let mut c = Compiler::new(schema);
    let ir = c.compile_free_expr(&sel.result).map_err(|e| e.to_string())?;
    let sql = crate::sql::emit_expr(&ir);
    Ok((sql, ir))
}

/// What in `expr` disqualifies it from being a column DEFAULT, if anything.
///
/// PostgreSQL evaluates a column default with no row and no query in scope,
/// so it rejects a sub-select outright ("cannot use subquery in DEFAULT
/// expression") and has nothing to resolve another column's name against.
pub fn default_blocker(expr: &IrExpr) -> Option<&'static str> {
    use IrExpr as E;
    match expr {
        E::Subquery(_)
        | E::ObjectSubquery(_)
        | E::ObjectPathSubquery(_)
        | E::ObjectPathUnion { .. }
        | E::PathSubquery(_)
        | E::FnSubquery(_)
        | E::ArrayFromSelect(_)
        | E::ScalarSubquery(_)
        | E::AggOverQuery { .. }
        | E::AggOverCte { .. }
        | E::ExistsOverCte { .. }
        | E::SetOp { .. }
        | E::AggOverSet { .. }
        | E::CteRef { .. }
        | E::CteFieldRef { .. }
        | E::GlobalRef { .. } => Some("a sub-select"),
        E::ColumnRef { .. } => Some("a reference to another pointer"),
        E::Param { .. } | E::GlobalParam { .. } => Some("a query parameter"),
        E::ForVar { .. } => Some("a for-loop variable"),
        E::FnParam { .. } => Some("a function parameter"),
        E::BinOp(b) => default_blocker(&b.left).or_else(|| default_blocker(&b.right)),
        E::UnaryOp(u) => default_blocker(&u.operand),
        E::TypeCast(c) => default_blocker(&c.expr),
        E::IfElse(i) => default_blocker(&i.condition)
            .or_else(|| default_blocker(&i.if_))
            .or_else(|| default_blocker(&i.else_)),
        E::FunctionCall(f) => f.args.iter().find_map(default_blocker),
        E::Array(items) | E::Tuple(items) => items.iter().find_map(default_blocker),
        E::NamedTuple { fields, .. } => fields.iter().find_map(|(_, e)| default_blocker(e)),
        E::Subscript { expr, index, .. } => default_blocker(expr).or_else(|| default_blocker(index)),
        E::JsonbField { expr, .. } | E::JsonbIndex { expr, .. } => default_blocker(expr),
        E::Slice { expr, lower, upper, .. } => default_blocker(expr)
            .or_else(|| lower.as_deref().and_then(default_blocker))
            .or_else(|| upper.as_deref().and_then(default_blocker)),
        E::Literal(_) | E::Null | E::EnumLiteral { .. } | E::RawSql(_) => None,
    }
}

/// The SQL for a pointer's PyQL default as a column DEFAULT clause, or `None`
/// when a column DEFAULT cannot hold it — it reads a session global, selects
/// an object, or otherwise needs the query around it. Those are applied by
/// `compile_insert` instead; see `inlined_pointer_defaults`.
pub fn column_default_sql(pyql: &str, schema: &SchemaDescriptor) -> Option<String> {
    let (sql, ir) = compile_scalar_default_typed(pyql, schema).ok()?;
    default_blocker(&ir).is_none().then_some(sql)
}

/// The pointers whose PyQL default an insert has to expand into its own shape,
/// paired with that default, because `column_default_sql` cannot render it.
///
/// Gel expands *every* default this way — `_gen_pointers_from_defaults` in its
/// EdgeQL compiler adds one shape element per unspecified pointer, which is why
/// an object-returning default like `created_by := account_of_transaction()` has
/// always worked there. Here the defaults a column DEFAULT does hold keep using
/// it, so only the remainder needs the query.
pub fn inlined_pointer_defaults(td: &TypeDescriptor, schema: &SchemaDescriptor) -> Vec<(String, String)> {
    let properties = td
        .properties
        .iter()
        .filter(|p| !p.is_pk)
        .filter_map(|p| p.default_pyql.as_ref().map(|d| (p.name.clone(), d.clone())));
    let links = td
        .links
        .iter()
        .filter(|l| !l.is_junction_backed())
        .filter_map(|l| l.default_pyql.as_ref().map(|d| (l.name.clone(), d.clone())));
    properties
        .chain(links)
        .filter(|(_, pyql)| column_default_sql(pyql, schema).is_none())
        .collect()
}

/// One inlined default as the insert shape carries it: `pointer := <default>`.
fn default_shape_element(pointer: &str, value: Expr) -> ShapeElement {
    ShapeElement {
        path: ast::Path::relative(pointer),
        splat: None,
        nested: None,
        compexpr: Some(value),
        op: ShapeOp::Assign,
        filter: None,
        order_by: vec![],
        offset: None,
        limit: None,
        marker_offset: None,
    }
}

/// One inlined default, compiled the way `compile_insert` expands it into an
/// insert's shape — so a default that cannot compile there is caught by schema
/// validation rather than by the first insert that omits the pointer.
///
/// One pointer at a time, because the caller reporting the failure has to be
/// able to name which declaration caused it.
pub fn compile_inlined_default(
    type_name: &str,
    pointer: &str,
    pyql: &str,
    schema: &SchemaDescriptor,
) -> Result<(String, IrExpr), PyQLError> {
    let mut c = Compiler::new(schema);
    let td = c.resolve_type(type_name)?;
    let alias = c.fresh_alias();
    let element = default_shape_element(pointer, crate::parse::parse_pointer_expr(pyql)?);
    let mut assignments = c.compile_assignments(&[element], td, &alias)?;
    Ok(assignments.remove(0))
}

// ── Compiler context ────────────────────────────────────────────────────────────

struct Compiler<'a> {
    schema: &'a SchemaDescriptor,
    /// Ordered parameter names — index + 1 is the $N position in SQL.
    params: Vec<String>,
    alias_counter: usize,
    /// CTE names registered in the enclosing WITH block → qualified type name.
    cte_types: HashMap<String, String>,
    /// `with g := (group …)` bindings. A group's rows are no schema object, so
    /// nothing can read them as a CTE; a `for` over one compiles the group
    /// again in its own terms instead.
    group_bindings: HashMap<String, IrGroup>,
    /// CTE names bound to a single free row (free object/scalar/tuple, not
    /// a schema object) → that row's `IrFreeExpr` — lets `root.field`
    /// resolve to `IrExpr::CteFieldRef` when `root` is such a binding,
    /// instead of failing as an unresolvable schema-path root.
    cte_free_items: HashMap<String, IrFreeExpr>,
    /// CTE names whose binding can hold more than one row. Comparing a value
    /// against one has to become set membership: `IrExpr::CteRef` reads the
    /// binding as a scalar subquery, which Postgres aborts on the second row
    /// ("more than one row returned by a subquery used as an expression").
    multi_row_ctes: HashSet<String>,
    /// FOR loop variables in scope: variable name → pg_type of the scalar iterator.
    for_vars: HashMap<String, String>,
    /// For-loop variables that iterate objects, by qualified type name. The
    /// variable itself holds the row's key (see `compile_for`), so a path
    /// rooted at one reads its table back by that key.
    for_var_types: HashMap<String, String>,
    /// For a loop over a `with` binding, the binding each variable's rows come
    /// from. The rows a sibling CTE has just written are not in the base table
    /// yet -- Postgres runs every CTE against the snapshot the statement
    /// started with -- so a walk off the variable has to read the binding.
    for_var_ctes: HashMap<String, String>,
    /// The name each loop variable's iterator CTE is emitted under. Two
    /// sibling loops may use the same variable name, and a WITH clause cannot
    /// hold the same CTE name twice.
    for_var_slots: HashMap<String, String>,
    /// The condition a `(insert …) if cond else {}` puts on the insert about
    /// to be compiled — see `IrInsert::guard`.
    pending_insert_guard: Option<Expr>,
    /// The condition a guarded `update` has to carry itself, for the same
    /// reason an insert does: a data-modifying CTE runs whether or not
    /// anything reads it, so filtering what is read back changes nothing.
    pending_update_guard: Option<Expr>,
    /// See `pending_update_guard` — the same, for a guarded delete.
    pending_delete_guard: Option<Expr>,
    /// Pointers a `with` binding declared in its own shape (`offering := (
    /// select Offering { publisher := … })`). They exist nowhere on the type,
    /// so a later `offering { publisher }` has to find them here.
    cte_declared_pointers: HashMap<String, Vec<ShapeElement>>,
    /// Those of the binding whose shape is being compiled right now.
    active_declared_pointers: Vec<ShapeElement>,
    /// Computed pointers a path is reading as a value right now, as
    /// `module::Type.name` — one that names itself would otherwise recurse
    /// without end.
    expanding_computeds: Vec<String>,
    /// The schema-bound selects currently being compiled, innermost last.
    ///
    /// Only consulted for `detached`: an absolute `TypeName.prop` inside a
    /// detached select means the *enclosing* select's row, so the innermost
    /// entry is skipped and the next matching one used.
    anchors: Vec<SelectAnchor>,
    /// CTE definitions a nested `with` contributed from somewhere the
    /// emitter has no WITH clause of its own — an expression, say. They are
    /// appended to the statement's own CTEs at the top-level boundary.
    hoisted_ctes: Vec<IrCteDef>,
    /// What each hoisted binding was defined as, so the same one arriving
    /// twice (one computed inlined from two places) is recognised as the same
    /// rather than emitted twice under one CTE name.
    hoisted_binding_sources: HashMap<String, Expr>,
    /// The WITH name a binding is actually emitted under. Two `for` bodies may
    /// each declare `line`; one WITH clause cannot hold that name twice, so the
    /// second is emitted under a suffixed one and every reference to it reads
    /// from here.
    cte_sql_names: HashMap<String, String>,
    /// Every WITH name this statement will carry, whoever asked for it — a
    /// user binding, a loop's iterator, a hoisted mutation. One set so no two
    /// can claim the same name and no guard has to know about the others.
    cte_namespace: std::collections::HashSet<String>,
    /// Loop slots whose variable has been read since the last time this was
    /// cleared — see `for_var_ref`.
    for_vars_read: std::collections::HashSet<String>,
    /// The loops whose bodies are being compiled, innermost last.
    for_scope: Vec<String>,
    /// `(through type, junction alias)` of the multi-link whose own
    /// modifiers are being compiled — what a bare `@prop` in `filter
    /// (@primary = true)` resolves against. `None` on the stack means a link
    /// with no through type, which has no link properties at all.
    link_prop_scope: Vec<Option<(String, String)>>,
    /// Set when `compile_stmt` strips a select-level `detached`, and taken by
    /// the `compile_path_modifiers` that compiles that select's own clauses.
    pending_detached: bool,
    /// Set while a path continues past a sub-select's own subject, e.g. the
    /// `.plan.tier` of `(select .licences filter not exists .ended_at limit
    /// 1).plan.tier`: the subject's landing row is what FILTER/ORDER BY/LIMIT
    /// scope to, not the type the whole path ends on.
    modifier_anchor: Option<(String, String)>,
    /// WITH bindings that name a path off the enclosing object. They read that
    /// object's alias, which a CTE emitted ahead of the FROM clause cannot
    /// see, so they stand in for their value wherever the name is used.
    inline_bindings: std::collections::HashMap<String, IrExpr>,
    /// True while compiling a `@pylon.function` body. A session global cannot
    /// be a query parameter there — a `CREATE FUNCTION` body has nothing to
    /// bind one to — so it is read out of the `__pylon_json_globals__`
    /// argument instead. See `GLOBALS_ARG`.
    in_fn_body: bool,
    /// Qualified names of functions that take the globals argument, so a call
    /// to one can be given it.
    ///
    /// Computed on first use rather than up front: working it out means
    /// compiling every function body in the schema, and the overwhelming
    /// majority of queries never call a user function at all. Function-body
    /// compilation seeds it explicitly (`compile_fn_body_with`), which is also
    /// what keeps the fixpoint from recursing into itself.
    fns_needing_globals: Option<std::collections::HashSet<String>>,
    /// Set when this body read a global or forwarded the argument to a callee
    /// — i.e. when the function being compiled needs the argument itself.
    used_globals_arg: bool,
    /// User-defined function parameters in scope (only set during body compilation).
    fn_params: HashMap<String, String>,
    /// `__new__`/`__old__` row-context bindings, only set during trigger-handler
    /// compilation (`compile_trigger_handler`) — maps the anchor name to
    /// *the trigger's own type* and the table alias its properties/links
    /// should resolve against (`"NEW"`/`"OLD"`). Stored explicitly (not just
    /// the alias string) because `__new__.x`/`__old__.x` can appear nested
    /// inside a sub-statement targeting a *different* type (e.g. `insert Note
    /// { note := __new__.name }` — the ambient `td` at that point is `Note`,
    /// not the trigger's own type), so resolution can't rely on whatever
    /// `td` happens to be in scope where the anchor is used. An anchor not
    /// legal for the trigger's `on` mask (e.g. `__old__` in an Insert-only
    /// trigger) is simply absent from this map, and fails resolution the
    /// same way any other unknown identifier does.
    special_anchors: HashMap<String, (&'a TypeDescriptor, String)>,
    /// Global CTEs collected during compilation (session and computed), in dependency order.
    global_ctes: Vec<IrGlobalCte>,
    /// Nested DML hoisted out of a link-assignment value currently being
    /// compiled (`author := (select (insert Person {...}) { id })`) — see
    /// `compile_link_subquery`'s doc comment. `compile_insert`/
    /// `compile_update` save-and-clear this on entry and drain it back into
    /// their own `IrInsert`/`IrUpdate::nested_ctes` on exit, so nesting
    /// (a nested insert whose own link value nests another insert) attaches
    /// each level's discoveries to the right statement.
    pending_nested_ctes: Vec<IrCteDef>,
    /// Junction tables this statement also *writes*, mapped to the CTE that
    /// wrote them — installed only while a walk off a hoisted mutation is
    /// being compiled. Postgres does not show a sibling CTE's inserts in the
    /// base table, so `(update T set { multi += … }).multi` has to read the
    /// rows back out of the append CTE or it sees none of them.
    junction_read_overrides: HashMap<String, JunctionReadOverride>,
    nested_cte_counter: usize,
    /// Non-fatal warnings collected during compilation.
    warnings: Vec<String>,
    /// Depth of `any()`/`all()` arguments currently being compiled. Wrapping a
    /// set-valued comparison in one of those *is* the explicit intent the
    /// multi-link FILTER warning asks for, so the warning stays quiet inside.
    explicit_set_depth: usize,
    /// User-configurable session options — see `SessionConfig`. Always
    /// `default()` for every entry point except `compile_with_config`.
    config: crate::ir::SessionConfig,
    /// Whether a shape compiled right now gets an `id` it did not ask for —
    /// see `prepend_implicit_id`. True at the top level and cleared, Gel-style,
    /// for the two places Gel clears it: a mutation's own body, where a link
    /// value compiles to a one-column correlated subquery that a second column
    /// would break, and under a cast to `json`, which is an output sink whose
    /// text an added key would change.
    implicit_id_in_shapes: bool,
}

/// One schema-bound select in the enclosing chain — see `Compiler::anchors`.
struct SelectAnchor {
    type_name: String,
    qualified: String,
    alias: String,
    detached: bool,
    /// The ancestor an inherited computed is declared on, set only for the
    /// anchor that computed is compiled under.
    ///
    /// Gel compiles a computed once, against the type that declares it, so
    /// `BrandAddon.bundle := (BrandAddon is BrandAddonBundle)` reads its own
    /// row there and keeps doing so through every subtype that inherits it.
    /// Pylon materialises an inherited computed onto each subtype and compiles
    /// it again there, where `BrandAddon` no longer names the subject -- and a
    /// bare type name that anchors nothing reads the whole table. Naming a
    /// supertype does *not* otherwise mean the subject (confirmed against Gel:
    /// `select BrandAddonBundle { n := count(BrandAddon) }` is the full count,
    /// while the same shape naming `BrandAddonBundle` is 1), so this is scoped
    /// to the one anchor rather than folded into the general name match.
    declared_on: Option<(String, String)>,
}

impl SelectAnchor {
    /// Whether this anchor answers to `root` as a path root.
    fn answers_to(&self, root: &str) -> bool {
        self.type_name == root
            || self.qualified == root
            || self
                .declared_on
                .as_ref()
                .is_some_and(|(name, qualified)| name == root || qualified == root)
    }
}

/// The synthetic argument carrying session globals into a function body.
///
/// A session global is normally a query parameter, which a `CREATE FUNCTION`
/// body cannot have — it would emit a bare `$1` nothing binds. Following Gel's
/// `__edb_json_globals__`, the caller packs the globals into one jsonb value
/// and passes it as a leading argument. One opaque argument rather than one
/// per global keeps the function's signature independent of which globals its
/// body happens to mention, so editing a body does not churn its signature
/// (and, with PostgreSQL overloading, leave a stale one behind).
pub const GLOBALS_ARG: &str = "__pylon_json_globals__";

/// SQL reading one global out of `GLOBALS_ARG`.
fn globals_arg_read(qualified: &str, pg_type: &str) -> String {
    let key = qualified.replace('\'', "''");
    if let Some(element) = pg_type.strip_suffix("[]") {
        // `->>` would hand back the JSON array's text, not an array, so the
        // elements are unpacked instead. The `jsonb_typeof` guard matters: an
        // unset global arrives as JSON null, and unpacking that raises "cannot
        // extract elements from a scalar". The `coalesce` keeps an empty array
        // an empty array rather than letting `array_agg` turn it into NULL.
        format!(
            "(case when jsonb_typeof({GLOBALS_ARG} -> '{key}') = 'array' \
             then coalesce((select array_agg(value::{element}) \
             from jsonb_array_elements_text({GLOBALS_ARG} -> '{key}') as value), '{{}}'::{pg_type}) \
             else null end)"
        )
    } else {
        format!("(({GLOBALS_ARG} ->> '{key}')::{pg_type})")
    }
}

impl<'a> Compiler<'a> {
    fn new(schema: &'a SchemaDescriptor) -> Self {
        Self::with_config(schema, crate::ir::SessionConfig::default())
    }

    fn with_config(schema: &'a SchemaDescriptor, config: crate::ir::SessionConfig) -> Self {
        Compiler {
            schema,
            params: vec![],
            alias_counter: 0,
            cte_types: HashMap::new(),
            group_bindings: HashMap::new(),
            cte_free_items: HashMap::new(),
            multi_row_ctes: HashSet::new(),
            for_vars: HashMap::new(),
            for_var_types: HashMap::new(),
            for_var_ctes: HashMap::new(),
            for_var_slots: HashMap::new(),
            pending_insert_guard: None,
            pending_update_guard: None,
            pending_delete_guard: None,
            cte_declared_pointers: HashMap::new(),
            active_declared_pointers: vec![],
            expanding_computeds: vec![],
            fn_params: HashMap::new(),
            special_anchors: HashMap::new(),
            global_ctes: vec![],
            pending_nested_ctes: vec![],
            junction_read_overrides: HashMap::new(),
            nested_cte_counter: 0,
            warnings: vec![],
            explicit_set_depth: 0,
            config,
            implicit_id_in_shapes: true,
            anchors: Vec::new(),
            link_prop_scope: Vec::new(),
            hoisted_ctes: Vec::new(),
            hoisted_binding_sources: HashMap::new(),
            cte_sql_names: HashMap::new(),
            cte_namespace: std::collections::HashSet::new(),
            for_vars_read: std::collections::HashSet::new(),
            for_scope: Vec::new(),
            pending_detached: false,
            modifier_anchor: None,
            inline_bindings: std::collections::HashMap::new(),
            in_fn_body: false,
            fns_needing_globals: None,
            used_globals_arg: false,
        }
    }

    /// Register a compiled WITH binding under `name`: records its type (or
    /// empty string for a free binding) in `cte_types`, and — when it's a
    /// single free row — its `IrFreeExpr` in `cte_free_items` so a later
    /// `name.field` reference can resolve to `IrExpr::CteFieldRef`.
    /// True when `name` is bound to a value rather than to an object set —
    /// a scalar WITH binding, or one inlined by `bind_inline_if_correlated`.
    fn is_value_binding(&self, name: &str) -> bool {
        self.inline_bindings.contains_key(name) || self.cte_types.get(name).is_some_and(|t| !t.contains("::"))
    }

    /// Bind `name` to the value of a relative path off the enclosing object —
    /// `with handle_id := .id`. Returns false when the binding is anything
    /// else, which the caller hoists into a CTE as usual.
    /// `ctx` is the row the enclosing sub-select is correlated to, when it
    /// has one: a relative path in its bindings reads that row, not whichever
    /// select happens to enclose it.
    fn bind_inline_if_correlated(
        &mut self,
        name: &str,
        expr: &Expr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<bool, PyQLError> {
        if (self.anchors.is_empty() && ctx.is_none()) || !matches!(expr, Expr::Path(p) if p.partial) {
            return Ok(false);
        }
        let ir = self.compile_expr_ctx(expr, ctx)?;
        self.inline_bindings.insert(name.to_string(), ir);
        Ok(true)
    }

    /// The WITH name `name` is emitted under — itself, unless it collided.
    fn cte_sql_name(&self, name: &str) -> String {
        self.cte_sql_names
            .get(name)
            .cloned()
            .unwrap_or_else(|| name.to_string())
    }

    /// Compile a `with` binding, reporting the loop slot it reads if it reads
    /// one. A binding that names the loop variable holds a different value
    /// each iteration, which is not something a statement-level CTE can be.
    fn compile_binding_in_scope(&mut self, expr: &Expr) -> Result<(IrStmt, Option<String>), PyQLError> {
        let before = std::mem::take(&mut self.for_vars_read);
        let ir_stmt = compile_cte_binding(self, expr);
        let read = std::mem::replace(&mut self.for_vars_read, before);
        // The innermost loop read is the one it belongs to; an outer loop's
        // variable is reachable from there anyway.
        let correlated_to = self
            .for_scope
            .iter()
            .rev()
            .find(|slot| read.contains(*slot))
            .map(|slot| format!("_for_{slot}"));
        self.for_vars_read.extend(read);
        Ok((ir_stmt?, correlated_to))
    }

    /// Claim a WITH name, suffixing `base` until it is free. Names the SQL
    /// emitter derives from a claimed one — `x__ids`, `x__rows`,
    /// `x__ml_add_0` — are claimed with it, which is why anything under a
    /// taken name's `__` prefix counts as taken too.
    fn claim_in_cte_namespace(&mut self, base: &str) -> String {
        // A suffixed candidate is itself an extension of `base`, so `base` is
        // the one claimed name that never rules its own suffixes out.
        let taken = |namespace: &std::collections::HashSet<String>, candidate: &String| {
            namespace.contains(candidate)
                || namespace
                    .iter()
                    .any(|claimed| claimed != base && candidate.starts_with(&format!("{claimed}__")))
        };
        let mut candidate = base.to_string();
        let mut suffix = 1;
        while taken(&self.cte_namespace, &candidate) {
            candidate = format!("{base}__{suffix}");
            suffix += 1;
        }
        self.cte_namespace.insert(candidate.clone());
        candidate
    }

    /// Claim a WITH name the compiler spelled itself — a loop's iterator, a
    /// hoisted mutation. These already live in the underscore-prefixed space
    /// that user names are kept out of, so they are claimed as written.
    fn claim_generated_cte_name(&mut self, preferred: &str) -> String {
        self.claim_in_cte_namespace(preferred)
    }

    /// Claim a WITH name for a `with` binding, recording the name to read it
    /// back by when the one it asked for was already spoken for.
    fn claim_cte_sql_name(&mut self, name: &str) -> String {
        // Every generated WITH name starts with an underscore. Keeping user
        // names out of that space is what makes the two sets disjoint, so a
        // binding named `_dml` cannot collide with the wrapper of that name.
        let base = match name.starts_with('_') {
            true => format!("w{name}"),
            false => name.to_string(),
        };
        let claimed = self.claim_in_cte_namespace(&base);
        if claimed == name {
            self.cte_sql_names.remove(name);
        } else {
            self.cte_sql_names.insert(name.to_string(), claimed.clone());
        }
        claimed
    }

    fn register_cte(&mut self, name: &str, ir_stmt: &IrStmt) -> String {
        let type_name = cte_stmt_type(ir_stmt);
        self.cte_types.insert(name.to_string(), type_name.clone());
        if let IrStmt::Select(sel) = ir_stmt
            && let [IrRowSource::Free(item)] = sel.rows.as_slice()
        {
            self.cte_free_items.insert(name.to_string(), item.clone());
        }
        self.note_cte_cardinality(name, ir_stmt);
        type_name
    }

    /// True when `sel`'s filter pins an exclusive property to one value, which
    /// makes it single-valued however many rows the table holds. Gel makes the
    /// same inference, and it is why
    /// `(select Installation filter .id = <uuid>$x).connector.provider.staff`
    /// is a value there rather than a one-element set.
    fn pins_an_exclusive_property(&self, sel: &IrSelect) -> bool {
        let [IrRowSource::Bound { source, .. }] = sel.rows.as_slice() else {
            return false;
        };
        let Some(filter) = &sel.filter else { return false };
        let Ok(td) = self.resolve_type(&source.type_name) else {
            return false;
        };
        Self::pins_exclusive(td, filter)
    }

    /// Walks the conjuncts of `filter` for an equality against an exclusive or
    /// primary-key column. Only `and` is descended: under `or` either side
    /// could match a different row, so neither pins anything.
    fn pins_exclusive(td: &TypeDescriptor, filter: &IrExpr) -> bool {
        let IrExpr::BinOp(binop) = filter else { return false };
        match binop.op {
            ast::BinOpKind::And => Self::pins_exclusive(td, &binop.left) || Self::pins_exclusive(td, &binop.right),
            ast::BinOpKind::Eq => {
                let column = match (&binop.left, &binop.right) {
                    (IrExpr::ColumnRef { column, .. }, _) => column,
                    (_, IrExpr::ColumnRef { column, .. }) => column,
                    _ => return false,
                };
                td.properties
                    .iter()
                    .any(|p| &p.name == column && (p.is_exclusive || p.is_pk))
            }
            _ => false,
        }
    }

    /// Record `name` when its binding can hold more than one row, so a later
    /// comparison against it compiles to membership rather than a scalar
    /// subquery read. Anything whose row count isn't statically one counts as
    /// multi: a needless membership test still answers correctly, a needless
    /// scalar read aborts the query.
    fn note_cte_cardinality(&mut self, name: &str, ir_stmt: &IrStmt) {
        let single = match ir_stmt {
            IrStmt::Insert(_) => true,
            IrStmt::Select(sel) => {
                matches!(sel.limit, Some(IrExpr::Literal(IrLiteral::Int(1))))
                    || matches!(
                        sel.rows.as_slice(),
                        [IrRowSource::Free(
                            IrFreeExpr::Scalar(_)
                                | IrFreeExpr::FreeObject(_)
                                | IrFreeExpr::NamedTupleRow(_)
                                | IrFreeExpr::Tuple(_)
                        )]
                    )
                    || self.pins_an_exclusive_property(sel)
            }
            _ => false,
        };
        if !single {
            self.multi_row_ctes.insert(name.to_string());
        }
    }

    /// Resolve `root.field1.field2. ... fieldN` where `root` is a WITH-bound
    /// free object (e.g. `with x := { a := { b := 1 } } select x.a.b`) —
    /// `None` when `root` isn't such a binding, so callers fall back to
    /// their normal path resolution. The first step reads the CTE's own
    /// per-field column (`IrExpr::CteFieldRef`, materialized once); any
    /// further steps index into that value as jsonb (`IrExpr::JsonbField`),
    /// since a nested free-object *field* is jsonb the moment it's not the
    /// top-level row itself — validated statically wherever the nesting is
    /// itself a free-object literal (so a typo like `x.a.typo` still gets a
    /// compile error instead of silently returning SQL NULL).
    fn resolve_cte_field_chain(&self, root: &str, steps: &[&str]) -> Option<Result<IrExpr, PyQLError>> {
        let (first, rest) = steps.split_first()?;
        let fields = match self.cte_free_items.get(root)? {
            IrFreeExpr::FreeObject(fields) => fields,
            _ => return None,
        };
        let mut current: &IrExpr = match fields.iter().find(|(n, _)| n == first) {
            Some((_, e)) => e,
            None => {
                return Some(Err(
                    self.type_err(&format!("free object '{root}' has no field '{first}'"))
                ));
            }
        };
        let mut expr = IrExpr::CteFieldRef {
            name: root.to_string(),
            field: first.to_string(),
            pg_type: infer_ir_type(current).map(str::to_string),
        };
        for step in rest {
            if let IrExpr::NamedTuple {
                fields: nested,
                is_free_object: true,
            } = current
            {
                match nested.iter().find(|(n, _)| n == step) {
                    Some((_, next)) => current = next,
                    None => {
                        return Some(Err(
                            self.type_err(&format!("{step} is not a member of the nested free object"))
                        ));
                    }
                }
            }
            expr = IrExpr::JsonbField {
                expr: Box::new(expr),
                field: step.to_string(),
            };
        }
        Some(Ok(expr))
    }

    /// `resolve_cte_field_chain`, but taking the whole `root.f1.f2...` path
    /// directly — `None` when the path isn't an absolute multi-step name
    /// chain (so, in particular, whenever a step is anything other than a
    /// plain name, e.g. a type intersection or backlink).
    fn resolve_cte_path(&self, p: &ast::Path) -> Option<Result<IrExpr, PyQLError>> {
        if p.partial || p.steps.len() < 2 {
            return None;
        }
        let ast::PathStep::Name(root) = &p.steps[0] else {
            return None;
        };
        let mut steps = Vec::with_capacity(p.steps.len() - 1);
        for step in &p.steps[1..] {
            match step {
                ast::PathStep::Name(n) => steps.push(n.as_str()),
                _ => return None,
            }
        }
        self.resolve_cte_field_chain(root, &steps)
    }

    /// Return the CTE name if `expr` is a bare identifier that matches a registered CTE.
    fn resolve_cte_name<'e>(&self, expr: &'e Expr) -> Option<&'e str> {
        if let Expr::Path(p) = expr
            && !p.partial
            && p.steps.len() == 1
            && let ast::PathStep::Name(n) = &p.steps[0]
            && self.cte_types.contains_key(n.as_str())
        {
            return Some(n.as_str());
        }
        None
    }

    /// A reference to the loop variable `name`, under the CTE name its loop
    /// was emitted with. Recorded as read, which is what tells a `with`
    /// binding compiled around it that it belongs to one iteration rather
    /// than to the statement.
    fn for_var_ref(&mut self, name: &str) -> IrExpr {
        let slot = self
            .for_var_slots
            .get(name)
            .cloned()
            .unwrap_or_else(|| name.to_string());
        self.for_vars_read.insert(slot.clone());
        let pg_type = self.for_vars.get(name).cloned();
        IrExpr::ForVar { name: slot, pg_type }
    }

    fn fresh_alias(&mut self) -> String {
        let a = format!("t{}", self.alias_counter);
        self.alias_counter += 1;
        a
    }

    /// A distinct naming scheme from `fresh_alias`'s `t0`, `t1`, ... (table
    /// aliases) so a hoisted nested-DML CTE name can never collide with one
    /// — see `pending_nested_ctes`.
    fn fresh_nested_cte_name(&mut self) -> String {
        let n = self.nested_cte_counter;
        self.nested_cte_counter += 1;
        self.claim_generated_cte_name(&format!("_nested_dml_{n}"))
    }

    /// Register a named parameter and return its 0-based index.
    fn param_index(&mut self, name: &str) -> usize {
        if let Some(i) = self.params.iter().position(|n| n == name) {
            return i;
        }
        let i = self.params.len();
        self.params.push(name.to_string());
        i
    }

    // ── Global variable resolution ────────────────────────────────────────────────

    /// `scalar_type` is a PyQL-style type-name string built by the Python
    /// walker's `_pyql_type_name` (e.g. `"std::str"`, `"std::uuid"`,
    /// `"cal::local_date"`, `"default::Gender"`, `"array<std::str>"`) — never
    /// a bare Python class name. Mirrors every shape `_pyql_type_name` can
    /// produce for a `Global[T]` annotation.
    fn resolve_global_pg_type(&self, scalar_type: &str) -> String {
        // `datetime` and `std::datetime` name the same type.
        let builtin = match scalar_type.strip_prefix("std::").unwrap_or(scalar_type) {
            "str" => Some("text"),
            "int16" => Some("int2"),
            "int32" => Some("int4"),
            "int64" => Some("int8"),
            "float32" => Some("float4"),
            "float64" => Some("float8"),
            "decimal" => Some("numeric"),
            "bool" => Some("boolean"),
            "datetime" => Some("timestamptz"),
            "cal::local_datetime" => Some("timestamp"),
            "cal::local_date" => Some("date"),
            "cal::local_time" => Some("time"),
            "uuid" => Some("uuid"),
            "bytes" => Some("bytea"),
            "json" => Some("jsonb"),
            "duration" => Some("interval"),
            _ => None,
        };
        if let Some(t) = builtin {
            return t.to_string();
        }
        if let Some(inner) = scalar_type.strip_prefix("array<").and_then(|s| s.strip_suffix('>')) {
            return format!("{}[]", self.resolve_global_pg_type(inner));
        }
        if scalar_type.starts_with("tuple<") {
            return "jsonb".to_string();
        }
        if let Some(ed) = self.resolve_enum(scalar_type) {
            return format!("{}.\"{}\"", crate::sql::pg_schema_str(&ed.module), ed.name);
        }
        if self.resolve_named_tuple(scalar_type).is_some() {
            return "jsonb".to_string();
        }
        // Fall back to a registered custom scalar lookup.
        self.schema
            .scalars
            .iter()
            .find(|s| s.name == scalar_type || format!("{}::{}", s.module, s.name) == scalar_type)
            .map(|s| s.pg_type.clone())
            .unwrap_or_else(|| "text".to_string())
    }

    /// When `global name` (or `global name { shape }`) appears as the top-level
    /// SELECT subject, inline the computed expression rather than going through a
    /// CTE — this returns a full object, not just its id.
    fn try_compile_global_select(
        &mut self,
        outer: &ast::SelectStmt,
        result: &Expr,
        _distinct: bool,
    ) -> Result<Option<IrStmt>, PyQLError> {
        let (global_name, shape_elements): (&str, &[ast::ShapeElement]) = match result {
            Expr::Global(name) => (name.as_str(), &[]),
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(Expr::Global(name)) => (name.as_str(), sh.elements.as_slice()),
                _ => return Ok(None),
            },
            _ => return Ok(None),
        };

        let global = self
            .schema
            .globals
            .iter()
            .find(|g| g.name == global_name || format!("{}::{}", g.module, g.name) == global_name);
        let global = match global {
            Some(g) => g.clone(),
            None => return Ok(None),
        };
        let computed_expr = match global.computed_expr {
            Some(e) => e,
            None => return Ok(None), // scalar session global — fall through
        };

        let inner_ast = crate::parse::parse(&computed_expr)?;
        let inner_sel = match inner_ast {
            Stmt::Select(sel) => sel,
            _ => return Ok(None),
        };

        let merged_result = if shape_elements.is_empty() {
            inner_sel.result.clone()
        } else {
            Expr::Shape(Box::new(ast::ShapeExpr {
                expr: Some(inner_sel.result.clone()),
                elements: shape_elements.to_vec(),
                marker_offset: None,
            }))
        };

        let merged_filter = match (&inner_sel.filter, &outer.filter) {
            (Some(a), Some(b)) => Some(Expr::BinOp(Box::new(ast::BinOp {
                left: a.clone(),
                op: ast::BinOpKind::And,
                right: b.clone(),
            }))),
            (Some(a), None) => Some(a.clone()),
            (None, b) => b.clone(),
        };

        let merged = ast::SelectStmt {
            result: merged_result,
            filter: merged_filter,
            order_by: if outer.order_by.is_empty() {
                inner_sel.order_by.clone()
            } else {
                outer.order_by.clone()
            },
            offset: outer.offset.clone().or(inner_sel.offset.clone()),
            limit: outer.limit.clone().or(inner_sel.limit.clone()),
            lock: outer.lock.clone().or(inner_sel.lock.clone()),
        };

        let ir = self.compile_stmt(&Stmt::Select(merged))?;
        Ok(Some(ir))
    }

    /// Reading one field off a free object. Gel compiles a free shape into a
    /// real object type, so `{ device := d { id }, … }.device` is an ordinary
    /// path step through a pointer and yields whatever that pointer holds —
    /// an object stays an object. Extracting it out of the jsonb the free
    /// object would otherwise build flattens it back to raw JSON. Any field
    /// left unread still runs: a mutation among them is a data-modifying CTE,
    /// which Postgres executes whether or not the outer query reads it.
    fn project_free_object_field(expr: IrExpr, field: &str) -> IrExpr {
        if let IrExpr::NamedTuple {
            fields,
            is_free_object: true,
        } = &expr
            && let Some((_, value)) = fields.iter().find(|(name, _)| name == field)
        {
            return value.clone();
        }
        IrExpr::JsonbField {
            expr: Box::new(expr),
            field: field.to_string(),
        }
    }

    /// The operands of a union written entirely of relative paths, which are
    /// correlated to the enclosing row and so cannot be hoisted.
    fn union_of_relative_paths(expr: &Expr) -> Option<Vec<ast::Path>> {
        fn walk(expr: &Expr, out: &mut Vec<ast::Path>) -> bool {
            match expr {
                Expr::Union(a, b) => walk(a, out) && walk(b, out),
                Expr::Path(p) if p.partial => {
                    out.push(p.clone());
                    true
                }
                _ => false,
            }
        }
        if !matches!(expr, Expr::Union(_, _)) {
            return None;
        }
        let mut out = vec![];
        walk(expr, &mut out).then_some(out)
    }

    /// `([is Conditional].configs ?? [is Loop].configs)` — the operands of a
    /// coalesce, when every one is a path off the enclosing row. Unlike a
    /// union each operand but the first only contributes when the ones before
    /// it are empty, which is what the caller guards them with.
    fn coalesce_of_relative_paths(expr: &Expr) -> Option<Vec<ast::Path>> {
        fn walk(expr: &Expr, out: &mut Vec<ast::Path>) -> bool {
            match expr {
                Expr::BinOp(b) if b.op == ast::BinOpKind::Coalesce => walk(&b.left, out) && walk(&b.right, out),
                Expr::Path(p) if p.partial => {
                    out.push(p.clone());
                    true
                }
                _ => false,
            }
        }
        if !matches!(expr, Expr::BinOp(b) if b.op == ast::BinOpKind::Coalesce) {
            return None;
        }
        let mut out = vec![];
        walk(expr, &mut out).then_some(out)
    }

    /// `(select Licence filter …) { id }` — a shape written after a
    /// parenthesised sub-select rather than inside it.
    ///
    /// The two mean the same thing, so the shape is pushed onto the inner
    /// statement's own result and the whole thing compiled as the select it
    /// already was. A `with` block is carried through to its inner statement.
    fn shape_over_subquery(&mut self, sh: &ast::ShapeExpr) -> Result<Option<IrExpr>, PyQLError> {
        fn push_shape(stmt: &Stmt, elements: &[ShapeElement]) -> Option<Stmt> {
            match stmt {
                Stmt::Select(sel) => {
                    if matches!(sel.result, Expr::Shape(_)) {
                        return None;
                    }
                    let mut shaped = sel.clone();
                    shaped.result = Expr::Shape(Box::new(ast::ShapeExpr {
                        expr: Some(sel.result.clone()),
                        elements: elements.to_vec(),
                        marker_offset: None,
                    }));
                    Some(Stmt::Select(shaped))
                }
                Stmt::With(w) => {
                    let inner = push_shape(&w.stmt, elements)?;
                    let mut carried = w.clone();
                    carried.stmt = Box::new(inner);
                    Some(Stmt::With(carried))
                }
                _ => None,
            }
        }
        let Some(Expr::SubQuery(stmt)) = sh.expr.as_ref() else {
            return Ok(None);
        };
        let Some(shaped) = push_shape(stmt.as_ref(), &sh.elements) else {
            return Ok(None);
        };
        let single = matches!(
            innermost_select(&shaped).and_then(|s| s.limit.as_ref()),
            Some(Expr::Literal(ast::Literal::Int(1)))
        );
        let IrStmt::Select(select) = self.compile_stmt(&shaped)? else {
            return Ok(None);
        };
        if !matches!(select.rows.as_slice(), [IrRowSource::Bound { .. }]) {
            return Ok(None);
        }
        Ok(Some(if single {
            IrExpr::ObjectSubquery(Box::new(select))
        } else {
            IrExpr::ArrayFromSelect(Box::new(IrArraySource::ObjectSelect(Box::new(select))))
        }))
    }

    /// `(select … limit 1).account { id, name }` — a shape written on what a
    /// projection off a sub-select lands on. Returns the sub-statement and
    /// the field chain, so the shape can ride along with the splice instead
    /// of being rejected as a shape in expression position.
    fn shape_over_subquery_projection(sh: &ast::ShapeExpr) -> Option<(&Stmt, Vec<String>)> {
        let inner = sh.expr.as_ref()?;
        if !matches!(inner, Expr::FieldAccess { .. }) {
            return None;
        }
        let (base, fields) = Self::peel_field_access_chain(inner);
        match base {
            Expr::SubQuery(stmt) => Some((stmt.as_ref(), fields)),
            _ => None,
        }
    }

    /// Peel nested `Expr::FieldAccess` layers (`X.a.b` parses as
    /// `FieldAccess{FieldAccess{X, "a"}, "b"}`) into the innermost root
    /// expression plus the ordered chain of field names.
    /// The junction tables `dml` writes, mapped to the CTE the emitter names
    /// for each append (`{cte}__ml_add_{i}`, see `emit_ml_append_cte`). A walk
    /// off that mutation reads them from there, because Postgres shows a
    /// sibling CTE's inserts nowhere else. Only appends carrying no link
    /// properties qualify: the append CTE returns just the two id columns, so
    /// a walk reading `@prop` off one would name a column it does not have.
    fn junction_overrides_for(dml: &IrStmt, cte_name: &str) -> HashMap<String, JunctionReadOverride> {
        let appends = match dml {
            IrStmt::Insert(ins) => &ins.multi_link_appends,
            IrStmt::Update(upd) => &upd.multi_link_appends,
            _ => return HashMap::new(),
        };
        appends
            .iter()
            .enumerate()
            .filter(|(_, append)| append.values.link_props.is_empty())
            .map(|(i, append)| {
                // The targets themselves may also have been inserted by this
                // statement, in which case they are only in their own CTE too.
                let targets = match &append.values.source {
                    IrMultiLinkValueSource::CteRef(target_cte) => Some(format!("@cte:{target_cte}")),
                    _ => None,
                };
                (
                    append.junction_table.clone(),
                    JunctionReadOverride {
                        junction: format!("@cte:{cte_name}__ml_add_{i}"),
                        targets,
                    },
                )
            })
            .collect()
    }

    /// `(select …).provider[is Individual].staff` — a walk off a sub-select
    /// that includes a step with no expression form of its own. The select is
    /// hoisted into the statement's own WITH and the walk re-rooted at that
    /// binding, which is the `with i := (select …) select i.provider[is …].staff`
    /// spelling that already compiles.
    ///
    /// `None` when this is not that shape — in particular a walk made only of
    /// `.field` steps, which the `FieldAccess` arm already handles and must go
    /// on handling: re-rooting one of those reads the trailing field as jsonb
    /// off an object id instead of as a column.
    fn try_compile_walk_off_subquery(
        &mut self,
        expr: &Expr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<Option<IrExpr>, PyQLError> {
        if !matches!(expr, Expr::PathStepOn { .. } | Expr::FieldAccess { .. }) {
            return Ok(None);
        }
        let (base, steps) = Self::peel_path_step_chain(expr);
        if !steps.iter().any(|step| !matches!(step, ast::PathStep::Name(_))) {
            return Ok(None);
        }
        let Expr::SubQuery(inner_stmt) = base else {
            return Ok(None);
        };
        // Bound exactly as a `with` alias would be, not via `compile_stmt`.
        let inner = compile_cte_binding(self, &Expr::SubQuery(inner_stmt.clone()))?;
        let cte_name = self.fresh_nested_cte_name();
        let overrides = Self::junction_overrides_for(&inner, &cte_name);
        let type_name = self.register_cte(&cte_name, &inner);
        self.hoisted_ctes.push(IrCteDef {
            name: cte_name.clone(),
            stmt: inner,
            type_name,
            correlated_to: None,
        });
        let mut path_steps = vec![ast::PathStep::Name(cte_name)];
        path_steps.extend(steps);
        let path = ast::Path {
            steps: path_steps,
            partial: false,
        };
        let previous = std::mem::replace(&mut self.junction_read_overrides, overrides);
        let ir = match ctx {
            Some((td, alias)) => self.compile_path(&path, td, alias),
            None => self.compile_free_path(&path),
        };
        self.junction_read_overrides = previous;
        Ok(Some(ir?))
    }

    /// Peel a mixed `.field` / `[is T]` / `@prop` / `.<backlink` walk off a
    /// base that is not itself a path, outermost step last. The counterpart of
    /// `peel_field_access_chain` for a chain that contains a step with no
    /// expression form of its own (see `ast::Expr::PathStepOn`).
    fn peel_path_step_chain(expr: &Expr) -> (&Expr, Vec<ast::PathStep>) {
        let mut steps = Vec::new();
        let mut current = expr;
        loop {
            match current {
                Expr::FieldAccess { expr: inner, field } => {
                    steps.push(ast::PathStep::Name(field.clone()));
                    current = inner;
                }
                Expr::PathStepOn { expr: inner, step } => {
                    steps.push((**step).clone());
                    current = inner;
                }
                _ => break,
            }
        }
        steps.reverse();
        (current, steps)
    }

    fn peel_field_access_chain(expr: &Expr) -> (&Expr, Vec<String>) {
        let mut fields = Vec::new();
        let mut current = expr;
        while let Expr::FieldAccess { expr: inner, field } = current {
            fields.push(field.clone());
            current = inner;
        }
        fields.reverse();
        (current, fields)
    }

    /// Resolve `expr` to the inner `select Type filter ...` statement it
    /// stands for, if any — either a literal subquery (`(select Type filter
    /// ...)`) or a computed global whose defining expression is such a
    /// select. Only bare object-type results are recognized (`select Type
    /// ...`, not `select Type { shape }` or a free expression) — that's the
    /// only shape `.field` access after it can be spliced onto as an
    /// additional path step.
    fn resolve_field_owner_select(&self, expr: &Expr) -> Option<ast::SelectStmt> {
        let sel = match expr {
            Expr::SubQuery(stmt) => match stmt.as_ref() {
                Stmt::Select(sel) => sel.clone(),
                _ => return None,
            },
            Expr::Global(name) => {
                let global = self
                    .schema
                    .globals
                    .iter()
                    .find(|g| g.name == *name || format!("{}::{}", g.module, g.name) == *name)?;
                let computed_expr = global.computed_expr.as_ref()?;
                match crate::parse::parse(computed_expr).ok()? {
                    Stmt::Select(sel) => sel,
                    _ => return None,
                }
            }
            _ => return None,
        };
        // `(select detached T filter … limit 1).field` — at the top level the
        // marker says nothing a field access changes, and the path underneath
        // is the subject to splice the chain onto.
        let mut sel = sel;
        if let Expr::Detached(inner) = &sel.result {
            sel.result = inner.as_ref().clone();
        }
        match &sel.result {
            Expr::Path(p) if !p.partial => Some(sel),
            _ => None,
        }
    }

    /// `global name.field` or `(select Type filter ...).field` (and deeper
    /// chains like `.link.field`) used as the top-level SELECT subject:
    /// rather than treating `.field` as jsonb extraction on an opaque value
    /// (which only makes sense for tuple-typed properties — see
    /// `resolve_property_tuple_shape`), splice the field chain onto the
    /// inner select as additional path steps and recompile as an ordinary
    /// path-select. Mirrors `try_compile_global_select`'s filter/modifier
    /// merge, generalized to a field-access result instead of a bare/shape
    /// global reference.
    fn try_compile_field_access_select(
        &mut self,
        outer: &ast::SelectStmt,
        result: &Expr,
    ) -> Result<Option<IrStmt>, PyQLError> {
        // `(select T).chapter { … }` — the parser folds a trailing shape around
        // the whole field access, so the chain has to be peeled out of it or
        // the select reads as one with no type for a subject.
        let (result, trailing_shape): (&Expr, &[ShapeElement]) = match result {
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(inner @ Expr::FieldAccess { .. }) => (inner, sh.elements.as_slice()),
                _ => (result, &[]),
            },
            other => (other, &[]),
        };
        let (root, fields) = Self::peel_field_access_chain(result);
        if fields.is_empty() {
            return Ok(None);
        }
        let inner_sel = match self.resolve_field_owner_select(root) {
            Some(sel) => sel,
            None => return Ok(None),
        };
        let Expr::Path(type_path) = &inner_sel.result else {
            return Ok(None);
        };
        let mut steps = type_path.steps.clone();
        let field_count = fields.len();
        steps.extend(fields.into_iter().map(ast::PathStep::Name));
        let merged_result = Expr::Path(ast::Path { steps, partial: false });

        let merged_filter = match (&inner_sel.filter, &outer.filter) {
            (Some(a), Some(b)) => Some(Expr::BinOp(Box::new(ast::BinOp {
                left: a.clone(),
                op: ast::BinOpKind::And,
                right: b.clone(),
            }))),
            (Some(a), None) => Some(a.clone()),
            (None, b) => b.clone(),
        };

        let merged = ast::SelectStmt {
            result: merged_result,
            filter: merged_filter,
            order_by: if outer.order_by.is_empty() {
                inner_sel.order_by.clone()
            } else {
                outer.order_by.clone()
            },
            offset: outer.offset.clone().or(inner_sel.offset.clone()),
            limit: outer.limit.clone().or(inner_sel.limit.clone()),
            lock: outer.lock.clone().or(inner_sel.lock.clone()),
        };

        // The inner select's own filter and ordering speak about its subject,
        // not about what the field chain projects off it: `(select Individual
        // filter .id = $a).credentials.password` filters Individuals, not
        // Credentials. `tail` is what pins them there. Only safe when the
        // outer select contributed none of its own — the merge folds both
        // into one clause, and an outer filter does belong at the end.
        if outer.filter.is_none() && outer.order_by.is_empty() {
            let Expr::Path(merged_path) = &merged.result else {
                unreachable!("built as a path just above")
            };
            let ps = self.compile_path_select_with_tail(&merged, merged_path, trailing_shape, false, field_count)?;
            return Ok(Some(IrStmt::PathSelect(ps)));
        }

        let merged = if trailing_shape.is_empty() {
            merged
        } else {
            ast::SelectStmt {
                result: Expr::Shape(Box::new(ast::ShapeExpr {
                    expr: Some(merged.result.clone()),
                    elements: trailing_shape.to_vec(),
                    marker_offset: None,
                })),
                ..merged
            }
        };
        let ir = self.compile_stmt(&Stmt::Select(merged))?;
        Ok(Some(ir))
    }

    fn try_compile_alias_select(
        &mut self,
        outer: &ast::SelectStmt,
        result: &Expr,
        distinct: bool,
    ) -> Result<Option<IrStmt>, PyQLError> {
        // Extract the bare path name and any outer shape elements.
        let (path_name, shape_elements): (&str, &[ast::ShapeElement]) = match result {
            Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
                if let ast::PathStep::Name(n) = &p.steps[0] {
                    (n.as_str(), &[])
                } else {
                    return Ok(None);
                }
            }
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(Expr::Path(p)) if !p.partial && p.steps.len() == 1 => {
                    if let ast::PathStep::Name(n) = &p.steps[0] {
                        (n.as_str(), sh.elements.as_slice())
                    } else {
                        return Ok(None);
                    }
                }
                _ => return Ok(None),
            },
            _ => return Ok(None),
        };

        // Match against schema aliases (bare name or module::name).
        let alias = self
            .schema
            .aliases
            .iter()
            .find(|a| a.name == path_name || format!("{}::{}", a.module, a.name) == path_name);
        let alias = match alias {
            Some(a) => a.clone(),
            None => return Ok(None),
        };

        let inner_ast = crate::parse::parse(&alias.expr)?;
        let inner_sel = match inner_ast {
            Stmt::Select(sel) => sel,
            _ => return Err(self.type_err(&format!("alias '{}' expression must be a select statement", alias.name))),
        };

        // Merge outer shape / filter / modifiers over the alias's select.
        // `inner_sel.result` is itself an `Expr::Shape` whenever the
        // alias's own body declares a shape (e.g. `select Type { field }
        // order by ... limit ...`, a legitimate, documented pattern — an
        // alias's own body may combine a shape with modifiers) — wrapping
        // it wholesale as the outer shape's own `expr` would nest a Shape
        // inside a Shape, which the compiler's SELECT-subject resolution
        // rejects ("expected a type name as SELECT subject", confirmed
        // live). The outer shape must bind to the same underlying *type*
        // reference the alias's own shape does, not to the alias's shape
        // node itself — so unwrap through it first.
        let inner_base = match &inner_sel.result {
            Expr::Shape(sh) => sh.expr.clone(),
            other => Some(other.clone()),
        };
        let merged_result = if shape_elements.is_empty() {
            inner_sel.result.clone()
        } else {
            Expr::Shape(Box::new(ast::ShapeExpr {
                expr: inner_base,
                elements: shape_elements.to_vec(),
                marker_offset: None,
            }))
        };

        let merged_filter = match (&inner_sel.filter, &outer.filter) {
            (Some(a), Some(b)) => Some(Expr::BinOp(Box::new(ast::BinOp {
                left: a.clone(),
                op: ast::BinOpKind::And,
                right: b.clone(),
            }))),
            (Some(a), None) => Some(a.clone()),
            (None, b) => b.clone(),
        };

        let merged = ast::SelectStmt {
            result: merged_result,
            filter: merged_filter,
            order_by: if outer.order_by.is_empty() {
                inner_sel.order_by.clone()
            } else {
                outer.order_by.clone()
            },
            offset: outer.offset.clone().or(inner_sel.offset.clone()),
            limit: outer.limit.clone().or(inner_sel.limit.clone()),
            lock: outer.lock.clone().or(inner_sel.lock.clone()),
        };

        let _ = distinct; // alias selects honour the outer distinct if applied
        let ir = self.compile_stmt(&Stmt::Select(merged))?;
        Ok(Some(ir))
    }

    fn compile_global(&mut self, raw_name: &str) -> Result<IrExpr, PyQLError> {
        let global = self
            .schema
            .globals
            .iter()
            .find(|g| g.name == raw_name || format!("{}::{}", g.module, g.name) == raw_name);
        let global = global
            .ok_or_else(|| {
                PyQLError::Resolution(PyQLResolutionError::UnknownField(PyQLUnknownFieldError {
                    message: format!("unknown global: {:?}", raw_name),
                    position: Position { line: 0, col: 0 },
                }))
            })?
            .clone();

        let qualified = format!("{}::{}", global.module, global.name);
        let cte_name = format!("__global__{}", qualified);

        if let Some(computed_expr) = global.computed_expr {
            // Computed global — check for duplicate before compiling
            if self.global_ctes.iter().any(|g| g.cte_name() == cte_name) {
                return Ok(IrExpr::GlobalRef { cte_name });
            }
            // Recursively compile the PyQL expression (shares params and global_ctes)
            let inner_ast = crate::parse::parse(&computed_expr)?;
            let inner_stmt = self.compile_stmt(&inner_ast)?;
            self.global_ctes
                .push(IrGlobalCte::Computed(Box::new(IrComputedGlobalCte {
                    cte_name: cte_name.clone(),
                    qualified_name: qualified,
                    stmt: inner_stmt,
                })));
            Ok(IrExpr::GlobalRef { cte_name })
        } else if self.in_fn_body {
            // Inside a function body there is no parameter to bind, so the
            // value is read out of the `__pylon_json_globals__` argument the
            // caller packs. Mirrors Gel's `__edb_json_globals__`.
            let pg_type = self.resolve_global_pg_type(&global.scalar_type);
            self.used_globals_arg = true;
            // Wrapped in a cast rather than returned bare: `RawSql` carries no
            // type, so overload resolution fell back to text and picked the
            // `str` `find` for an `array<str>` global (`strpos(text[], text)
            // does not exist`).
            Ok(IrExpr::TypeCast(Box::new(super::IrTypeCast {
                expr: IrExpr::RawSql(globals_arg_read(&qualified, &pg_type)),
                pg_type,
                tuple_shape: None,
            })))
        } else {
            // Session global — allocate parameter slot
            let pg_type = self.resolve_global_pg_type(&global.scalar_type);
            let param_name = format!("__global__{}", qualified);
            let index = self.param_index(&param_name);
            // Register CTE only once
            if !self.global_ctes.iter().any(|g| g.cte_name() == cte_name) {
                self.global_ctes.push(IrGlobalCte::Session(IrSessionGlobalCte {
                    cte_name,
                    qualified_name: qualified,
                    param_index: index,
                    pg_type: pg_type.clone(),
                }));
            }
            Ok(IrExpr::GlobalParam { index, pg_type })
        }
    }

    // ── Schema lookups ────────────────────────────────────────────────────────────

    /// The object type a WITH binding names, if it binds one — object type
    /// strings are qualified, free/scalar bindings' are not.
    fn cte_object_type(&self, name: &str) -> Option<String> {
        self.cte_types.get(name).filter(|t| t.contains("::")).cloned()
    }

    fn resolve_type(&self, name: &str) -> Result<&'a TypeDescriptor, PyQLError> {
        // Accept both "TypeName" and "module::TypeName"
        self.schema
            .types
            .iter()
            .find(|t| t.name == name || format!("{}::{}", t.module, t.name) == name)
            .ok_or_else(|| {
                PyQLError::Resolution(PyQLResolutionError::UnknownType(PyQLUnknownTypeError {
                    message: format!("unknown type '{name}'"),
                    position: Position { line: 0, col: 0 },
                }))
            })
    }

    /// A schema enum, or failing that one the stdlib defines (`std::Endian`).
    /// The stdlib's are `&'static`, which coerces to `&'a` for any shorter
    /// `'a`, so both live behind one lookup and every site that recognizes
    /// enum member access picks them up without its own special case.
    fn resolve_enum(&self, name: &str) -> Option<&'a crate::schema::EnumDescriptor> {
        self.schema
            .enums
            .iter()
            .find(|e| e.name == name || format!("{}::{}", e.module, e.name) == name)
            .or_else(|| crate::stdlib::lookup_enum(name))
    }

    /// Resolve a `Channel` by name (bare or `module::Name`) — used by
    /// `notify()` to find the declared payload shape its second argument
    /// must match.
    fn resolve_channel(&self, name: &str) -> Option<&'a crate::schema::ChannelDescriptor> {
        self.schema.find_channel(name)
    }

    /// Resolve a registered custom scalar (`pylon.scalar(..., name=...)` or
    /// the `@pylon.scalar` decorator form) by name — used to recognize a
    /// cast target as that scalar's own PostgreSQL DOMAIN (see
    /// `resolve_cast_pg_type`); an anonymous (unregistered) scalar has no
    /// name reachable here at all, so it's never a valid cast target.
    fn resolve_scalar(&self, name: &str) -> Option<&'a crate::schema::ScalarDescriptor> {
        self.schema
            .scalars
            .iter()
            .find(|s| s.name == name || format!("{}::{}", s.module, s.name) == name)
    }

    /// Resolve a registered (nominal) `@pylon.named_tuple` type by name — used only
    /// to recognize a cast target as a named tuple (member structure isn't
    /// validated here; the value is trusted the same way a plain `<json>` cast is).
    fn resolve_named_tuple(&self, name: &str) -> Option<&'a crate::schema::NamedTupleDescriptor> {
        self.schema
            .named_tuples
            .iter()
            .find(|nt| nt.name == name || format!("{}::{}", nt.module, nt.name) == name)
    }

    /// Convert a schema-level `TupleMemberDescriptor` into a decode-time
    /// `JsonMember` — recurses for a nested tuple member, resolving a nested
    /// *nominal* member's own registered members too.
    fn tuple_member_to_json_member(&self, m: &crate::schema::TupleMemberDescriptor) -> crate::query::JsonMember {
        use crate::schema::TupleMemberKind;
        let kind = match &m.kind {
            TupleMemberKind::Scalar { .. } => crate::query::JsonMemberKind::Scalar,
            TupleMemberKind::Enum { module, name } => crate::query::JsonMemberKind::Enum {
                enum_type: format!("{}::{}", module, name),
            },
            TupleMemberKind::NamedTuple { module, name } => {
                let qname = format!("{}::{}", module, name);
                let nested_members = self
                    .resolve_named_tuple(&qname)
                    .map(|nt| {
                        nt.members
                            .iter()
                            .map(|mm| self.tuple_member_to_json_member(mm))
                            .collect()
                    })
                    .unwrap_or_default();
                crate::query::JsonMemberKind::Tuple {
                    type_name: Some(qname),
                    members: nested_members,
                }
            }
            TupleMemberKind::Tuple { members } => crate::query::JsonMemberKind::Tuple {
                type_name: None,
                members: members.iter().map(|mm| self.tuple_member_to_json_member(mm)).collect(),
            },
        };
        crate::query::JsonMember {
            key: m.name.clone(),
            kind,
        }
    }

    /// Convert a parsed cast-target `ast::TupleTypeElement` into a decode-time
    /// `JsonMember` — the cast-syntax counterpart of `tuple_member_to_json_member`.
    fn ast_tuple_element_to_json_member(&self, elem: &ast::TupleTypeElement) -> crate::query::JsonMember {
        crate::query::JsonMember {
            key: elem.name.clone(),
            kind: self.ast_type_expr_to_json_member_kind(&elem.ty),
        }
    }

    fn ast_type_expr_to_json_member_kind(&self, ty: &ast::TypeExpr) -> crate::query::JsonMemberKind {
        if let ast::TypeExpr::Tuple { elements } = ty {
            return crate::query::JsonMemberKind::Tuple {
                type_name: None,
                members: elements
                    .iter()
                    .map(|e| self.ast_tuple_element_to_json_member(e))
                    .collect(),
            };
        }
        let Some((module, name)) = ty.as_named() else {
            return crate::query::JsonMemberKind::Scalar;
        };
        let qname = match module {
            Some(m) => format!("{}::{}", m, name),
            None => name.to_string(),
        };
        if let Some(ed) = self.resolve_enum(&qname) {
            return crate::query::JsonMemberKind::Enum {
                enum_type: format!("{}::{}", ed.module, ed.name),
            };
        }
        if let Some(nt) = self.resolve_named_tuple(&qname) {
            return crate::query::JsonMemberKind::Tuple {
                type_name: Some(format!("{}::{}", nt.module, nt.name)),
                members: nt.members.iter().map(|m| self.tuple_member_to_json_member(m)).collect(),
            };
        }
        crate::query::JsonMemberKind::Scalar
    }

    /// Resolve a cast's own target-type shape for decode-time `ShapeNode`
    /// building — a structural `tuple<...>` cast resolves its elements
    /// directly; a nominal `<module::Name>` cast resolves via the registered
    /// `NamedTupleDescriptor`'s members. `None` for a plain scalar/enum
    /// cast target.
    fn resolve_tuple_cast_shape(&self, ty: &ast::TypeExpr) -> Option<TupleCastShape> {
        match ty {
            ast::TypeExpr::Tuple { elements } => Some(TupleCastShape {
                type_name: None,
                members: elements
                    .iter()
                    .map(|e| self.ast_tuple_element_to_json_member(e))
                    .collect(),
            }),
            _ => {
                let (module, name) = ty.as_named()?;
                let qname = match module {
                    Some(m) => format!("{}::{}", m, name),
                    None => name.to_string(),
                };
                let nt = self.resolve_named_tuple(&qname)?;
                Some(TupleCastShape {
                    type_name: Some(format!("{}::{}", nt.module, nt.name)),
                    members: nt.members.iter().map(|m| self.tuple_member_to_json_member(m)).collect(),
                })
            }
        }
    }

    /// Render a cast target `TypeExpr` for error messages, e.g.
    /// `tuple<std::int64, std::str>` or `default::Point` — used by the
    /// compile-time tuple-index bounds check.
    fn type_expr_to_display_str(&self, ty: &ast::TypeExpr) -> String {
        match ty {
            ast::TypeExpr::Tuple { elements } => {
                let inner = elements
                    .iter()
                    .map(|e| match &e.name {
                        Some(n) => format!("{}: {}", n, self.type_expr_to_display_str(&e.ty)),
                        None => self.type_expr_to_display_str(&e.ty),
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("tuple<{}>", inner)
            }
            ast::TypeExpr::Array { element } => format!("array<{}>", self.type_expr_to_display_str(element)),
            ast::TypeExpr::Named { module, name } => match module {
                Some(m) => format!("{}::{}", m, name),
                None => type_expr_to_pg(ty)
                    .map(|pg| pg_type_to_pyql(&pg).to_string())
                    .unwrap_or_else(|_| name.clone()),
            },
        }
    }

    /// Resolve a property's tuple-type shape for decode-time `ShapeNode`
    /// building — a nominal `__nt__:module::Name` `pg_type` marker resolves
    /// via the registered `NamedTupleDescriptor`'s own members; a structural
    /// `pylon.Tuple[...]` property carries its own `tuple_members` directly.
    fn resolve_property_tuple_shape(&self, prop: &PropertyDescriptor) -> Option<TupleCastShape> {
        if let Some(qname) = prop.pg_type.strip_prefix("__nt__:") {
            let nt = self.resolve_named_tuple(qname)?;
            return Some(TupleCastShape {
                type_name: Some(qname.to_string()),
                members: nt.members.iter().map(|m| self.tuple_member_to_json_member(m)).collect(),
            });
        }
        prop.tuple_members.as_ref().map(|members| TupleCastShape {
            type_name: None,
            members: members.iter().map(|m| self.tuple_member_to_json_member(m)).collect(),
        })
    }

    /// Emit a bare `<pg_type>expr` scalar cast as a free-select statement — shared
    /// by the enum/named-tuple/structural-tuple cast cases in `compile_stmt`'s
    /// top-level `Expr::TypeCast` handling. For a structural tuple cast whose
    /// source is itself a tuple/named-tuple literal, applies each element's
    /// own cast by position (see `try_compile_tuple_literal_cast_ctx`)
    /// instead of jsonb-wrapping the raw uncast literal values.
    fn scalar_cast_free_select(
        &mut self,
        tc: &ast::TypeCast,
        pg_type: String,
        distinct: bool,
    ) -> Result<IrStmt, PyQLError> {
        let cast_expr = match &tc.ty {
            ast::TypeExpr::Tuple { elements } => {
                let tuple_shape = self.resolve_tuple_cast_shape(&tc.ty);
                match self.try_compile_tuple_literal_cast_ctx(elements, &tc.expr, None)? {
                    // The literal-decompose path already applies each element's own
                    // cast — still wrap in TypeCast so `tuple_shape` reaches SQL
                    // emission for decode-time ShapeNode building (jsonb_build_*
                    // already produces jsonb, so the outer `::jsonb` is a no-op).
                    Some(ir) => IrExpr::TypeCast(Box::new(IrTypeCast {
                        expr: ir,
                        pg_type,
                        tuple_shape,
                    })),
                    None => {
                        let inner = self.compile_expr_ctx(&tc.expr, None)?;
                        IrExpr::TypeCast(Box::new(IrTypeCast {
                            expr: inner,
                            pg_type,
                            tuple_shape,
                        }))
                    }
                }
            }
            _ => {
                let inner = self.compile_expr_ctx(&tc.expr, None)?;
                let tuple_shape = self.resolve_tuple_cast_shape(&tc.ty);
                IrExpr::TypeCast(Box::new(IrTypeCast {
                    expr: inner,
                    pg_type,
                    tuple_shape,
                }))
            }
        };
        Ok(IrStmt::Select(IrSelect {
            rows: vec![IrRowSource::Free(IrFreeExpr::Scalar(cast_expr))],
            filter: None,
            order_by: vec![],
            offset: None,
            limit: None,
            distinct,
            dml_source: None,
            polymorphic: false,
            poly_implementors: vec![],
            poly_columns: vec![],
            lock: None,
        }))
    }

    /// Resolve a cast's target `pg_type` string — shared by both `Expr::TypeCast`
    /// compile sites (`compile_free_expr`/`compile_expr`). A structural tuple
    /// always resolves to jsonb; an array resolves to its element's own pg_type
    /// with a `[]` suffix — a real Postgres array, not jsonb, so it decodes
    /// natively (the driver already returns a Python list) with no per-member
    /// shape-tracking needed the way tuples require; a named type checks enum,
    /// then registered named tuple, then falls back to the built-in
    /// scalar/pgvector/cal type list.
    fn resolve_cast_pg_type(&self, ty: &ast::TypeExpr) -> Result<String, PyQLError> {
        if matches!(ty, ast::TypeExpr::Tuple { .. }) {
            return Ok("jsonb".to_string());
        }
        if let ast::TypeExpr::Array { element } = ty {
            let element_pg = self.resolve_cast_pg_type(element)?;
            return Ok(format!("{}[]", element_pg));
        }
        let (module, name) = ty.as_named().expect("checked above: not Tuple/Array");
        let qname = match module {
            Some(m) => format!("{}::{}", m, name),
            None => name.to_string(),
        };
        if let Some(ed) = self.resolve_enum(&qname) {
            return Ok(format!("{}.\"{}\"", crate::sql::pg_schema_str(&ed.module), ed.name));
        }
        if self.resolve_named_tuple(&qname).is_some() {
            return Ok("jsonb".to_string());
        }
        // A registered custom scalar casts directly to its own DOMAIN (not
        // just its base type) — Postgres enforces the domain's CHECK right
        // at cast time, the same way it would on column assignment (see
        // `PropertyDescriptor.column_type`'s own doc comment for why this
        // is safe to do everywhere else too).
        if let Some(sd) = self.resolve_scalar(&qname) {
            return Ok(format!("{}.\"{}\"", crate::sql::pg_schema_str(&sd.module), sd.name));
        }
        type_expr_to_pg(ty)
    }

    /// Cast one tuple-type element's source value to `target_ty` — recurses
    /// via `try_compile_tuple_literal_cast_ctx` when both the element's own
    /// type and its source value are themselves a nested tuple/named-tuple
    /// literal, so nesting applies per-element casts all the way down;
    /// otherwise a plain scalar/enum/nominal-named-tuple cast.
    fn compile_tuple_element_cast_ctx(
        &mut self,
        target_ty: &ast::TypeExpr,
        value: &Expr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<IrExpr, PyQLError> {
        if let ast::TypeExpr::Tuple { elements } = target_ty
            && let Some(ir) = self.try_compile_tuple_literal_cast_ctx(elements, value, ctx)?
        {
            return Ok(ir);
        }
        let inner = self.compile_expr_ctx(value, ctx)?;
        let pg_type = self.resolve_cast_pg_type(target_ty)?;
        Ok(IrExpr::TypeCast(Box::new(IrTypeCast {
            expr: inner,
            pg_type,
            tuple_shape: None,
        })))
    }

    /// When casting a tuple/named-tuple *literal* to a structural tuple type,
    /// apply each target element's own cast to its corresponding source value
    /// by position — e.g. `<tuple<int64, str>>('1', 3)` must coerce '1' to
    /// int64 and 3 to str, not just jsonb-wrap the raw literal values
    /// unchanged. Returns `None` when the source isn't a literal tuple/named-
    /// tuple of matching arity (e.g. a `$param`) — the whole value already
    /// arrives pre-shaped in that case, so the caller's generic jsonb-cast
    /// path handles it instead.
    fn try_compile_tuple_literal_cast_ctx(
        &mut self,
        target_elements: &[ast::TupleTypeElement],
        source: &Expr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<Option<IrExpr>, PyQLError> {
        let source_values: Vec<&Expr> = match source {
            Expr::Tuple(vals) if vals.len() == target_elements.len() => vals.iter().collect(),
            Expr::NamedTuple(fields) if fields.len() == target_elements.len() => {
                fields.iter().map(|(_, v)| v).collect()
            }
            _ => return Ok(None),
        };
        let named = target_elements.iter().all(|e| e.name.is_some());
        let mut casted = Vec::with_capacity(target_elements.len());
        for (elem, value) in target_elements.iter().zip(source_values) {
            casted.push(self.compile_tuple_element_cast_ctx(&elem.ty, value, ctx)?);
        }
        if named {
            let fields = target_elements
                .iter()
                .zip(casted)
                .map(|(e, v)| (e.name.clone().unwrap(), v))
                .collect();
            Ok(Some(IrExpr::NamedTuple {
                fields,
                is_free_object: false,
            }))
        } else {
            Ok(Some(IrExpr::Tuple(casted)))
        }
    }

    /// When casting an array *literal* to `array<T>`, apply the element
    /// type's own cast to each element by position — e.g.
    /// `<array<int64>>['1', '3']` must coerce each string element to int64,
    /// not just emit a raw untyped `ARRAY[...]`. Reuses
    /// `compile_tuple_element_cast_ctx` for the per-element cast since
    /// casting "this value to this target type" is exactly the same
    /// operation regardless of whether the target is a tuple element or an
    /// array element (including decomposing a nested tuple-literal element).
    /// Returns `None` when the source isn't a literal array (e.g. a
    /// `$param` or a sub-select) — the caller's generic cast path handles
    /// those instead.
    fn try_compile_array_literal_cast_ctx(
        &mut self,
        element_ty: &ast::TypeExpr,
        source: &Expr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<Option<IrExpr>, PyQLError> {
        let Expr::Array(elems) = source else { return Ok(None) };
        let casted = elems
            .iter()
            .map(|e| self.compile_tuple_element_cast_ctx(element_ty, e, ctx))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Some(IrExpr::Array(casted)))
    }

    fn compile_enum_access(&self, type_ref: &str, variant: &str) -> Result<IrExpr, PyQLError> {
        let ed = self
            .resolve_enum(type_ref)
            .ok_or_else(|| self.type_err(&format!("unknown type '{}'", type_ref)))?;
        if !ed.members.iter().any(|m| m == variant) {
            return Err(self.type_err(&format!(
                "enum '{}::{}' has no member '{}'",
                ed.module, ed.name, variant
            )));
        }
        // A stdlib enum has no PostgreSQL enum type to cast to — the function
        // taking it switches on the label as text.
        let pg_type = if crate::stdlib::lookup_enum(&format!("{}::{}", ed.module, ed.name)).is_some() {
            "text".to_string()
        } else {
            format!("{}.\"{}\"", crate::sql::pg_schema_str(&ed.module), ed.name)
        };
        Ok(IrExpr::EnumLiteral {
            pg_type,
            variant: variant.to_string(),
        })
    }

    /// The row source a name reads from: the binding it is bound to, if any,
    /// else the type's own table.
    fn row_source_table(&self, name: &str, td: &TypeDescriptor) -> String {
        if let Some(cte) = self.for_var_ctes.get(name) {
            return format!("@cte:{cte}");
        }
        if self.cte_object_type(name).is_some() {
            return format!("@cte:{}", self.cte_sql_name(name));
        }
        td.table.clone()
    }

    /// The type a path's root names — a real type, or the object type a
    /// `with` binding stands for.
    ///
    /// A binding is a row source just like a type name, so anything that
    /// re-resolves a root after `compile_path_select` has already accepted it
    /// has to look it up the same way, or a bound alias reads as an unknown
    /// type.
    fn resolve_path_root(&self, root_name: &str) -> Result<&'a TypeDescriptor, PyQLError> {
        if let Some(qualified) = self.for_var_types.get(root_name) {
            return self.resolve_type(qualified);
        }
        match self.cte_types.get(root_name).filter(|t| t.contains("::")).cloned() {
            Some(bound) => self.resolve_type(&bound),
            None => self.resolve_type(root_name),
        }
    }

    fn find_poly_implementors(&self, iface_qname: &str) -> Vec<IrPolyImplementor> {
        self.schema
            .types
            .iter()
            .filter(|t| !t.abstract_ && Self::is_or_implements(t, iface_qname))
            .map(|t| IrPolyImplementor {
                type_name: format!("{}::{}", t.module, t.name),
                table: t.table.clone(),
                module: t.module.clone(),
            })
            .collect()
    }

    fn resolve_property<'t>(td: &'t TypeDescriptor, name: &str) -> Option<&'t PropertyDescriptor> {
        td.properties.iter().find(|p| p.name == name)
    }

    fn resolve_link<'t>(td: &'t TypeDescriptor, name: &str) -> Option<&'t LinkDescriptor> {
        td.links.iter().find(|l| l.name == name)
    }

    fn resolve_multilink<'t>(td: &'t TypeDescriptor, name: &str) -> Option<&'t MultiLinkDescriptor> {
        td.multilinks.iter().find(|m| m.name == name)
    }

    /// `@prop` read off the junction row of the multi-link currently in
    /// scope (`link_prop_scope`). Only its own modifiers put one there —
    /// anywhere else there is no junction row to read.
    fn compile_link_prop_ref(&mut self, prop_name: &str) -> Result<IrExpr, PyQLError> {
        let Some(scope) = self.link_prop_scope.last().cloned() else {
            return Err(self.type_err(&format!(
                "'@{prop_name}' is a link property, so it is only valid in the modifiers or shape of the \
                 link it belongs to, e.g. 'locators: {{ … }} filter @{prop_name}'"
            )));
        };
        let Some((through_qname, junction_alias)) = scope else {
            return Err(self.type_err(&format!(
                "this link has no link properties, so '@{prop_name}' cannot be read — \
                 declare the link with a `Through[...]` type to give it some"
            )));
        };
        let through_td = self.resolve_type(&through_qname)?;
        let Some(prop) = Self::resolve_property(through_td, prop_name) else {
            return Err(self.field_err(prop_name, &through_qname));
        };
        Ok(IrExpr::ColumnRef {
            alias: junction_alias,
            column: prop.name.clone(),
            pg_type: prop.pg_type.clone(),
        })
    }

    /// Whether a link declared with `target` reaches the type named
    /// `current_qname` — directly, or because that type implements the
    /// interface the link points at. A link to an interface accepts every
    /// implementor, so a backlink from one is exactly as valid as a backlink
    /// from the interface itself.
    fn link_target_reaches(&self, target: &str, current_qname: &str) -> bool {
        if target == current_qname {
            return true;
        }
        self.resolve_type(current_qname)
            .is_ok_and(|td| td.interfaces.iter().any(|i| i == target))
    }

    /// A computed pointer visible on `td` — its own, or one declared on an
    /// interface it implements. An interface's computeds are not copied into
    /// its implementors the way its stored pointers are, so without the
    /// second lookup `.account.tier` reported that `tier` was missing while
    /// suggesting `tier` (the suggester already searched interfaces).
    fn resolve_computed(&self, td: &TypeDescriptor, name: &str) -> Option<crate::schema::ComputedDescriptor> {
        if let Some(cd) = td.computed.iter().find(|c| c.name == name) {
            return Some(cd.clone());
        }
        td.interfaces
            .iter()
            .filter_map(|iface| self.resolve_type(iface).ok())
            .find_map(|itd| itd.computed.iter().find(|c| c.name == name))
            .cloned()
    }

    // ── Statement dispatch ────────────────────────────────────────────────────────

    fn compile_stmt(&mut self, stmt: &Stmt) -> Result<IrStmt, PyQLError> {
        match stmt {
            Stmt::Select(s) => {
                let (distinct, result) = match &s.result {
                    Expr::UnaryOp(u) if u.op == ast::UnaryOpKind::Distinct => (true, &u.operand),
                    // `detached` marks this select as independent of the one
                    // enclosing it. At the top level that is already true, but
                    // for a select nested in a filter it is the whole point:
                    // it is what lets `select X filter not exists (select
                    // detached X filter .k = X.k)` mean "no *other* X", rather
                    // than comparing the inner row with itself. Stripping the
                    // wrapper outright made that anti-join a tautology
                    // (`"t1"."label" = "t1"."label"`) with no error.
                    Expr::Detached(inner) => {
                        self.pending_detached = true;
                        (false, inner.as_ref())
                    }
                    other => (false, other),
                };

                // `select assert_distinct(f(…)) { … }` — the function's rows,
                // with the assert run once over all of them: the select's own
                // filter narrows what comes back, not what is checked.
                if let Expr::Shape(sh) = result
                    && let Some(Expr::FunctionCall(assert)) = &sh.expr
                    && assert.module.as_deref().is_none_or(|m| m == "std")
                    && matches!(assert.name.as_str(), "assert_exists" | "assert_distinct")
                    && let [Expr::FunctionCall(inner)] = assert.args.as_slice()
                    && let Some(mut fs) = self.try_compile_fn_object_select(inner, &sh.elements, s, distinct)?
                {
                    let message = self.assert_message(assert, None)?;
                    let unchecked = ast::SelectStmt {
                        result: Expr::FunctionCall(inner.clone()),
                        filter: None,
                        order_by: vec![],
                        offset: None,
                        limit: None,
                        lock: None,
                    };
                    let every_row = self
                        .try_compile_fn_object_select(inner, &[], &unchecked, false)?
                        .ok_or_else(|| self.type_err("assert subject is not an object-returning function"))?;
                    let checked = IrExpr::FunctionCall(IrFunctionCall {
                        return_pg_type: None,
                        schema: Some("_pylon".to_string()),
                        name: assert.name.clone(),
                        args: std::iter::once(IrExpr::ArrayFromSelect(Box::new(IrArraySource::StmtColumn {
                            stmt: Box::new(IrStmt::FunctionSelect(every_row)),
                            column: "id".to_string(),
                        })))
                        .chain(message)
                        .collect(),
                        sql_template: None,
                    });
                    let check = IrExpr::BinOp(Box::new(IrBinOp {
                        left: IrExpr::FunctionCall(IrFunctionCall {
                            return_pg_type: None,
                            schema: None,
                            name: "cardinality".to_string(),
                            args: vec![checked],
                            sql_template: None,
                        }),
                        op: ast::BinOpKind::Ge,
                        right: IrExpr::Literal(IrLiteral::Int(0)),
                    }));
                    fs.filter = and_conditions(fs.filter, vec![check]);
                    return Ok(IrStmt::FunctionSelect(fs));
                }
                if let Some(flattened) = flatten_shape_subject(result) {
                    let mut flat = s.clone();
                    flat.result = match distinct {
                        true => Expr::UnaryOp(Box::new(ast::UnaryOp {
                            op: ast::UnaryOpKind::Distinct,
                            operand: flattened,
                        })),
                        false => flattened,
                    };
                    return self.compile_stmt(&Stmt::Select(flat));
                }
                if let Expr::Shape(sh) = result
                    && let Some(Expr::SubQuery(inner)) = &sh.expr
                    && let Stmt::Group(g) = inner.as_ref()
                {
                    return self.compile_group_projection(s, g, &sh.elements).map(IrStmt::Group);
                }

                // `select alias_name [{ shape }]` — inline the alias expression.
                if let Some(ir) = self.try_compile_alias_select(s, result, distinct)? {
                    return Ok(ir);
                }

                // `select global name [{ shape }]` — inline the computed expression.
                if let Some(ir) = self.try_compile_global_select(s, result, distinct)? {
                    return Ok(ir);
                }

                // `global name.field` / `(select Type filter ...).field` — splice the
                // field access onto the inner type-select as an additional path step.
                if let Some(ir) = self.try_compile_field_access_select(s, result)? {
                    return Ok(ir);
                }

                // select fn() { shape } — user-defined object-returning function with shape.
                if let Expr::Shape(sh) = result
                    && let Some(Expr::FunctionCall(fc)) = sh.expr.as_ref()
                    && let Some(ir) = self.try_compile_fn_object_select(fc, &sh.elements, s, distinct)?
                {
                    return Ok(IrStmt::FunctionSelect(ir));
                }

                // select fn() — bare user-defined object-returning function (no shape).
                if let Expr::FunctionCall(fc) = result
                    && let Some(ir) = self.try_compile_fn_object_select(fc, &[], s, distinct)?
                {
                    return Ok(IrStmt::FunctionSelect(ir));
                }

                // select vector::search(Type, $vec) { object { … }, distance }
                if let Expr::Shape(sh) = result
                    && let Some(Expr::FunctionCall(fc)) = sh.expr.as_ref()
                {
                    if let Some(ir) = self.try_compile_vector_search(fc, &sh.elements, s)? {
                        return Ok(IrStmt::VectorSearch(ir));
                    }
                    if let Some(ir) = self.try_compile_fts_search(fc, &sh.elements, s)? {
                        return Ok(IrStmt::FtsSearch(ir));
                    }
                }
                // bare vector::search / fts::search without shape
                if let Expr::FunctionCall(fc) = result {
                    if let Some(ir) = self.try_compile_vector_search(fc, &[], s)? {
                        return Ok(IrStmt::VectorSearch(ir));
                    }
                    if let Some(ir) = self.try_compile_fts_search(fc, &[], s)? {
                        return Ok(IrStmt::FtsSearch(ir));
                    }
                }

                // (<Module::Type>expr) { shape } — parenthesised id-lookup with shape.
                // The parens are stripped by the parser, leaving Shape { expr: TypeCast }.
                // Only meaningful for a named schema type — a structural tuple cast
                // never denotes an object-type lookup.
                if let Expr::Shape(sh) = result
                    && let Some(Expr::TypeCast(tc)) = sh.expr.as_ref()
                    && let Some((module, name)) = tc.ty.as_named()
                    && module
                        .map(|m| !["std", "cal", "math", "sys", "pgvector", "crypto", "postgis"].contains(&m))
                        .unwrap_or(false)
                {
                    let id_filter = Expr::BinOp(Box::new(ast::BinOp {
                        left: Expr::Path(ast::Path::relative("id")),
                        op: ast::BinOpKind::Eq,
                        right: tc.expr.clone(),
                    }));
                    let merged_filter = match &s.filter {
                        None => Some(id_filter),
                        Some(existing) => Some(Expr::BinOp(Box::new(ast::BinOp {
                            left: id_filter,
                            op: ast::BinOpKind::And,
                            right: existing.clone(),
                        }))),
                    };
                    // Keep the module qualification so an unknown
                    // target reports its full name, not a bare one.
                    let qname = match module {
                        Some(m) => format!("{}::{}", m, name),
                        None => name.to_string(),
                    };
                    let synthetic = ast::SelectStmt {
                        result: Expr::Shape(Box::new(ast::ShapeExpr {
                            expr: Some(Expr::Path(ast::Path::absolute(&qname))),
                            elements: sh.elements.clone(),
                            marker_offset: None,
                        })),
                        filter: merged_filter,
                        order_by: s.order_by.clone(),
                        offset: s.offset.clone(),
                        limit: s.limit.clone(),
                        lock: s.lock.clone(),
                    };
                    return self
                        .compile_select(&synthetic, &synthetic.result, distinct)
                        .map(IrStmt::Select);
                }
                // <Module::Type>expr — schema object lookup by id, or a scalar cast
                // (enum, registered named tuple, or a bare structural `tuple<...>`).
                // Stdlib modules are handled by compile_free_expr; only user schema
                // modules (or a structural tuple, which has no module at all) route here.
                const STDLIB_MODULES: &[&str] = &["std", "cal", "math", "sys", "pgvector", "crypto", "postgis"];
                if let Expr::TypeCast(tc) = result {
                    // A structural tuple cast is always a plain scalar (jsonb) cast —
                    // never an object-type lookup — so it's handled directly, before
                    // any of the qname-based (named-type-only) checks below.
                    if matches!(&tc.ty, ast::TypeExpr::Tuple { .. }) {
                        return self.scalar_cast_free_select(tc, "jsonb".to_string(), distinct);
                    }
                    if let Some((module, name)) = tc.ty.as_named() {
                        let qname = match module {
                            Some(m) => format!("{}::{}", m, name),
                            None => name.to_string(),
                        };
                        if let Some(ed) = self.resolve_enum(&qname) {
                            let pg_type = format!("{}.\"{}\"", crate::sql::pg_schema_str(&ed.module), ed.name);
                            return self.scalar_cast_free_select(tc, pg_type, distinct);
                        }
                        if self.resolve_named_tuple(&qname).is_some() {
                            return self.scalar_cast_free_select(tc, "jsonb".to_string(), distinct);
                        }
                        if let Some(sd) = self.resolve_scalar(&qname) {
                            let pg_type = format!("{}.\"{}\"", crate::sql::pg_schema_str(&sd.module), sd.name);
                            return self.scalar_cast_free_select(tc, pg_type, distinct);
                        }
                        if module.map(|m| !STDLIB_MODULES.contains(&m)).unwrap_or(false) {
                            return self.compile_schema_cast_select(s, tc).map(IrStmt::Select);
                        }
                    }
                }
                // Path traversal: `select TypeName.link.prop` or `select TypeName.link { shape }`.
                if let Expr::Path(p) = result {
                    if !p.partial
                        && p.steps.len() == 2
                        && let [ast::PathStep::Name(type_ref), ast::PathStep::Name(variant)] = p.steps.as_slice()
                        && self.resolve_enum(type_ref).is_some()
                    {
                        let expr = self.compile_enum_access(type_ref, variant)?;
                        return Ok(IrStmt::Select(IrSelect {
                            rows: vec![IrRowSource::Free(IrFreeExpr::Scalar(expr))],
                            filter: None,
                            order_by: vec![],
                            offset: None,
                            limit: None,
                            distinct,
                            dml_source: None,
                            polymorphic: false,
                            poly_implementors: vec![],
                            poly_columns: vec![],
                            lock: None,
                        }));
                    }
                    // `root.field1.field2...` where `root` is a WITH-bound
                    // free object (not a real/CTE-bound schema type) —
                    // resolve to a field reference (possibly chained through
                    // nested free objects) instead of falling into
                    // compile_path_select, which only knows schema paths.
                    if let Some(resolved) = self.resolve_cte_path(p) {
                        let expr = resolved?;
                        return Ok(IrStmt::Select(IrSelect {
                            rows: vec![IrRowSource::Free(IrFreeExpr::Scalar(expr))],
                            filter: None,
                            order_by: vec![],
                            offset: None,
                            limit: None,
                            distinct,
                            dml_source: None,
                            polymorphic: false,
                            poly_implementors: vec![],
                            poly_columns: vec![],
                            lock: None,
                        }));
                    }
                    if !p.partial && p.steps.len() > 1 {
                        return self.compile_path_select(s, p, &[], distinct).map(IrStmt::PathSelect);
                    }
                }
                if let Expr::Shape(sh) = result
                    && let Some(Expr::Path(p)) = sh.expr.as_ref()
                    && !p.partial
                    && p.steps.len() > 1
                {
                    return self
                        .compile_path_select(s, p, &sh.elements, distinct)
                        .map(IrStmt::PathSelect);
                }
                // assert_exists/assert_distinct with SubQuery arg → set-returning assert
                if let Expr::FunctionCall(f) = result
                    && (f.module.is_none() || f.module.as_deref() == Some("std"))
                    && matches!(f.name.as_str(), "assert_exists" | "assert_distinct")
                    && !f.args.is_empty()
                    && let Expr::SubQuery(inner_stmt) = &f.args[0]
                {
                    let offset = s.offset.as_ref().map(|e| self.compile_free_expr(e)).transpose()?;
                    let limit = s.limit.as_ref().map(|e| self.compile_free_expr(e)).transpose()?;
                    let message = self.assert_message(f, None)?;
                    // A set of objects has to come back as rows, not as the
                    // bare ids the array form carries — so the assert vets the
                    // ids and the type's own rows are selected by them.
                    if let Ok(type_name) = self.dml_subject_type(inner_stmt)
                        && let Ok(td) = self.resolve_type(&type_name)
                    {
                        let td_module = td.module.clone();
                        let td_name = td.name.clone();
                        let td_table = td.table.clone();
                        let pk = td
                            .properties
                            .iter()
                            .find(|p| p.is_pk)
                            .map(|p| (p.name.clone(), p.pg_type.clone()))
                            .unwrap_or_else(|| ("id".to_string(), "uuid".to_string()));
                        let inner_ir = self.compile_stmt(inner_stmt)?;
                        let alias = self.fresh_alias();
                        let vetted = IrExpr::FunctionCall(IrFunctionCall {
                            return_pg_type: None,
                            schema: Some("_pylon".to_string()),
                            name: f.name.clone(),
                            args: std::iter::once(IrExpr::ArrayFromSelect(Box::new(IrArraySource::StmtColumn {
                                stmt: Box::new(inner_ir),
                                column: pk.0.clone(),
                            })))
                            .chain(message)
                            .collect(),
                            sql_template: None,
                        });
                        let filter = IrExpr::BinOp(Box::new(IrBinOp {
                            left: IrExpr::ColumnRef {
                                alias: alias.clone(),
                                column: pk.0.clone(),
                                pg_type: pk.1.clone(),
                            },
                            op: ast::BinOpKind::In,
                            right: vetted,
                        }));
                        let shape = vec![IrShapePointer::Scalar(IrScalarPointer {
                            implicit_id: false,
                            marker_offset: None,
                            alias: "id".to_string(),
                            column: pk.0,
                            pg_type: pk.1,
                            tuple_shape: None,
                        })];
                        let source = IrSource {
                            poly: None,
                            type_name: format!("{td_module}::{td_name}"),
                            table: td_table,
                            alias,
                        };
                        let mut select = IrSelect::schema_bound(source, shape, Some(filter));
                        select.offset = offset;
                        select.limit = limit;
                        select.distinct = distinct;
                        return Ok(IrStmt::Select(select));
                    }
                    let inner = self.compile_subquery_to_array_source(inner_stmt)?;
                    return Ok(IrStmt::Select(IrSelect {
                        rows: vec![IrRowSource::Free(IrFreeExpr::AssertSet {
                            fn_name: f.name.clone(),
                            inner: Box::new(inner),
                            message,
                        })],
                        filter: None,
                        order_by: vec![],
                        offset,
                        limit,
                        distinct,
                        dml_source: None,
                        polymorphic: false,
                        poly_implementors: vec![],
                        poly_columns: vec![],
                        lock: None,
                    }));
                }
                // `array_agg(array_unpack(teams.permissions))` — the unpacking
                // has to happen in a row source, so the aggregate is left with
                // no walk of its own and the select stands free.
                if let Some(expr) = self.aggregate_over_unpacked(s, result, distinct)? {
                    return Ok(IrStmt::Select(IrSelect {
                        rows: vec![IrRowSource::Free(IrFreeExpr::Scalar(expr))],
                        filter: None,
                        order_by: vec![],
                        offset: None,
                        limit: None,
                        distinct: false,
                        dml_source: None,
                        polymorphic: false,
                        poly_implementors: vec![],
                        poly_columns: vec![],
                        lock: None,
                    }));
                }
                // Expression containing a type-rooted path: `select fn(TypeName.link.prop, ...)`.
                if let Some(root) = self.find_path_root_in_expr(result) {
                    return self
                        .compile_expr_as_path_select(s, result, &root, distinct)
                        .map(IrStmt::PathSelect);
                }
                // `select TypeName is CheckType` — iterate source type, return bool per row.
                if let Expr::TypeIs { expr, ty } = result
                    && let Expr::Path(p) = expr.as_ref()
                    && !p.partial
                    && p.steps.len() == 1
                    && let ast::PathStep::Name(src_name) = &p.steps[0]
                    && self.resolve_name_ref(src_name, true).is_none()
                {
                    let src_td = self.resolve_type(src_name)?;
                    {
                        let src_qname = format!("{}::{}", src_td.module, src_td.name);
                        let (ty_module, ty_name) = ty
                            .as_named()
                            .ok_or_else(|| self.type_err("cannot use IS with a tuple or array type"))?;
                        let check_module = ty_module.unwrap_or(&src_td.module);
                        let check_name = format!("{}::{}", check_module, ty_name);
                        self.resolve_type(&check_name)?;
                        let check_qname = check_name;
                        let src_table = src_td.table.clone();
                        let src_alias = self.fresh_alias();
                        let src_td = self.resolve_type(&src_qname)?;
                        let poly_implementors = if self.is_polymorphic(src_td) {
                            self.find_poly_implementors(&src_qname)
                        } else {
                            vec![]
                        };
                        let bool_expr = self.type_check_bool_expr(&src_qname, &check_qname, src_td, &src_alias);
                        let ps = IrPathSelect {
                            root: IrSource {
                                poly: None,
                                type_name: src_qname,
                                table: src_table,
                                alias: src_alias,
                            },
                            joins: vec![],
                            result: IrPathResult::Scalar(bool_expr, None),
                            filter: s
                                .filter
                                .as_ref()
                                .map(|_| Err(self.type_err("FILTER is not supported on type-is SELECT")))
                                .transpose()?,
                            order_by: vec![],
                            offset: None,
                            limit: None,
                            distinct,
                            poly_implementors,
                        };
                        return Ok(IrStmt::PathSelect(ps));
                    }
                }
                if let Expr::Union(a, b) = result
                    && !distinct
                    && s.filter.is_none()
                    && s.order_by.is_empty()
                    && s.offset.is_none()
                    && s.limit.is_none()
                    && (self.is_scalar_walk(a) || self.is_scalar_walk(b))
                {
                    return self.compile_scalar_union(result);
                }
                // `select (l.addon { c := … }).c` — the values, one row each.
                if !distinct
                    && s.filter.is_none()
                    && s.order_by.is_empty()
                    && s.offset.is_none()
                    && s.limit.is_none()
                    && let Some(ps) = self.compile_shape_field_select(result, None)?
                {
                    return Ok(IrStmt::PathSelect(ps));
                }
                // `select (update T … ).link { … }` — the subject walks off a
                // mutation. Hoist the mutation into the statement's own WITH
                // and re-root the walk at that binding, which is the
                // `with a := (update …) select a.link { … }` spelling that
                // already compiles. A walk off a plain sub-select needs none
                // of this.
                if let Expr::Shape(sh) = result
                    && let Some(subject) = sh.expr.as_ref()
                    && !matches!(subject, Expr::Path(_))
                {
                    let (base, fields) = Self::peel_field_access_chain(subject);
                    if let Expr::SubQuery(inner_stmt) = base
                        && !fields.is_empty()
                        && matches!(inner_stmt.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_))
                    {
                        let inner = self.compile_stmt(inner_stmt)?;
                        let cte_name = self.fresh_nested_cte_name();
                        // The walk may read a junction this very mutation
                        // appended to; those rows live only in the append CTE.
                        let overrides = Self::junction_overrides_for(&inner, &cte_name);
                        let type_name = self.register_cte(&cte_name, &inner);
                        self.hoisted_ctes.push(IrCteDef {
                            name: cte_name.clone(),
                            stmt: inner,
                            type_name,
                            correlated_to: None,
                        });
                        let mut steps = vec![ast::PathStep::Name(cte_name)];
                        steps.extend(fields.into_iter().map(ast::PathStep::Name));
                        let rerooted = ast::SelectStmt {
                            result: Expr::Shape(Box::new(ast::ShapeExpr {
                                expr: Some(Expr::Path(ast::Path { steps, partial: false })),
                                elements: sh.elements.clone(),
                                marker_offset: None,
                            })),
                            filter: s.filter.clone(),
                            order_by: s.order_by.clone(),
                            offset: s.offset.clone(),
                            limit: s.limit.clone(),
                            lock: s.lock.clone(),
                        };
                        let previous = std::mem::replace(&mut self.junction_read_overrides, overrides);
                        let compiled = self.compile_stmt(&Stmt::Select(rerooted));
                        self.junction_read_overrides = previous;
                        return compiled;
                    }
                }
                // `select (select (A union B) { … } limit 1) { … }` — a nested
                // select whose own subject is a union has no single type name
                // for the outer select to take. Hoisting it into a binding and
                // reading that back is the `with l := (select …) select l { … }`
                // spelling, which already compiles.
                if let Expr::Shape(sh) = result
                    && let Some(Expr::SubQuery(inner_stmt)) = sh.expr.as_ref()
                    && matches!(inner_stmt.as_ref(), Stmt::Select(_))
                    && self.dml_subject_type(inner_stmt).is_err()
                {
                    let inner = self.compile_stmt(inner_stmt)?;
                    let cte_name = self.fresh_nested_cte_name();
                    let type_name = self.register_cte(&cte_name, &inner);
                    self.hoisted_ctes.push(IrCteDef {
                        name: cte_name.clone(),
                        stmt: inner,
                        type_name,
                        correlated_to: None,
                    });
                    let rerooted = ast::SelectStmt {
                        result: Expr::Shape(Box::new(ast::ShapeExpr {
                            expr: Some(Expr::Path(ast::Path {
                                steps: vec![ast::PathStep::Name(cte_name)],
                                partial: false,
                            })),
                            elements: sh.elements.clone(),
                            marker_offset: None,
                        })),
                        filter: s.filter.clone(),
                        order_by: s.order_by.clone(),
                        offset: s.offset.clone(),
                        limit: s.limit.clone(),
                        lock: s.lock.clone(),
                    };
                    return self.compile_stmt(&Stmt::Select(rerooted));
                }
                // `select (for … union …)` — the select adds nothing the loop has
                // not already produced, so it *is* the loop. Written with
                // modifiers of its own it would need the loop bound in a CTE
                // first, which nothing supports yet, so that still errors.
                if let Expr::SubQuery(inner) = result
                    && matches!(inner.as_ref(), Stmt::For(_))
                    && !distinct
                    && s.filter.is_none()
                    && s.order_by.is_empty()
                    && s.offset.is_none()
                    && s.limit.is_none()
                {
                    return self.compile_stmt(inner);
                }
                // Catch mixed object/scalar UNION before dispatching further.
                self.check_union_type_compat(result)?;
                if self.is_free_result(result) {
                    self.compile_free_select(s, result, distinct).map(IrStmt::Select)
                } else {
                    self.compile_select(s, result, distinct).map(IrStmt::Select)
                }
            }
            Stmt::Insert(s) => self.compile_insert(s).map(IrStmt::Insert),
            Stmt::Update(s) => self.compile_update(s).map(IrStmt::Update),
            Stmt::Delete(s) => self.compile_delete(s).map(IrStmt::Delete),
            Stmt::Group(s) => self.compile_group(s).map(IrStmt::Group),
            // Nested WITH blocks (e.g. inside a subquery): inline the CTE types
            // into the current compiler scope so references resolve correctly.
            // The actual CTE SQL is handled at the top-level compile() boundary.
            Stmt::With(w) => {
                for alias in &w.aliases {
                    if self.bind_inline_if_correlated(&alias.name, &alias.expr, None)?
                        || self.bind_group(&alias.name, &alias.expr)?
                    {
                        continue;
                    }
                    let (ir_inner, correlated_to) = self.compile_binding_in_scope(&alias.expr)?;
                    let sql_name = self.claim_cte_sql_name(&alias.name);
                    let type_name = self.register_cte(&alias.name, &ir_inner);
                    self.hoisted_binding_sources
                        .insert(sql_name.clone(), alias.expr.clone());
                    self.hoisted_ctes.push(IrCteDef {
                        name: sql_name,
                        stmt: ir_inner,
                        type_name,
                        correlated_to,
                    });
                }
                self.compile_stmt(&w.stmt)
            }
            Stmt::For(f) => match self.compile_group_elements(f)? {
                Some(grp) => Ok(IrStmt::Group(grp)),
                None => self.compile_for(f).map(IrStmt::For),
            },
            // `analyze` only changes how the query is *executed* (see
            // `analyze.rs`) — the inner statement's IR is identical either
            // way, so this layer just unwraps and compiles it normally.
            Stmt::Analyze(inner) => self.compile_stmt(inner),
        }
    }

    /// `<Module::Type>expr` in SELECT position is a schema object lookup:
    /// select the object whose `id` equals `expr`.  Semantically identical to
    /// `SELECT Type FILTER .id = expr` plus any modifiers on the outer SELECT.
    fn compile_schema_cast_select(&mut self, sel: &ast::SelectStmt, tc: &ast::TypeCast) -> Result<IrSelect, PyQLError> {
        let id_filter = Expr::BinOp(Box::new(ast::BinOp {
            left: Expr::Path(ast::Path::relative("id")),
            op: ast::BinOpKind::Eq,
            right: tc.expr.clone(),
        }));
        let merged_filter = match &sel.filter {
            None => Some(id_filter),
            Some(existing) => Some(Expr::BinOp(Box::new(ast::BinOp {
                left: id_filter,
                op: ast::BinOpKind::And,
                right: existing.clone(),
            }))),
        };
        // Callers only reach this function after confirming `tc.ty` is `Named`
        // (a structural tuple is never an object-type lookup).
        let (module, name) = tc
            .ty
            .as_named()
            .ok_or_else(|| self.type_err("cannot use a tuple or array type as a schema object cast"))?;
        // Keep the module qualification in the synthetic path so a genuinely
        // unknown target (neither an object type, enum, scalar, nor named
        // tuple) reports its full name via `resolve_type`'s own error,
        // instead of silently dropping the module and reporting a bare name.
        let qname = match module {
            Some(m) => format!("{}::{}", m, name),
            None => name.to_string(),
        };
        let synthetic = ast::SelectStmt {
            result: Expr::Path(ast::Path::absolute(&qname)),
            filter: merged_filter,
            order_by: sel.order_by.clone(),
            offset: sel.offset.clone(),
            limit: sel.limit.clone(),
            lock: sel.lock.clone(),
        };
        self.compile_select(&synthetic, &synthetic.result, false)
    }

    // ── PATH SELECT ───────────────────────────────────────────────────────────────

    /// `select TypeName.link.prop` / `select TypeName.link { shape }`.
    /// Walks the path, building JOIN steps, then projects the final pointer or object.
    /// `compile_shape` with the type the walk landed on anchored, so a
    /// relative path written inside the shape — a `with` binding's value, a
    /// nested sub-select's filter — has an enclosing object to resolve
    /// against. A plain `select` pushes the same anchor for its own shape.
    fn compile_shape_anchored(
        &mut self,
        elements: &[ShapeElement],
        td: &'a TypeDescriptor,
        alias: &str,
        module: &str,
    ) -> Result<Vec<IrShapePointer>, PyQLError> {
        self.anchors.push(SelectAnchor {
            type_name: td.name.clone(),
            qualified: format!("{}::{}", td.module, td.name),
            alias: alias.to_string(),
            detached: false,
            declared_on: None,
        });
        let result = self.compile_shape(elements, td, alias, module);
        self.anchors.pop();
        result
    }

    fn compile_path_select(
        &mut self,
        sel: &ast::SelectStmt,
        path: &ast::Path,
        shape_elements: &[ShapeElement],
        distinct: bool,
    ) -> Result<IrPathSelect, PyQLError> {
        self.compile_path_select_with_tail(sel, path, shape_elements, distinct, 0)
    }

    /// `compile_path_select` where the last `tail` steps were appended by a
    /// projection off a sub-select — `(select … limit 1).plan.tier` — so
    /// `sel`'s own modifiers belong to the step before them, not to the end
    /// of the path.
    fn compile_path_select_with_tail(
        &mut self,
        sel: &ast::SelectStmt,
        path: &ast::Path,
        shape_elements: &[ShapeElement],
        distinct: bool,
        tail: usize,
    ) -> Result<IrPathSelect, PyQLError> {
        let outer_anchor = self.modifier_anchor.take();
        let mut result = self.compile_path_select_inner(sel, path, shape_elements, distinct, tail);
        self.modifier_anchor = outer_anchor;
        if let Ok(path_select) = &mut result {
            self.resolve_join_fanouts(path_select);
        }
        result
    }

    fn compile_path_select_inner(
        &mut self,
        sel: &ast::SelectStmt,
        path: &ast::Path,
        shape_elements: &[ShapeElement],
        distinct: bool,
        mut tail: usize,
    ) -> Result<IrPathSelect, PyQLError> {
        use ast::PathStep;

        let root_name = match &path.steps[0] {
            PathStep::Name(n) => n.as_str(),
            _ => return Err(self.type_err("path traversal must start with a type name")),
        };
        // A WITH-block CTE bound to an object type (e.g. `with user :=
        // (select global current_user) select user.gender`) can be
        // traversed just like a real type name — resolve its underlying
        // type and source from the `@cte:` sentinel table (the same
        // mechanism `compile_select`'s bare-CTE-object-select case uses)
        // instead of failing with "unknown type '{root_name}'".
        let root_td = self.resolve_path_root(root_name)?;
        let root_alias = self.fresh_alias();
        let root = IrSource {
            poly: None,
            type_name: format!("{}::{}", root_td.module, root_td.name),
            table: self.row_source_table(root_name, root_td),
            alias: root_alias.clone(),
        };
        // `for c in (select Person) union (select c.name)` — the loop variable
        // holds the row's key, so the walk starts from that row rather than
        // from the whole table.
        let for_var_root = self.for_var_types.contains_key(root_name).then(|| {
            IrExpr::BinOp(Box::new(IrBinOp {
                left: IrExpr::ColumnRef {
                    alias: root_alias.clone(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
                op: ast::BinOpKind::Eq,
                right: self.for_var_ref(root_name),
            }))
        });

        let mut joins: Vec<IrPathJoin> = vec![];
        let mut current_td = root_td;
        let mut current_alias = root_alias;

        // Owned rather than borrowed: traversing *through* a computed
        // pointer splices that computed's own path in place of the step
        // naming it (see the computed branch at the bottom of the loop).
        let mut steps: Vec<PathStep> = path.steps[1..].to_vec();
        // `(step index, filter)` a spliced computed contributed, to compile
        // against the type that step lands on once the loop reaches it.
        let mut pending_filters: Vec<(usize, Expr)> = vec![];
        let mut extra_conditions: Vec<IrExpr> = for_var_root.into_iter().collect();
        // The junction the traversal last crossed, for a bare `@prop` in the
        // select's own modifiers.
        let mut junction_scope: Option<(String, String)> = None;
        let mut splices = 0usize;
        let mut idx = 0;
        if tail > 0 && tail >= steps.len() {
            self.modifier_anchor = Some((
                format!("{}::{}", current_td.module, current_td.name),
                current_alias.clone(),
            ));
        }
        while idx < steps.len() {
            let owned_step = steps[idx].clone();
            let step = &owned_step;
            let n_steps = steps.len();
            let is_last = |extra: usize| idx + extra == n_steps - 1;
            if tail > 0 && idx == n_steps - tail {
                self.modifier_anchor = Some((
                    format!("{}::{}", current_td.module, current_td.name),
                    current_alias.clone(),
                ));
            }

            // A spliced computed's own filter belongs to the step it landed
            // on, which is the one just processed.
            while let Some(pos) = pending_filters.iter().position(|(i, _)| *i + 1 == idx) {
                let (_, f) = pending_filters.remove(pos);
                let cond = self.compile_expr(&f, current_td, &current_alias)?;
                extra_conditions.push(cond);
            }

            // Type intersection standalone (not after backlink): narrows current_td.
            if let PathStep::TypeIntersection(type_ref) = step {
                let type_name = match &type_ref.module {
                    Some(m) => format!("{}::{}", m, type_ref.name),
                    None => type_ref.name.clone(),
                };
                let narrowed = self.resolve_type(&type_name)?;
                // Narrowing to a type with a relation of its own moves to that
                // relation, joined on the shared id: an interface's view has
                // none of its implementors' own columns, and two unrelated
                // types share no ids at all, so the join finds nothing — which
                // is exactly what an impossible intersection yields. A mixin
                // has no relation; its columns are already on the current row.
                let narrowed_has_relation = !Self::backs_no_relation(narrowed);
                if narrowed_has_relation && narrowed.table != current_td.table {
                    let target_alias = self.fresh_alias();
                    let target = IrSource {
                        poly: None,
                        type_name: format!("{}::{}", narrowed.module, narrowed.name),
                        table: narrowed.table.clone(),
                        alias: target_alias.clone(),
                    };
                    joins.push(IrPathJoin::Single {
                        source_alias: current_alias.clone(),
                        fk_col: "id".to_string(),
                        target,
                    });
                    current_alias = target_alias;
                }
                current_td = narrowed;
                idx += 1;
                continue;
            }

            // Backlink: .<link_name — optionally followed by [is OwnerType].
            if let PathStep::Backlink(link_name) = step {
                // Peek ahead: if the next step is [is Type], use it to identify the owner.
                let owner_hint = steps.get(idx + 1).and_then(|s| {
                    if let PathStep::TypeIntersection(tr) = s {
                        Some(tr.clone())
                    } else {
                        None
                    }
                });
                let consumed_extra = if owner_hint.is_some() { 1 } else { 0 };

                let owner_td: &TypeDescriptor = if let Some(ref tr) = owner_hint {
                    let type_name = match &tr.module {
                        Some(m) => format!("{}::{}", m, tr.name),
                        None => tr.name.clone(),
                    };
                    let td = self.resolve_type(&type_name)?;
                    let current_qname = format!("{}::{}", current_td.module, current_td.name);
                    let link_targets_current =
                        td.links
                            .iter()
                            .any(|l| l.name == *link_name && self.link_target_reaches(&l.target, &current_qname))
                            || td.multilinks.iter().any(|ml| {
                                ml.name == *link_name && self.link_target_reaches(&ml.target, &current_qname)
                            });
                    if link_targets_current {
                        td
                    } else {
                        // `.<memberships[is account::Account]` — declared further
                        // down, by the one type under the narrowing that has it.
                        let narrowed = format!("{}::{}", td.module, td.name);
                        let declaring: Vec<&'a TypeDescriptor> = self
                            .schema
                            .types
                            .iter()
                            .filter(|t| !t.abstract_ && Self::is_or_implements(t, &narrowed))
                            .filter(|t| self.declares_backlink(t, link_name, &current_qname))
                            .collect();
                        match Self::without_inherited_owners(declaring).as_slice() {
                            [only] => only,
                            _ => {
                                return Err(self.type_err(&format!(
                                    "link '{}::{}' does not target '{}'; backlink is not valid here",
                                    type_name, link_name, current_qname,
                                )));
                            }
                        }
                    }
                } else {
                    // No hint — search for any type whose link/multilink targets current_td.
                    let current_qname = format!("{}::{}", current_td.module, current_td.name);
                    self.schema
                        .types
                        .iter()
                        // The base, not a subtype inheriting the link from it.
                        .filter(|t| {
                            t.bases.is_empty()
                                || !t.bases.iter().any(|base| {
                                    self.resolve_type(base).is_ok_and(|b| {
                                        b.links.iter().any(|l| l.name == *link_name)
                                            || b.multilinks.iter().any(|ml| ml.name == *link_name)
                                    })
                                })
                        })
                        .find(|t| {
                            t.links
                                .iter()
                                .any(|l| l.name == *link_name && self.link_target_reaches(&l.target, &current_qname))
                                || t.multilinks.iter().any(|ml| {
                                    ml.name == *link_name && self.link_target_reaches(&ml.target, &current_qname)
                                })
                        })
                        .ok_or_else(|| {
                            self.type_err(&format!(
                                "no type has a link '{}' targeting '{}'",
                                link_name, current_qname,
                            ))
                        })?
                };

                let target_alias = self.fresh_alias();
                let target = IrSource {
                    poly: None,
                    type_name: format!("{}::{}", owner_td.module, owner_td.name),
                    table: owner_td.table.clone(),
                    alias: target_alias.clone(),
                };

                // Determine if the link is single (FK), junction-backed
                // single (same shape as a backlinked multi-link), or multi
                // (junction).
                if let Some(l) = owner_td.links.iter().find(|l| l.name == *link_name) {
                    if l.is_junction_backed() {
                        let junction_alias = self.fresh_alias();
                        let (junction_table, module, owner_col, current_col, _) =
                            self.link_junction_info(owner_td, l)?;
                        joins.push(IrPathJoin::BacklinkMulti {
                            source_alias: current_alias.clone(),
                            junction_alias,
                            junction_table,
                            module,
                            owner_col,
                            current_col,
                            target,
                        });
                    } else {
                        joins.push(IrPathJoin::BacklinkSingle {
                            source_alias: current_alias.clone(),
                            fk_col: format!("{}_id", link_name),
                            target,
                        });
                    }
                } else {
                    let ml = owner_td
                        .multilinks
                        .iter()
                        .find(|ml| ml.name == *link_name)
                        .unwrap()
                        .clone();
                    let junction_alias = self.fresh_alias();
                    let (junction_table, module, _, _, _) = self.multilink_junction_info(owner_td, &ml)?;
                    joins.push(IrPathJoin::BacklinkMulti {
                        source_alias: current_alias.clone(),
                        junction_alias,
                        junction_table,
                        module,
                        owner_col: "source".to_string(),
                        current_col: "target".to_string(),
                        target,
                    });
                }

                if is_last(consumed_extra) {
                    let shape =
                        self.compile_shape_anchored(shape_elements, owner_td, &target_alias, &owner_td.module.clone())?;
                    let result = IrPathResult::Object {
                        alias: target_alias.clone(),
                        type_name: format!("{}::{}", owner_td.module, owner_td.name),
                        shape,
                    };
                    let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                        sel,
                        owner_td,
                        &target_alias,
                        junction_scope.clone(),
                        shape_elements,
                    )?;
                    return Ok(IrPathSelect {
                        root,
                        joins,
                        result,
                        filter: and_conditions(filter, extra_conditions),
                        order_by,
                        offset,
                        limit,
                        distinct,
                        poly_implementors: vec![],
                    });
                }
                current_td = owner_td;
                current_alias = target_alias;
                idx += 1 + consumed_extra;
                continue;
            }

            let step_name = match step {
                PathStep::Name(n) => n.as_str(),
                _ => return Err(self.type_err("only name steps are supported in path traversal")),
            };

            // `__type__` is a virtual scalar property holding the
            // fully-qualified type name: a real discriminator column on a
            // polymorphic (interface) source, a constant on a concrete one.
            if step_name == "__type__" {
                if !is_last(0) {
                    return Err(
                        self.type_err("'__type__' is the type's name, not an object — it cannot be traversed further")
                    );
                }
                let polymorphic = self.is_polymorphic(current_td);
                let expr = if polymorphic {
                    IrExpr::ColumnRef {
                        alias: current_alias.clone(),
                        column: "__type__".to_string(),
                        pg_type: "text".to_string(),
                    }
                } else {
                    IrExpr::Literal(IrLiteral::Str(format!("{}::{}", current_td.module, current_td.name)))
                };
                // A CTE-backed root already carries the discriminator column
                // from the binding's own polymorphic expansion; re-expanding it
                // here would read the base type again and drop the binding's
                // filter.
                let poly_implementors = if polymorphic && joins.is_empty() && !root.table.starts_with("@cte:") {
                    self.find_poly_implementors(&root.type_name.clone())
                } else {
                    vec![]
                };
                let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                    sel,
                    current_td,
                    &current_alias,
                    junction_scope.clone(),
                    shape_elements,
                )?;
                return Ok(IrPathSelect {
                    root,
                    joins,
                    result: IrPathResult::Scalar(expr, None),
                    filter: and_conditions(filter, extra_conditions),
                    order_by,
                    offset,
                    limit,
                    distinct,
                    poly_implementors,
                });
            }

            // Check scalar property first.
            if let Some(p) = current_td.properties.iter().find(|p| p.name == step_name) {
                if !is_last(0) {
                    // Named tuple properties (nominal `__nt__:` marker) and structural
                    // tuple properties (`tuple_members`) both allow further field
                    // access via jsonb operators.
                    if p.pg_type.starts_with("__nt__:") || p.tuple_members.is_some() {
                        let base = IrExpr::ColumnRef {
                            alias: current_alias.clone(),
                            column: p.name.clone(),
                            pg_type: p.pg_type.clone(),
                        };
                        let remaining = &steps[idx + 1..];
                        let mut ir: IrExpr = base;
                        for step in remaining {
                            let field = match step {
                                ast::PathStep::Name(n) => n.clone(),
                                _ => return Err(self.type_err("only field name steps are valid inside a named tuple")),
                            };
                            ir = IrExpr::JsonbField {
                                expr: Box::new(ir),
                                field,
                            };
                        }
                        let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                            sel,
                            current_td,
                            &current_alias,
                            junction_scope.clone(),
                            shape_elements,
                        )?;
                        return Ok(IrPathSelect {
                            root,
                            joins,
                            result: IrPathResult::Scalar(ir, None),
                            filter: and_conditions(filter, extra_conditions),
                            order_by,
                            offset,
                            limit,
                            distinct,
                            poly_implementors: vec![],
                        });
                    }
                    return Err(self.type_err(&format!(
                        "'{step_name}' is a scalar property, not a link — cannot traverse further"
                    )));
                }
                let tuple_shape = self.resolve_property_tuple_shape(p);
                let result = IrPathResult::Scalar(
                    IrExpr::ColumnRef {
                        alias: current_alias.clone(),
                        column: p.name.clone(),
                        pg_type: p.pg_type.clone(),
                    },
                    tuple_shape,
                );
                let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                    sel,
                    current_td,
                    &current_alias,
                    junction_scope.clone(),
                    shape_elements,
                )?;
                return Ok(IrPathSelect {
                    root,
                    joins,
                    result,
                    filter: and_conditions(filter, extra_conditions),
                    order_by,
                    offset,
                    limit,
                    distinct,
                    poly_implementors: vec![],
                });
            }

            // Single link.
            if let Some(l) = Self::resolve_link(current_td, step_name) {
                let target_td = self.resolve_type(&l.target)?;
                let target_alias = self.fresh_alias();
                let target = IrSource {
                    poly: None,
                    type_name: format!("{}::{}", target_td.module, target_td.name),
                    table: target_td.table.clone(),
                    alias: target_alias.clone(),
                };
                if l.is_junction_backed() {
                    // Same join shape a multi-link's own path step uses
                    // (D1) — `PRIMARY KEY (source)` on the junction table
                    // already guarantees at most one matching row, so no
                    // extra cardinality handling is needed here.
                    let join = self.build_multilink_join(current_td, &l.name, &l.target, &l.through)?;
                    let junction_alias = self.fresh_alias();
                    junction_scope = l.through.clone().map(|t| (t, junction_alias.clone()));
                    joins.push(IrPathJoin::Multi {
                        source_alias: current_alias.clone(),
                        junction_alias,
                        join,
                        target,
                    });
                } else {
                    joins.push(IrPathJoin::Single {
                        source_alias: current_alias.clone(),
                        fk_col: format!("{}_id", l.name),
                        target,
                    });
                }
                if is_last(0) {
                    let shape = self.compile_shape_anchored(
                        shape_elements,
                        target_td,
                        &target_alias,
                        &target_td.module.clone(),
                    )?;
                    let result = IrPathResult::Object {
                        alias: target_alias.clone(),
                        type_name: format!("{}::{}", target_td.module, target_td.name),
                        shape,
                    };
                    let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                        sel,
                        target_td,
                        &target_alias,
                        junction_scope.clone(),
                        shape_elements,
                    )?;
                    return Ok(IrPathSelect {
                        root,
                        joins,
                        result,
                        filter: and_conditions(filter, extra_conditions),
                        order_by,
                        offset,
                        limit,
                        distinct,
                        poly_implementors: vec![],
                    });
                }
                current_td = target_td;
                current_alias = target_alias;
                idx += 1;
                continue;
            }

            // Multi-link.
            if let Some(ml) = Self::resolve_multilink(current_td, step_name) {
                let target_td = self.resolve_type(&ml.target)?;
                let target_alias = self.fresh_alias();
                let junction_alias = self.fresh_alias();
                // Set only while walking off a mutation this statement made:
                // both the junction rows and, when they were inserted here
                // too, the targets live in CTEs rather than their tables.
                let override_for_step = self
                    .junction_read_overrides
                    .get(&self.owner_junction(current_td, &ml.name, None))
                    .cloned();
                let target = IrSource {
                    poly: None,
                    type_name: format!("{}::{}", target_td.module, target_td.name),
                    table: match override_for_step.as_ref().and_then(|o| o.targets.clone()) {
                        Some(cte) => cte,
                        None => target_td.table.clone(),
                    },
                    alias: target_alias.clone(),
                };
                let join_info = if let Some(through_qname) = &ml.through {
                    let through_td = self.resolve_type(through_qname)?;
                    if through_td.junction {
                        // See `junction_info_for`'s doc comment: owner-derived,
                        // never `through_td.table` itself.
                        IrMultiLinkJoin::Standard {
                            junction_table: self.owner_junction(current_td, &ml.name, Some(through_td)),
                            module: current_td.module.clone(),
                        }
                    } else {
                        let source_qname = format!("{}::{}", current_td.module, current_td.name);
                        let source_col = through_td
                            .links
                            .iter()
                            .find(|l| l.target == source_qname)
                            .ok_or_else(|| {
                                PyQLError::Type(PyQLTypeError {
                                    message: format!("through type {through_qname} has no link to {source_qname}"),
                                    position: Position { line: 0, col: 0 },
                                })
                            })?
                            .name
                            .clone();
                        let target_col = through_td
                            .links
                            .iter()
                            .find(|l| l.target == ml.target && l.name != source_col)
                            .or_else(|| through_td.links.iter().find(|l| l.target == ml.target))
                            .ok_or_else(|| {
                                PyQLError::Type(PyQLTypeError {
                                    message: format!(
                                        "through type {through_qname} has no link to target {}",
                                        ml.target
                                    ),
                                    position: Position { line: 0, col: 0 },
                                })
                            })?
                            .name
                            .clone();
                        IrMultiLinkJoin::Through {
                            junction_table: through_td.table.clone(),
                            module: through_td.module.clone(),
                            source_col,
                            target_col,
                        }
                    }
                } else {
                    let junction_table = self.owner_junction(current_td, &ml.name, None);
                    IrMultiLinkJoin::Standard {
                        junction_table: match &override_for_step {
                            Some(o) => o.junction.clone(),
                            None => junction_table,
                        },
                        module: current_td.module.clone(),
                    }
                };
                junction_scope = ml.through.clone().map(|t| (t, junction_alias.clone()));
                joins.push(IrPathJoin::Multi {
                    source_alias: current_alias.clone(),
                    junction_alias,
                    join: join_info,
                    target,
                });
                if is_last(0) {
                    let shape = self.compile_shape_anchored(
                        shape_elements,
                        target_td,
                        &target_alias,
                        &target_td.module.clone(),
                    )?;
                    let result = IrPathResult::Object {
                        alias: target_alias.clone(),
                        type_name: format!("{}::{}", target_td.module, target_td.name),
                        shape,
                    };
                    let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                        sel,
                        target_td,
                        &target_alias,
                        junction_scope.clone(),
                        shape_elements,
                    )?;
                    return Ok(IrPathSelect {
                        root,
                        joins,
                        result,
                        filter: and_conditions(filter, extra_conditions),
                        order_by,
                        offset,
                        limit,
                        distinct,
                        poly_implementors: vec![],
                    });
                }
                current_td = target_td;
                current_alias = target_alias;
                idx += 1;
                continue;
            }

            // A computed pointer declared on the type reached so far (or on
            // an interface it implements) — or, at the root only, one the
            // shape in scope declared, which is on no type at all:
            // `r { revision := … }` read back as `.revision.created_at`.
            let declared = match self.resolve_computed(current_td, step_name) {
                Some(cd) => Some(crate::parse::parse_pointer_expr(&cd.expression).map_err(PyQLError::Syntax)?),
                None if idx == 0 => self
                    .active_declared_pointers
                    .iter()
                    .find(|d| path_leaf(&d.path).is_ok_and(|n| n == step_name))
                    .and_then(|d| d.compexpr.clone()),
                None => None,
            };
            if let Some(parsed) = declared {
                // `(select .parents … limit 1).parent` reads as the select over
                // the walk those two make together.
                let rewritten = Self::field_access_over_select(&parsed);
                let expr_ast = match &rewritten {
                    Some((sel, _)) => Expr::SubQuery(Box::new(Stmt::Select(sel.clone()))),
                    None => parsed,
                };
                let field_steps = rewritten.as_ref().map(|(_, n)| *n).unwrap_or(0);

                // Traversing *through* it: a computed has no stored column
                // for a join to hang off, but if it just names a link — with
                // or without a filter — its own path can take the step's
                // place, and its filter rides along on the spliced segment.
                // Chaining computeds this way is routine, so the splice
                // re-enters the loop and expands again if it lands on
                // another one.
                // As the last step too, when what it names lands on an object:
                // the shape and the select's own modifiers belong to that
                // object, and reading it as an expression instead binds them to
                // the type that declares the computed.
                if let Some((p, _, modifiers)) = Self::pointer_subject(&expr_ast)
                    && p.partial
                    && !p.steps.is_empty()
                    && (!is_last(0)
                        || self
                            .walk_path_types(current_td, &p.steps, MAX_COMPUTED_SPLICES)
                            .1
                            .is_some())
                {
                    // Order/offset/limit of its own pick one row *per source
                    // row*, which no plain join expresses — so the computed's
                    // own traversal becomes a correlated LATERAL and the path
                    // continues from its result.
                    if let Some(m) = modifiers
                        && (m.limit.is_some() || m.offset.is_some() || !m.order_by.is_empty())
                    {
                        let mut inner_steps =
                            vec![PathStep::Name(format!("{}::{}", current_td.module, current_td.name))];
                        inner_steps.extend(p.steps.iter().cloned());
                        let inner_path = ast::Path {
                            steps: inner_steps,
                            partial: false,
                        };
                        let inner_sel = ast::SelectStmt {
                            result: Expr::Path(inner_path.clone()),
                            filter: m.filter.clone(),
                            order_by: m.order_by.clone(),
                            offset: m.offset.clone(),
                            limit: m.limit.clone(),
                            lock: None,
                        };
                        let mut inner =
                            self.compile_path_select_with_tail(&inner_sel, &inner_path, &[], false, field_steps)?;
                        Self::correlate_path_select(&mut inner, &current_alias);
                        let IrPathResult::Object { type_name, .. } = &inner.result else {
                            return Err(self.type_err(&format!(
                                "computed pointer '{step_name}' is a scalar — a path cannot continue through it"
                            )));
                        };
                        let target_td = self.resolve_type(&type_name.clone())?;
                        let target_alias = self.fresh_alias();
                        let target = IrSource {
                            poly: None,
                            type_name: format!("{}::{}", target_td.module, target_td.name),
                            table: target_td.table.clone(),
                            alias: target_alias.clone(),
                        };
                        joins.push(IrPathJoin::Lateral {
                            inner: Box::new(inner),
                            target,
                        });
                        if is_last(0) {
                            let module = target_td.module.clone();
                            let shape =
                                self.compile_shape_anchored(shape_elements, target_td, &target_alias, &module)?;
                            let result = IrPathResult::Object {
                                alias: target_alias.clone(),
                                type_name: format!("{}::{}", target_td.module, target_td.name),
                                shape,
                            };
                            let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                                sel,
                                target_td,
                                &target_alias,
                                junction_scope,
                                shape_elements,
                            )?;
                            return Ok(IrPathSelect {
                                root,
                                joins,
                                result,
                                filter: and_conditions(filter, extra_conditions),
                                order_by,
                                offset,
                                limit,
                                distinct,
                                poly_implementors: vec![],
                            });
                        }
                        current_td = target_td;
                        current_alias = target_alias;
                        idx += 1;
                        continue;
                    }
                    splices += 1;
                    if splices > MAX_COMPUTED_SPLICES {
                        return Err(self.type_err(&format!(
                            "computed pointer '{step_name}' expands into itself — \
                             a path cannot be resolved through a cycle of computed pointers"
                        )));
                    }
                    let filter = modifiers.and_then(|m| m.filter.clone());
                    let spliced = p.steps.clone();
                    if tail > 0 && idx >= steps.len() - tail {
                        tail += spliced.len() - 1;
                    }
                    let landing = idx + spliced.len() - 1;
                    steps.splice(idx..idx + 1, spliced);
                    // Every filter already queued for a later step shifts
                    // along with it.
                    let shift = landing - idx;
                    for (i, _) in pending_filters.iter_mut() {
                        if *i > idx {
                            *i += shift;
                        }
                    }
                    if let Some(f) = filter {
                        pending_filters.push((landing, f));
                    }
                    continue;
                }

                // A computed backed by an object-returning function —
                // `translation := latest(.id)`. There is no path to splice
                // in, so the call itself becomes the next row source: a
                // LATERAL join, since its arguments read the alias the
                // traversal has reached.
                if let Some((fc, modifiers)) = Self::function_subject(&expr_ast)
                    && let Some(fd) = self.resolve_object_fn(fc)
                {
                    if fd.params.len() != fc.args.len() {
                        return Err(self.type_err(&format!(
                            "function '{}::{}' expects {} argument(s), got {}",
                            fd.module,
                            fd.name,
                            fd.params.len(),
                            fc.args.len()
                        )));
                    }
                    let (fn_module, fn_name, return_type_name) =
                        (fd.module.clone(), fd.name.clone(), fd.return_pg_type.clone());
                    let mut args = fc
                        .args
                        .iter()
                        .map(|a| self.compile_expr(a, current_td, &current_alias))
                        .collect::<Result<Vec<_>, _>>()?;
                    let qualified = format!("{fn_module}::{fn_name}");
                    if let Some(globals) = self.globals_arg_for_call(&qualified)? {
                        args.insert(0, globals);
                    }
                    let target_td = self.resolve_type(&return_type_name)?;
                    let target_alias = self.fresh_alias();
                    let target = IrSource {
                        poly: None,
                        type_name: format!("{}::{}", target_td.module, target_td.name),
                        table: target_td.table.clone(),
                        alias: target_alias.clone(),
                    };
                    joins.push(IrPathJoin::Function {
                        fn_module,
                        fn_name,
                        args,
                        target,
                    });
                    if let Some(f) = modifiers.and_then(|m| m.filter.clone()) {
                        let cond = self.compile_expr(&f, target_td, &target_alias)?;
                        extra_conditions.push(cond);
                    }
                    if is_last(0) {
                        let shape = self.compile_shape_anchored(
                            shape_elements,
                            target_td,
                            &target_alias,
                            &target_td.module.clone(),
                        )?;
                        let result = IrPathResult::Object {
                            alias: target_alias.clone(),
                            type_name: format!("{}::{}", target_td.module, target_td.name),
                            shape,
                        };
                        let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                            sel,
                            target_td,
                            &target_alias,
                            junction_scope.clone(),
                            shape_elements,
                        )?;
                        return Ok(IrPathSelect {
                            root,
                            joins,
                            result,
                            filter: and_conditions(filter, extra_conditions),
                            order_by,
                            offset,
                            limit,
                            distinct,
                            poly_implementors: vec![],
                        });
                    }
                    current_td = target_td;
                    current_alias = target_alias;
                    idx += 1;
                    continue;
                }

                if !is_last(0) {
                    return Err(self.type_err(&format!(
                        "'{step_name}' is a computed pointer — it has no stored column to traverse further through"
                    )));
                }
                let expanding = format!("{}::{}.{step_name}", current_td.module, current_td.name);
                if self.expanding_computeds.contains(&expanding) {
                    return Err(self.type_err(&format!(
                        "computed pointer '{step_name}' expands into itself — \
                         a path cannot be resolved through a cycle of computed pointers"
                    )));
                }
                self.expanding_computeds.push(expanding);
                let expr = self.compile_expr(&expr_ast, current_td, &current_alias);
                self.expanding_computeds.pop();
                let expr = expr?;
                let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                    sel,
                    current_td,
                    &current_alias,
                    junction_scope.clone(),
                    shape_elements,
                )?;
                return Ok(IrPathSelect {
                    root,
                    joins,
                    result: IrPathResult::Scalar(expr, None),
                    filter: and_conditions(filter, extra_conditions),
                    order_by,
                    offset,
                    limit,
                    distinct,
                    poly_implementors: vec![],
                });
            }

            return Err(self.field_err(step_name, &format!("{}::{}", current_td.module, current_td.name)));
        }

        // Every step consumed with nothing returned means the path *ended* on a
        // narrowing (`a.respondents[is GuestRespondent]`, or a bare `[is T]`).
        // The loop has already joined to the narrowed relation, so what it
        // landed on is the answer — read with the shape, like any other object
        // step.
        if matches!(steps.last(), Some(PathStep::TypeIntersection(_))) {
            let module = current_td.module.clone();
            let type_name = format!("{}::{}", current_td.module, current_td.name);
            let shape = self.compile_shape_anchored(shape_elements, current_td, &current_alias, &module)?;
            let (filter, order_by, offset, limit) = self.compile_path_modifiers_scoped(
                sel,
                current_td,
                &current_alias,
                junction_scope.clone(),
                shape_elements,
            )?;
            return Ok(IrPathSelect {
                root,
                joins,
                result: IrPathResult::Object {
                    alias: current_alias,
                    type_name,
                    shape,
                },
                filter: and_conditions(filter, extra_conditions),
                order_by,
                offset,
                limit,
                distinct,
                poly_implementors: vec![],
            });
        }

        // Should be unreachable: steps is non-empty (we checked len > 1 before dispatch).
        Err(self.type_err("empty path traversal"))
    }

    /// `compile_path_modifiers` with the junction the traversal last crossed
    /// in scope, so a bare `@prop` in the select's own FILTER/ORDER BY can
    /// read it. Pushes nothing when there is no junction, leaving `@prop` to
    /// report that it has no link to belong to.
    fn compile_path_modifiers_scoped(
        &mut self,
        sel: &ast::SelectStmt,
        td: &TypeDescriptor,
        alias: &str,
        junction: Option<(String, String)>,
        shape: &[ShapeElement],
    ) -> Result<SelectModifiers, PyQLError> {
        let pushed = junction.is_some();
        if pushed {
            self.link_prop_scope.push(junction);
        }
        // `select .applied_promotions { name := .promotion.name } order by .name`
        // — the shape's own computeds are in scope for the clauses beside it,
        // the same as for a schema select. Added only now, after the shape has
        // been compiled, so one shape pointer still cannot read another.
        let outer_declared = self.active_declared_pointers.clone();
        self.active_declared_pointers
            .extend(shape.iter().filter(|el| el.compexpr.is_some()).cloned());
        let anchored = self.modifier_anchor.take();
        let result = match &anchored {
            Some((qualified, anchor_alias)) => {
                let anchor_td = self.resolve_type(qualified)?;
                let anchor_alias = anchor_alias.clone();
                self.compile_path_modifiers(sel, anchor_td, &anchor_alias)
            }
            None => self.compile_path_modifiers(sel, td, alias),
        };
        if pushed {
            self.link_prop_scope.pop();
        }
        self.active_declared_pointers = outer_declared;
        result
    }

    fn compile_path_modifiers(
        &mut self,
        sel: &ast::SelectStmt,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<SelectModifiers, PyQLError> {
        self.anchors.push(SelectAnchor {
            type_name: td.name.clone(),
            qualified: format!("{}::{}", td.module, td.name),
            alias: alias.to_string(),
            detached: std::mem::take(&mut self.pending_detached),
            declared_on: None,
        });
        let result = self.compile_path_modifiers_inner(sel, td, alias);
        self.anchors.pop();
        result
    }

    fn compile_path_modifiers_inner(
        &mut self,
        sel: &ast::SelectStmt,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<SelectModifiers, PyQLError> {
        let filter = sel
            .filter
            .as_ref()
            .map(|f| self.compile_expr(f, td, alias))
            .transpose()?;
        let order_by = sel
            .order_by
            .iter()
            .map(|s| self.compile_sort(s, td, alias))
            .collect::<Result<Vec<_>, _>>()?;
        let offset = sel
            .offset
            .as_ref()
            .map(|e| self.compile_expr(e, td, alias))
            .transpose()?;
        let limit = sel
            .limit
            .as_ref()
            .map(|e| self.compile_expr(e, td, alias))
            .transpose()?;
        Ok((filter, order_by, offset, limit))
    }

    // ── Expression-over-type dispatch ─────────────────────────────────────────────

    /// Recursively find the first absolute path (non-partial, multi-step) in an expression
    /// and return its root type name if it resolves to a known schema type.
    fn find_path_root_in_expr(&self, expr: &Expr) -> Option<String> {
        match expr {
            Expr::Path(p) if !p.partial && p.steps.len() > 1 => {
                if let ast::PathStep::Name(root) = &p.steps[0]
                    && (self.resolve_type(root).is_ok() || self.cte_object_type(root).is_some())
                {
                    return Some(root.clone());
                }
                None
            }
            Expr::FunctionCall(f) => f.args.iter().find_map(|a| self.find_path_root_in_expr(a)),
            Expr::BinOp(b) => self
                .find_path_root_in_expr(&b.left)
                .or_else(|| self.find_path_root_in_expr(&b.right)),
            Expr::UnaryOp(u) => self.find_path_root_in_expr(&u.operand),
            _ => None,
        }
    }

    /// Rewrite absolute paths rooted at `root_name` to relative (partial) paths.
    fn rewrite_abs_to_partial(expr: Expr, root_name: &str) -> Expr {
        match expr {
            Expr::Path(ref p) if !p.partial => {
                if let ast::PathStep::Name(first) = &p.steps[0]
                    && first == root_name
                    && p.steps.len() > 1
                {
                    return Expr::Path(ast::Path {
                        steps: p.steps[1..].to_vec(),
                        partial: true,
                    });
                }
                expr
            }
            Expr::FunctionCall(f) => Expr::FunctionCall(ast::FunctionCall {
                module: f.module,
                name: f.name,
                args: f
                    .args
                    .into_iter()
                    .map(|a| Self::rewrite_abs_to_partial(a, root_name))
                    .collect(),
                kwargs: f.kwargs,
            }),
            Expr::BinOp(b) => Expr::BinOp(Box::new(ast::BinOp {
                left: Self::rewrite_abs_to_partial(b.left, root_name),
                op: b.op,
                right: Self::rewrite_abs_to_partial(b.right, root_name),
            })),
            Expr::UnaryOp(u) => Expr::UnaryOp(Box::new(ast::UnaryOp {
                op: u.op,
                operand: Self::rewrite_abs_to_partial(u.operand, root_name),
            })),
            other => other,
        }
    }

    /// The pointers a sub-select's shape declares, as the relative paths they
    /// stand for: `{ handle := [is Handle].handle }` → `handle` → `[is
    /// Handle].handle`. `None` when any element is something other than a
    /// named pointer defined by a relative path, which this substitution
    /// cannot stand in for.
    fn shape_alias_paths(elements: &[ShapeElement]) -> Option<Vec<(String, ast::Path)>> {
        let mut defs = Vec::with_capacity(elements.len());
        for element in elements {
            let [ast::PathStep::Name(name)] = element.path.steps.as_slice() else {
                return None;
            };
            match &element.compexpr {
                Some(Expr::Path(p)) if p.partial => defs.push((name.clone(), p.clone())),
                _ => return None,
            }
        }
        Some(defs)
    }

    /// Replace each `.alias` a sub-select's shape declares with the path it
    /// stands for, so the select's own FILTER/ORDER BY read the same thing the
    /// shape projects.
    fn substitute_shape_aliases(expr: Expr, defs: &[(String, ast::Path)]) -> Expr {
        match expr {
            Expr::Path(ref p) if p.partial => {
                let Some(ast::PathStep::Name(first)) = p.steps.first() else {
                    return expr;
                };
                let Some((_, definition)) = defs.iter().find(|(name, _)| name == first) else {
                    return expr;
                };
                let mut steps = definition.steps.clone();
                steps.extend(p.steps[1..].iter().cloned());
                Expr::Path(ast::Path { steps, partial: true })
            }
            Expr::FunctionCall(f) => Expr::FunctionCall(ast::FunctionCall {
                module: f.module,
                name: f.name,
                args: f
                    .args
                    .into_iter()
                    .map(|a| Self::substitute_shape_aliases(a, defs))
                    .collect(),
                kwargs: f.kwargs,
            }),
            Expr::BinOp(b) => Expr::BinOp(Box::new(ast::BinOp {
                left: Self::substitute_shape_aliases(b.left, defs),
                op: b.op,
                right: Self::substitute_shape_aliases(b.right, defs),
            })),
            Expr::UnaryOp(u) => Expr::UnaryOp(Box::new(ast::UnaryOp {
                op: u.op,
                operand: Self::substitute_shape_aliases(u.operand, defs),
            })),
            other => other,
        }
    }

    /// `array_agg(array_unpack(X))` — the aggregate runs over the elements the
    /// array unpacks to. PostgreSQL rejects a set-returning call inside an
    /// aggregate ("aggregate function calls cannot contain set-returning
    /// function calls"), so the unpacking moves to a row source of its own and
    /// the aggregate reads that from outside. `None` when the result is not an
    /// aggregate over an unpacked array, leaving the ordinary routes to it.
    fn aggregate_over_unpacked(
        &mut self,
        sel: &ast::SelectStmt,
        result: &Expr,
        distinct: bool,
    ) -> Result<Option<IrExpr>, PyQLError> {
        let Expr::FunctionCall(f) = result else {
            return Ok(None);
        };
        let [Expr::FunctionCall(unpack)] = f.args.as_slice() else {
            return Ok(None);
        };
        if !f.kwargs.is_empty()
            || !unpack.kwargs.is_empty()
            || unpack.module.as_deref().unwrap_or("std") != "std"
            || unpack.name != "array_unpack"
        {
            return Ok(None);
        }
        let [array] = unpack.args.as_slice() else {
            return Ok(None);
        };
        let namespace = f.module.as_deref().unwrap_or("std");
        let Some(sql_name) =
            crate::stdlib::lookup(namespace, &f.name)
                .into_iter()
                .find_map(|d| match &d.impl_strategy {
                    crate::stdlib::ImplStrategy::SqlBuiltin(sql_name) if d.is_aggregate() => Some(sql_name.to_string()),
                    _ => None,
                })
        else {
            return Ok(None);
        };

        // A walk is unpacked one row at a time, so the unnest belongs in that
        // walk's own projection; anything else is a single array standing on
        // its own and unnests directly.
        let elements = match array {
            Expr::Path(path) if !path.partial && path.steps.len() > 1 => {
                let walk = ast::Path {
                    partial: false,
                    steps: path.steps.clone(),
                };
                let mut path_select = self.compile_path_select(sel, &walk, &[], distinct)?;
                let IrPathResult::Scalar(column, _) = path_select.result else {
                    return Ok(None);
                };
                path_select.result = IrPathResult::Scalar(
                    IrExpr::FunctionCall(IrFunctionCall {
                        return_pg_type: None,
                        schema: None,
                        name: "unnest".to_string(),
                        args: vec![column],
                        sql_template: None,
                    }),
                    None,
                );
                IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(path_select))))
            }
            _ if sel.filter.is_none()
                && sel.order_by.is_empty()
                && sel.offset.is_none()
                && sel.limit.is_none()
                && !distinct =>
            {
                self.compile_expr_ctx(array, None)?
            }
            _ => return Ok(None),
        };

        // Over no rows SQL's aggregates give NULL where Gel's give the empty
        // set's own value.
        let over_nothing = aggregate_over_nothing_sql(&f.name).unwrap_or("NULL");
        Ok(Some(IrExpr::FunctionCall(IrFunctionCall {
            return_pg_type: None,
            schema: None,
            name: sql_name.clone(),
            args: vec![elements],
            sql_template: Some(format!(
                "(SELECT coalesce({sql_name}(\"_s\".\"v\"), {over_nothing}) FROM unnest($1) AS \"_s\"(\"v\"))"
            )),
        })))
    }

    /// Compile an expression that contains a type-rooted absolute path as a flat
    /// path select, iterating over the root type and projecting the expression as
    /// a scalar computed pointer.
    fn compile_expr_as_path_select(
        &mut self,
        sel: &ast::SelectStmt,
        result: &Expr,
        root_type_name: &str,
        distinct: bool,
    ) -> Result<IrPathSelect, PyQLError> {
        // `array_agg(a.sessions.id)` — a single-argument aggregate over a
        // path. The aggregate applies to the set the path traverses *to*, so
        // the traversal becomes this select's own row source and the aggregate
        // wraps the column it lands on. Compiling the path as an expression
        // instead yields the array it stands for, and aggregating that nests it
        // one level deep.
        // `array_agg(distinct X.p)` — the DISTINCT belongs *inside* the
        // aggregate. The unary `distinct` emits its operand unchanged (it is
        // normally applied where the set is built, which an aggregate argument
        // is not), so left here it silently keeps the duplicates Gel drops.
        let (agg_arg, agg_distinct) = match result {
            Expr::FunctionCall(f) if f.args.len() == 1 => match &f.args[0] {
                Expr::UnaryOp(u) if matches!(u.op, ast::UnaryOpKind::Distinct) => (Some(&u.operand), true),
                other => (Some(other), false),
            },
            _ => (None, false),
        };
        if let Expr::FunctionCall(f) = result
            && f.args.len() == 1
            && let Some(Expr::Path(p)) = agg_arg
            && !p.partial
            && p.steps.len() > 1
        {
            let arg_path = ast::Path {
                partial: false,
                steps: p.steps.clone(),
            };
            let mut ps = self.compile_path_select(sel, &arg_path, &[], distinct)?;
            // A walk onto objects (`count(.<brand[is Licence])`) is counted by
            // its rows, which is its key. Falling through instead put the
            // aggregate back through the expression route that sent it here.
            let aggregated = match ps.result.clone() {
                IrPathResult::Scalar(column, _) => Some(column),
                IrPathResult::Object { alias, .. } => Some(IrExpr::ColumnRef {
                    alias,
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                }),
            };
            if let Some(column) = aggregated {
                let mut args = vec![column];
                if !f.kwargs.is_empty() {
                    if !matches!(f.name.as_str(), "assert_single" | "assert_exists" | "assert_distinct") {
                        return Err(self.type_err(&format!(
                            "function '{}' does not take named arguments, got '{}'",
                            f.name, f.kwargs[0].0
                        )));
                    }
                    args.extend(self.assert_message(f, None)?);
                }
                let mut call = self.resolve_fn_call(f.module.as_deref(), &f.name, args)?;
                if agg_distinct {
                    let IrExpr::FunctionCall(fc) = &mut call else {
                        return Err(self.type_err(&format!(
                            "'{}' does not take a distinct argument — it does not resolve to an aggregate",
                            f.name
                        )));
                    };
                    if fc.schema.is_some() || fc.sql_template.is_some() {
                        return Err(self.type_err(&format!(
                            "'distinct' inside '{}' is not supported — only a plain SQL aggregate can take it",
                            f.name
                        )));
                    }
                    fc.sql_template = Some(format!("{}(DISTINCT $1)", fc.name));
                }
                ps.result = IrPathResult::Scalar(aggregate_over_nothing(&f.name, call), None);
                return Ok(ps);
            }
        }

        // BinOp where one side is the absolute type-rooted path:
        // Build the join chain for the path side, then apply the comparison
        // element-wise so we get one boolean per traversal element (not one EXISTS per root).
        if let Expr::BinOp(b) = result {
            let (path_expr, value_expr, flip) = match (&b.left, &b.right) {
                (Expr::Path(p), v) if !p.partial => (p, v, false),
                (v, Expr::Path(p)) if !p.partial => (p, v, true),
                _ => return self.compile_expr_as_path_select_fallback(sel, result, root_type_name, distinct),
            };
            // Compile value side first so we can report its type in errors
            let root_td = match self.cte_object_type(root_type_name) {
                Some(t) => self.resolve_type(&t)?,
                None => self.resolve_type(root_type_name)?,
            };
            // Build PathSelect for the path (builds root + joins + scalar/object result)
            let ast_path = ast::Path {
                partial: false,
                steps: path_expr.steps.clone(),
            };
            let mut ps = self.compile_path_select(sel, &ast_path, &[], distinct)?;
            let val_ir = self.compile_expr(value_expr, root_td, &ps.root.alias)?;
            // Extract the scalar result from the path
            let scalar_col = match ps.result {
                IrPathResult::Scalar(e, _) => e,
                IrPathResult::Object { type_name, .. } => {
                    let val_type = infer_ir_type(&val_ir).map(pg_type_to_pyql).unwrap_or("unknown");
                    return Err(PyQLError::Type(PyQLTypeError {
                        message: format!(
                            "operator '{}' cannot be applied to operands of type '{}' and '{}'",
                            b.op, type_name, val_type,
                        ),
                        position: Position { line: 0, col: 0 },
                    }));
                }
            };
            let (l, r) = if flip {
                (val_ir, scalar_col)
            } else {
                (scalar_col, val_ir)
            };
            ps.result = IrPathResult::Scalar(
                IrExpr::BinOp(Box::new(IrBinOp {
                    left: true_division_operand(&b.op, l, &r),
                    op: b.op.clone(),
                    right: r,
                })),
                None,
            );
            return Ok(ps);
        }
        self.compile_expr_as_path_select_fallback(sel, result, root_type_name, distinct)
    }

    fn compile_expr_as_path_select_fallback(
        &mut self,
        sel: &ast::SelectStmt,
        result: &Expr,
        root_type_name: &str,
        distinct: bool,
    ) -> Result<IrPathSelect, PyQLError> {
        let cte_object_type = self.cte_object_type(root_type_name);
        let td = match &cte_object_type {
            Some(t) => self.resolve_type(t)?,
            None => self.resolve_type(root_type_name)?,
        };
        let alias = self.fresh_alias();
        let root = IrSource {
            poly: None,
            type_name: format!("{}::{}", td.module, td.name),
            table: match &cte_object_type {
                Some(_) => format!("@cte:{}", root_type_name),
                None => td.table.clone(),
            },
            alias: alias.clone(),
        };
        let rewritten = Self::rewrite_abs_to_partial(result.clone(), root_type_name);
        let expr = self.compile_expr(&rewritten, td, &alias)?;
        let (filter, order_by, offset, limit) = self.compile_path_modifiers(sel, td, &alias)?;
        Ok(IrPathSelect {
            root,
            joins: vec![],
            result: IrPathResult::Scalar(expr, None),
            filter,
            order_by,
            offset,
            limit,
            distinct,
            poly_implementors: vec![],
        })
    }

    /// Compile a SubQuery stmt to an `IrArraySource` for use in assert functions.
    /// The result is `ARRAY(SELECT scalar FROM compiled_inner)`.
    fn compile_subquery_to_array_source(&mut self, stmt: &Stmt) -> Result<IrArraySource, PyQLError> {
        match self.compile_stmt(stmt)? {
            IrStmt::Select(s) if matches!(s.rows.as_slice(), [IrRowSource::Bound { .. }]) => {
                Ok(IrArraySource::Select(s))
            }
            IrStmt::PathSelect(ps) => Ok(IrArraySource::PathSelect(Box::new(ps))),
            _ => Err(self.type_err("assert functions require a schema-bound SELECT as argument")),
        }
    }

    /// `exists` in either schema-bound (FILTER, computed pointer, etc. —
    /// `ctx = Some((td, alias))`) or free (`ctx = None`) expression context.
    /// The `Path`-based arms (backlink / prop / link / multilink existence)
    /// only apply schema-bound — guarded on `ctx.is_some()` — since none of
    /// those concepts exist without a schema type in scope; everything else
    /// (`Parameter`, `TypeCast`, `SubQuery`, and the scalar-expression
    /// fallback) is identical either way and just threads `ctx` through.
    fn compile_exists_ctx(
        &mut self,
        operand: &Expr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<IrExpr, PyQLError> {
        match operand {
            // exists $param  /  exists <type>$param → $N IS NOT NULL
            Expr::Parameter(name) => {
                let idx = self.param_index(name);
                Ok(ir_is_not_null(IrExpr::Param { index: idx }))
            }
            // exists <type>expr → expr IS NOT NULL (cast result is always a scalar)
            Expr::TypeCast(_) => {
                let inner = self.compile_expr_ctx(operand, ctx)?;
                Ok(ir_is_not_null(inner))
            }

            // exists .<link[is Type] → EXISTS(SELECT 1 FROM type WHERE type.link_id = alias.id)
            Expr::Path(p)
                if ctx.is_some() && p.partial && matches!(p.steps.first(), Some(ast::PathStep::Backlink(_))) =>
            {
                let (td, alias) = ctx.unwrap();
                let current_qname = format!("{}::{}", td.module, td.name);
                let exists = self.compile_backlink_as_exists(&p.steps, None, &current_qname, alias)?;
                Ok(exists)
            }

            // exists .prop → alias.col IS NOT NULL
            // exists .link → alias.link_id IS NOT NULL
            // exists .multilink → EXISTS(SELECT 1 FROM junction WHERE src = alias.id)
            Expr::Path(p) if ctx.is_some() && p.partial && p.steps.len() == 1 => {
                let (td, alias) = ctx.unwrap();
                // `exists @dismissed` — a link property is a column on the
                // junction row the multi-link's own modifiers are being
                // compiled against, so whether it is set is an ordinary null
                // check on it.
                if let ast::PathStep::LinkProp(prop_name) = &p.steps[0] {
                    let prop = self.compile_link_prop_ref(prop_name)?;
                    return Ok(ir_is_not_null(prop));
                }
                // `filter exists .n` where the shape in scope declared `n` —
                // the pointer is on no type, so it is read as the expression it
                // was written as.
                if let ast::PathStep::Name(n) = &p.steps[0]
                    && Self::resolve_property(td, n).is_none()
                    && Self::resolve_link(td, n).is_none()
                    && Self::resolve_multilink(td, n).is_none()
                    && self.resolve_computed(td, n).is_none()
                    && let Some(expr) = self
                        .active_declared_pointers
                        .iter()
                        .find(|d| path_leaf(&d.path).is_ok_and(|name| name == n))
                        .and_then(|d| d.compexpr.clone())
                {
                    let inner = self.compile_expr(&expr, td, alias)?;
                    return Ok(ir_is_not_null(inner));
                }
                // `exists [is contact::IndividualContact]` — a bare narrowing
                // is the current row seen as that type, so whether it exists is
                // whether the row *is* one.
                if let ast::PathStep::TypeIntersection(type_ref) = &p.steps[0] {
                    let narrowed = self.resolve_type(&type_ref.qualified_name())?;
                    let check = format!("{}::{}", narrowed.module, narrowed.name);
                    let source = format!("{}::{}", td.module, td.name);
                    return Ok(self.type_check_bool_expr(&source, &check, td, alias));
                }
                let pointer_name = match &p.steps[0] {
                    ast::PathStep::Name(n) => n.as_str(),
                    _ => return Err(self.type_err("exists: invalid path step")),
                };
                if let Some(prop) = Self::resolve_property(td, pointer_name) {
                    return Ok(ir_is_not_null(IrExpr::ColumnRef {
                        alias: alias.to_string(),
                        column: prop.name.clone(),
                        pg_type: prop.pg_type.clone(),
                    }));
                }
                if let Some(link) = Self::resolve_link(td, pointer_name) {
                    if link.is_junction_backed() {
                        return self.compile_junction_link_exists_check(link, td, alias);
                    }
                    return Ok(ir_is_not_null(IrExpr::ColumnRef {
                        alias: alias.to_string(),
                        column: format!("{}_id", link.name),
                        pg_type: "uuid".to_string(),
                    }));
                }
                if Self::resolve_multilink(td, pointer_name).is_some() {
                    return self.compile_multilink_exists_check(pointer_name, td, alias);
                }
                // `exists .primary_email` — a computed pointer stands for the
                // path it names, and whether *that* is empty is the question.
                // Checked last, so a stored pointer of the same name still
                // wins; without it the suggester could see the name the
                // resolver had just reported as unknown.
                if let Some(cd) = self.resolve_computed(td, pointer_name) {
                    let expr_ast = crate::parse::parse_pointer_expr(&cd.expression).map_err(PyQLError::Syntax)?;
                    return self.compile_exists_ctx(&expr_ast, ctx);
                }
                Err(self.field_err(pointer_name, &format!("{}::{}", td.module, td.name)))
            }

            // `exists ((select .prices filter …))` — a sub-select over a
            // relative path is relative to the enclosing object, so it needs
            // the same rooting and correlation `count((select .prices))`
            // already gets. Compiled without them it resolves in free context
            // and reports the pointer as unknown.
            Expr::SubQuery(stmt)
                if ctx.is_some()
                    && matches!(
                        stmt.as_ref(),
                        Stmt::Select(inner) if matches!(&inner.result, Expr::Path(p) if p.partial)
                    ) =>
            {
                let Stmt::Select(inner) = stmt.as_ref() else {
                    unreachable!("checked by the guard")
                };
                let Expr::Path(path) = &inner.result else {
                    unreachable!("checked by the guard")
                };
                let (td, alias) = ctx.expect("checked by the guard");
                let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
                steps.extend(path.steps.iter().cloned());
                let full_path = ast::Path { steps, partial: false };
                let rooted = ast::SelectStmt {
                    result: Expr::Path(full_path.clone()),
                    filter: inner.filter.clone(),
                    order_by: inner.order_by.clone(),
                    offset: inner.offset.clone(),
                    limit: inner.limit.clone(),
                    lock: None,
                };
                let mut ps = self.compile_path_select(&rooted, &full_path, &[], false)?;
                Self::correlate_path_select(&mut ps, alias);
                Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
                    op: ast::UnaryOpKind::Exists,
                    operand: IrExpr::PathSubquery(Box::new(ps)),
                })))
            }

            // exists (select ...) → EXISTS(SELECT 1 FROM ...)
            Expr::SubQuery(stmt) => self.compile_subquery_exists(stmt),

            // `exists licenses` — a binding names a set, so it exists when it
            // has a row; the fallback's scalar subquery aborts on the second.
            operand if let Some(name) = self.resolve_cte_name(operand) => {
                let object = self.cte_types.get(name).is_some_and(|bound| bound.contains("::"));
                Ok(IrExpr::ExistsOverCte {
                    cte: name.to_string(),
                    column: (!object).then(|| "v".to_string()),
                })
            }

            // Fallback: any scalar expression → expr IS NOT NULL. When `ctx`
            // is `None` and `operand` is a partial `Path` not caught above
            // (guards failed since ctx.is_some() was false), this recurses
            // into the free-context Path handling, which itself produces the
            // "not valid in free SELECT" error — same as before the merge.
            other => {
                let inner = self.compile_expr_ctx(other, ctx)?;
                // A set operation already knows how to ask whether it yields
                // anything; going through the array would build it first.
                if let IrExpr::SetOp { op, left, right, .. } = inner {
                    return Ok(IrExpr::SetOp {
                        op,
                        left,
                        right,
                        mode: super::SetOpMode::Exists,
                    });
                }
                Ok(ir_is_not_null(inner))
            }
        }
    }

    /// Compile `exists (select ...)` → `EXISTS(SELECT 1 FROM ... WHERE ...)`.
    fn compile_subquery_exists(&mut self, stmt: &Stmt) -> Result<IrExpr, PyQLError> {
        match self.compile_stmt(stmt)? {
            IrStmt::Select(s) => {
                let mut rows = s.rows;
                if rows.len() != 1 {
                    return Err(self.type_err("exists requires a schema-bound SELECT expression"));
                }
                let IrRowSource::Bound { source, .. } = rows.remove(0) else {
                    return Err(self.type_err("exists requires a schema-bound SELECT expression"));
                };
                let inner = IrExpr::Subquery(Box::new(IrSelect::schema_bound(source, vec![], s.filter)));
                Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
                    op: ast::UnaryOpKind::Exists,
                    operand: inner,
                })))
            }
            IrStmt::PathSelect(ps) => {
                // EXISTS(SELECT 1 FROM root [JOINs] WHERE filter)
                // Reuse the path select but signal "exists" via a dedicated IR node
                Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
                    op: ast::UnaryOpKind::Exists,
                    operand: IrExpr::Subquery(Box::new(IrSelect::schema_bound(ps.root, vec![], ps.filter))),
                })))
            }
            _ => Err(self.type_err("exists requires a SELECT expression")),
        }
    }

    /// `EXISTS(SELECT 1 FROM junction WHERE junction.source = alias.id)` for a multi-link.
    /// Build the `IrSelect` over the junction/FK-target rows for a multilink,
    /// correlated to the current row (`alias.id`) — shared by `exists
    /// .multilink` and `count(.multilink)`.
    /// `EXISTS(SELECT 1 FROM junction WHERE junction.<source_col> = alias.id)`,
    /// correlated to the current row — shared by a multi-link's own `exists
    /// .multilink`/`count(.multilink)` and a junction-backed single link's
    /// `exists .link` (D2: same junction-info resolution either way).
    fn junction_correlation_select(
        &mut self,
        td: &TypeDescriptor,
        alias: &str,
        name: &str,
        target: &str,
        through: &Option<String>,
    ) -> Result<IrSelect, PyQLError> {
        let jt_alias = self.fresh_alias();
        let (jt_table, jt_module, jt_src_col, _, _) = self.junction_info_for(td, name, target, through)?;

        let filter = IrExpr::BinOp(Box::new(IrBinOp {
            left: IrExpr::ColumnRef {
                alias: jt_alias.clone(),
                column: jt_src_col,
                pg_type: "uuid".to_string(),
            },
            op: ast::BinOpKind::Eq,
            right: IrExpr::ColumnRef {
                alias: alias.to_string(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
        }));
        Ok(IrSelect::schema_bound(
            IrSource {
                poly: None,
                type_name: format!("{}::__jt__", jt_module),
                table: jt_table,
                alias: jt_alias,
            },
            vec![],
            Some(filter),
        ))
    }

    fn multilink_correlation_select(
        &mut self,
        ml_name: &str,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<IrSelect, PyQLError> {
        let ml = Self::resolve_multilink(td, ml_name).unwrap();
        let (name, target, through) = (ml.name.clone(), ml.target.clone(), ml.through.clone());
        self.junction_correlation_select(td, alias, &name, &target, &through)
    }

    fn compile_multilink_exists_check(
        &mut self,
        ml_name: &str,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        let inner = self.multilink_correlation_select(ml_name, td, alias)?;
        Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
            op: ast::UnaryOpKind::Exists,
            operand: IrExpr::Subquery(Box::new(inner)),
        })))
    }

    /// Same as `compile_multilink_exists_check`, for `exists .link` where
    /// `link` is a junction-backed single link.
    fn compile_junction_link_exists_check(
        &mut self,
        l: &LinkDescriptor,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        let (name, target, through) = (l.name.clone(), l.target.clone(), l.through.clone());
        let inner = self.junction_correlation_select(td, alias, &name, &target, &through)?;
        Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
            op: ast::UnaryOpKind::Exists,
            operand: IrExpr::Subquery(Box::new(inner)),
        })))
    }

    /// A junction-backed single link's target id, as a scalar correlated
    /// subquery — `(SELECT jt.<target_col> FROM junction AS jt WHERE
    /// jt.<source_col> = alias.id)`. Stands in wherever a plain single
    /// link's `{name}_id` FK column would otherwise be referenced directly
    /// as a scalar uuid expression (bare `.link` in a filter/order-by,
    /// `.link.id`, or correlating `.link.<other prop>`).
    fn junction_target_id_expr(
        &mut self,
        td: &TypeDescriptor,
        l: &LinkDescriptor,
        alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        let (name, target, through) = (l.name.clone(), l.target.clone(), l.through.clone());
        let (jt_table, jt_module, jt_src_col, jt_tgt_col, _) = self.junction_info_for(td, &name, &target, &through)?;
        let jt_alias = self.fresh_alias();
        let filter = IrExpr::BinOp(Box::new(IrBinOp {
            left: IrExpr::ColumnRef {
                alias: jt_alias.clone(),
                column: jt_src_col,
                pg_type: "uuid".to_string(),
            },
            op: ast::BinOpKind::Eq,
            right: IrExpr::ColumnRef {
                alias: alias.to_string(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
        }));
        let select = IrSelect::schema_bound(
            IrSource {
                poly: None,
                type_name: format!("{}::__jt__", jt_module),
                table: jt_table,
                alias: jt_alias,
            },
            vec![IrShapePointer::Scalar(IrScalarPointer {
                implicit_id: false,
                marker_offset: None,
                alias: "target".to_string(),
                column: jt_tgt_col,
                pg_type: "uuid".to_string(),
                tuple_shape: None,
            })],
            Some(filter),
        );
        Ok(IrExpr::Subquery(Box::new(select)))
    }

    /// Returns true when the SELECT result expression is not a schema type reference.
    /// Check that a UNION expression doesn't mix object types with scalars.
    /// Called before dispatch so we can give a clear error instead of "expected a type name".
    fn check_union_type_compat(&self, expr: &Expr) -> Result<(), PyQLError> {
        let Expr::Union(a, b) = expr else { return Ok(()) };
        let a_free = self.is_free_result(a);
        let b_free = self.is_free_result(b);
        if a_free != b_free {
            let left = self.union_operand_type_display(a);
            let right = self.union_operand_type_display(b);
            return Err(PyQLError::Type(PyQLTypeError {
                message: format!(
                    "operator 'UNION' cannot be applied to operands of type '{}' and '{}'",
                    left, right,
                ),
                position: Position { line: 0, col: 0 },
            }));
        }
        Ok(())
    }

    fn union_operand_type_display(&self, expr: &Expr) -> String {
        match expr {
            Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
                if let ast::PathStep::Name(n) = &p.steps[0]
                    && let Some(t) = self.cte_types.get(n.as_str())
                {
                    if t.contains("::") {
                        return t.clone(); // object CTE: "default::Person"
                    }
                    if !t.is_empty() {
                        return pg_type_to_pyql(t).to_string(); // scalar CTE: "std::int64"
                    }
                }
                // Bare type name reference
                if let Ok(td) = self.resolve_type(
                    p.steps
                        .first()
                        .and_then(|s| {
                            if let ast::PathStep::Name(n) = s {
                                Some(n.as_str())
                            } else {
                                None
                            }
                        })
                        .unwrap_or(""),
                ) {
                    return format!("{}::{}", td.module, td.name);
                }
            }
            Expr::Literal(Literal::Int(_)) => return "std::int64".to_string(),
            Expr::Literal(Literal::Str(_)) => return "std::str".to_string(),
            Expr::Literal(Literal::Float(_)) => return "std::float64".to_string(),
            Expr::Literal(Literal::Bool(_)) => return "std::bool".to_string(),
            _ => {}
        }
        "unknown".to_string()
    }

    fn is_free_result(&self, expr: &Expr) -> bool {
        let expr = match expr {
            Expr::UnaryOp(u) if u.op == ast::UnaryOpKind::Distinct => &u.operand,
            Expr::Detached(inner) => inner.as_ref(),
            other => other,
        };
        match expr {
            Expr::Path(p) if !p.partial => {
                if p.steps.len() == 1
                    && let ast::PathStep::Name(n) = &p.steps[0]
                {
                    // A for-loop variable over values is a scalar; one over
                    // objects stands for a row, and `select c` is a schema-
                    // bound select of its type.
                    if self.for_vars.contains_key(n.as_str()) {
                        return !self.for_var_types.contains_key(n.as_str());
                    }
                    // Scalar CTE: type string has no "::" (object types always do).
                    if self.is_value_binding(n.as_str()) {
                        return true;
                    }
                    // Function parameter — only populated while compiling a
                    // function body (see `compile_fn_body`), so a bare `select a`
                    // where `a` is a param must resolve as the param, not be
                    // misread as a schema-type-name select.
                    if self.fn_params.contains_key(n.as_str()) {
                        return true;
                    }
                }
                false
            }
            Expr::Shape(s) if s.expr.is_some() => false,
            Expr::SubQuery(_) => false,
            Expr::Union(a, b) => self.is_free_result(a) && self.is_free_result(b),
            // `A if cond else B` picks between two *sets*; when those are
            // object sets the result is an object set too, not the scalar an
            // if/else over values gives. An empty branch says nothing about
            // which it is, so it does not get a vote.
            Expr::IfElse(ie) => {
                let empty = |e: &Expr| matches!(e, Expr::Set(items) if items.is_empty());
                match (empty(&ie.if_expr), empty(&ie.else_expr)) {
                    (true, true) => true,
                    (true, false) => self.is_free_result(&ie.else_expr),
                    (false, true) => self.is_free_result(&ie.if_expr),
                    (false, false) => self.is_free_result(&ie.if_expr) || self.is_free_result(&ie.else_expr),
                }
            }
            _ => true,
        }
    }

    /// True when `expr` is a bare 1-step name bound to a free (non-object)
    /// WITH binding — the same "scalar CTE" check `is_free_result` uses for
    /// its `Expr::Path` arm, factored out so `Expr::Shape`'s handling of
    /// "shape applied to a non-object" can reuse it too.
    fn is_free_cte_ref(&self, expr: &Expr) -> bool {
        let Expr::Path(p) = expr else { return false };
        if p.partial || p.steps.len() != 1 {
            return false;
        }
        let ast::PathStep::Name(n) = &p.steps[0] else {
            return false;
        };
        self.is_value_binding(n.as_str())
    }

    // ── FREE SELECT ───────────────────────────────────────────────────────────────

    /// A mutation standing where a value is expected. Postgres cannot run DML
    /// in a value list, so it becomes a data-modifying CTE — which it runs to
    /// completion whether or not the outer query reads it — and what stands
    /// here reads the ids back, so the value still names the rows the
    /// mutation touched.
    fn dml_as_value(&mut self, stmt: &Stmt) -> Result<IrExpr, PyQLError> {
        let (cte_name, type_name) = self.hoist_dml_as_cte(stmt)?;
        // Read back through a subquery rather than naming the CTE's column
        // directly: a free select has no FROM of its own for the reference to
        // resolve against.
        let source = IrSource {
            poly: None,
            type_name,
            table: format!("@cte:{cte_name}"),
            alias: self.fresh_alias(),
        };
        Ok(IrExpr::Subquery(Box::new(IrSelect::schema_bound(
            source,
            // An empty shape would emit the `SELECT 1` an EXISTS wants, which
            // says nothing about which rows the value stands for.
            vec![IrShapePointer::Scalar(IrScalarPointer {
                implicit_id: false,
                marker_offset: None,
                alias: "id".to_string(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
                tuple_shape: None,
            })],
            None,
        ))))
    }

    fn collect_union_items(&mut self, expr: &Expr, items: &mut Vec<IrFreeExpr>) -> Result<(), PyQLError> {
        match expr {
            Expr::Union(a, b) => {
                self.collect_union_items(a, items)?;
                self.collect_union_items(b, items)?;
            }
            Expr::Set(exprs) => {
                for e in exprs {
                    self.collect_union_items(e, items)?;
                }
            }
            // `select { (update A set …), (update B set …) }` — several
            // mutations in one statement. Postgres cannot run DML in a value
            // list, so each becomes a data-modifying CTE, which it runs to
            // completion whether or not the outer query reads it; the item
            // itself reads back the id, so the set still stands for the rows
            // the mutations touched.
            Expr::SubQuery(stmt) if matches!(stmt.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_)) => {
                items.push(IrFreeExpr::Scalar(self.dml_as_value(stmt.as_ref())?));
            }
            other => {
                items.push(IrFreeExpr::Scalar(self.compile_free_expr(other)?));
            }
        }
        Ok(())
    }

    /// `metadata := metadata { author }` — a shape over a `with` binding or a
    /// for-loop variable. Both name a row source, so the shape reads their
    /// rows; a bare type name is deliberately not accepted here, because in an
    /// enclosing scope that prefix is factored (see `outer_anchor`) and would
    /// mean the outer row rather than the whole table.
    fn shape_over_binding(&mut self, expr: &Expr) -> Result<Option<IrExpr>, PyQLError> {
        let Expr::Shape(sh) = expr else {
            return Ok(None);
        };
        let Some(Expr::Path(p)) = sh.expr.as_ref() else {
            return Ok(None);
        };
        let Some(ast::PathStep::Name(root)) = p.steps.first() else {
            return Ok(None);
        };
        if p.partial || (self.cte_object_type(root).is_none() && !self.for_var_types.contains_key(root)) {
            return Ok(None);
        }
        self.free_object_link_field(expr)
    }

    /// A free object's field holding an object with a shape (`{ device := d
    /// { id } }`). Gel compiles a free shape into a real object type whose
    /// fields are real pointers, so an object field stays an object; without
    /// this it would compile to the object's bare id, which is not what was
    /// asked for.
    fn free_object_link_field(&mut self, expr: &Expr) -> Result<Option<IrExpr>, PyQLError> {
        let Expr::Shape(sh) = expr else {
            return Ok(None);
        };
        let Some(Expr::Path(p)) = sh.expr.as_ref() else {
            return Ok(None);
        };
        if p.partial {
            return Ok(None);
        }
        let rest_steps = p.steps.as_slice();
        let Some(ast::PathStep::Name(name)) = rest_steps.first() else {
            return Ok(None);
        };
        let cte_name = self.cte_object_type(name).map(|_| name.clone());
        let Ok(td) = self.resolve_path_root(name) else {
            return Ok(None);
        };
        let table = self.row_source_table(name, td);
        // `account := resource.account { id }` — the field holds what a walk
        // off the binding lands on, so it is that walk with the shape on it
        // rather than a plain read of the binding.
        if rest_steps.len() > 1 {
            let synthetic = ast::SelectStmt {
                result: Expr::Path(p.clone()),
                filter: None,
                order_by: vec![],
                offset: None,
                limit: None,
                lock: None,
            };
            let path_select = self.compile_path_select(&synthetic, p, &sh.elements, false)?;
            return Ok(Some(IrExpr::ObjectPathSubquery(Box::new(path_select))));
        }
        let alias = self.fresh_alias();
        let source = IrSource {
            poly: self.poly_fanout_for(&format!("{}::{}", td.module, td.name)),
            type_name: format!("{}::{}", td.module, td.name),
            table,
            alias: alias.clone(),
        };
        // Same as reading the binding by name: its own shape may have
        // declared pointers that exist on no type.
        let outer_declared = std::mem::replace(
            &mut self.active_declared_pointers,
            cte_name
                .as_deref()
                .and_then(|n| self.cte_declared_pointers.get(n).cloned())
                .unwrap_or_default(),
        );
        let shape = self.compile_shape(&sh.elements, td, &alias, &td.module);
        self.active_declared_pointers = outer_declared;
        // A for-loop variable holds one row's key, so the select has to be
        // narrowed to it -- unfiltered it would read the whole table.
        let filter = self.for_var_types.contains_key(name).then(|| {
            IrExpr::BinOp(Box::new(IrBinOp {
                left: IrExpr::ColumnRef {
                    alias: alias.clone(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
                op: ast::BinOpKind::Eq,
                right: self.for_var_ref(name),
            }))
        });
        Ok(Some(IrExpr::ObjectSubquery(Box::new(IrSelect::schema_bound(
            source, shape?, filter,
        )))))
    }

    /// One field of a free object written as a whole SELECT's result. A
    /// mutation is allowed here for the same reason it is allowed as an item
    /// of a free set — see `dml_as_value`.
    fn free_object_field(&mut self, expr: &Expr) -> Result<IrExpr, PyQLError> {
        if let Some(object) = self.free_object_link_field(expr)? {
            return Ok(object);
        }
        match expr {
            Expr::SubQuery(stmt) if matches!(stmt.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_)) => {
                self.dml_as_value(stmt.as_ref())
            }
            other => self.compile_free_expr(other),
        }
    }

    fn compile_free_select(
        &mut self,
        sel: &ast::SelectStmt,
        result_expr: &Expr,
        distinct: bool,
    ) -> Result<IrSelect, PyQLError> {
        // `{ a := 1 } if cond else {}` — read as a scalar `CASE` it comes back
        // as a bare record instead of an object, so the object is the row and
        // the condition decides whether there is one.
        if let Expr::IfElse(ie) = result_expr {
            let is_empty_set = |expr: &Expr| matches!(expr, Expr::Set(items) if items.is_empty());
            let is_free_object = |expr: &Expr| matches!(expr, Expr::Shape(sh) if sh.expr.is_none());
            let guarded = if is_free_object(&ie.if_expr) && is_empty_set(&ie.else_expr) {
                Some((&ie.if_expr, false))
            } else if is_empty_set(&ie.if_expr) && is_free_object(&ie.else_expr) {
                Some((&ie.else_expr, true))
            } else {
                None
            };
            if let Some((object, negated)) = guarded {
                let condition = self.compile_free_expr(&ie.condition)?;
                let condition = if negated {
                    IrExpr::UnaryOp(Box::new(IrUnaryOp {
                        op: ast::UnaryOpKind::Not,
                        operand: condition,
                    }))
                } else {
                    condition
                };
                let mut select = self.compile_free_select(sel, object, distinct)?;
                select.filter = and_conditions(select.filter, vec![condition]);
                return Ok(select);
            }
        }
        let items: Vec<IrFreeExpr> = match result_expr {
            Expr::Union(_, _) | Expr::Set(_) => {
                let mut union_items = vec![];
                self.collect_union_items(result_expr, &mut union_items)?;
                // Type-check UNION operands: all scalar branches must be in the same type family.
                let mut first: Option<(String, String)> = None; // (pg_type, pyql_name)
                for item in &union_items {
                    if let IrFreeExpr::Scalar(expr) = item
                        && let Some(t) = infer_ir_type(expr)
                    {
                        let t = t.to_string();
                        if let Some((ft, fq)) = &first {
                            if !types_compatible(ft, &t) {
                                return Err(PyQLError::Type(PyQLTypeError {
                                    message: format!(
                                        "operator 'UNION' cannot be applied to operands of type '{}' and '{}'",
                                        fq,
                                        pg_type_to_pyql(&t),
                                    ),
                                    position: Position { line: 0, col: 0 },
                                }));
                            }
                        } else {
                            first = Some((t.clone(), pg_type_to_pyql(&t).to_string()));
                        }
                    }
                }
                union_items
            }
            Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
                if let ast::PathStep::Name(n) = &p.steps[0] {
                    if self
                        .cte_types
                        .get(n.as_str())
                        .map(|t| !t.contains("::"))
                        .unwrap_or(false)
                    {
                        vec![IrFreeExpr::CtePassthrough(n.clone())]
                    } else {
                        vec![IrFreeExpr::Scalar(self.compile_free_expr(result_expr)?)]
                    }
                } else {
                    vec![IrFreeExpr::Scalar(self.compile_free_expr(result_expr)?)]
                }
            }
            Expr::Shape(s) if s.expr.is_none() => {
                let fields = s
                    .elements
                    .iter()
                    .map(|el| -> Result<(String, IrExpr), PyQLError> {
                        let name = path_leaf(&el.path)?.to_string();
                        let expr = el.compexpr.as_ref().ok_or_else(|| {
                            self.type_err("free object field must have a value expression (':= expr')")
                        })?;
                        Ok((name, self.free_object_field(expr)?))
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                vec![IrFreeExpr::FreeObject(fields)]
            }
            Expr::Tuple(exprs) => {
                // An element may hold an object with a shape
                // (`select (offering { id }, revision { id })`), which is the
                // same question a free object's field asks.
                let ir = exprs
                    .iter()
                    .map(|e| self.free_object_field(e))
                    .collect::<Result<_, _>>()?;
                vec![IrFreeExpr::Tuple(ir)]
            }
            Expr::NamedTuple(fields) => {
                let ir = fields
                    .iter()
                    .map(|(name, e)| Ok((name.clone(), self.free_object_field(e)?)))
                    .collect::<Result<Vec<_>, PyQLError>>()?;
                // jsonb has no member kind for an object, so a tuple holding
                // one is emitted as a composite row instead; the rest stay on
                // the jsonb encoding they have always had.
                // An array of objects (`brands := array_agg((select b { * }))`)
                // flattens in jsonb the same way.
                let holds_an_object = ir.iter().any(|(_, e)| match e {
                    IrExpr::ObjectSubquery(_) | IrExpr::ObjectPathSubquery(_) => true,
                    IrExpr::ArrayFromSelect(source) => match source.as_ref() {
                        IrArraySource::ObjectSelect(_) | IrArraySource::ObjectFunction(_) | IrArraySource::Group(_) => {
                            true
                        }
                        IrArraySource::PathSelect(ps) => matches!(ps.result, IrPathResult::Object { .. }),
                        _ => false,
                    },
                    _ => false,
                });
                if holds_an_object {
                    vec![IrFreeExpr::NamedTupleRow(ir)]
                } else {
                    vec![IrFreeExpr::Scalar(IrExpr::NamedTuple {
                        fields: ir,
                        is_free_object: false,
                    })]
                }
            }
            other => vec![IrFreeExpr::Scalar(self.compile_free_expr(other)?)],
        };

        let order_by = sel
            .order_by
            .iter()
            .map(|s| self.compile_sort_ctx(s, None))
            .collect::<Result<Vec<_>, _>>()?;

        let offset = sel.offset.as_ref().map(|e| self.compile_free_expr(e)).transpose()?;
        let limit = sel.limit.as_ref().map(|e| self.compile_free_expr(e)).transpose()?;
        let filter = sel.filter.as_ref().map(|f| self.compile_free_filter(f)).transpose()?;

        Ok(IrSelect {
            rows: items.into_iter().map(IrRowSource::Free).collect(),
            filter,
            order_by,
            offset,
            limit,
            distinct,
            dml_source: None,
            polymorphic: false,
            poly_implementors: vec![],
            poly_columns: vec![],
            lock: None,
        })
    }

    /// The FILTER of a free SELECT, which has no row to apply itself to: it
    /// gates the result the select already produced.
    ///
    /// A condition over a type-rooted path is a *set* of booleans, one per row
    /// of that type, so the result survives when any of them holds — the same
    /// reading EdgeQL gives it, and the reason for the warning: a filter is
    /// meant to be one boolean, and `any()` says so outright.
    fn compile_free_filter(&mut self, filter: &Expr) -> Result<IrExpr, PyQLError> {
        let Some(root) = self.find_path_root_in_expr(filter) else {
            return self.compile_free_expr(filter);
        };
        // A binding roots a path here as readily as a type name does; resolved
        // as a type it is simply unknown.
        let td = self.resolve_path_root(&root)?;
        let table = self.row_source_table(&root, td);
        let alias = self.fresh_alias();
        let source = IrSource {
            poly: None,
            type_name: format!("{}::{}", td.module, td.name),
            table,
            alias: alias.clone(),
        };
        let condition = self.compile_expr(&Self::rewrite_abs_to_partial(filter.clone(), &root), td, &alias)?;
        self.warnings.push(format!(
            "possibly more than one element returned by an expression in a FILTER clause \
             (every '{root}'); wrap with any() to make intent explicit",
        ));
        Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
            op: ast::UnaryOpKind::Exists,
            operand: IrExpr::Subquery(Box::new(IrSelect::schema_bound(source, vec![], Some(condition)))),
        })))
    }

    // ── SELECT ────────────────────────────────────────────────────────────────────

    /// The `(qualified type, source table)` of each branch of an object-set
    /// union, or `None` if any branch is something other than a direct
    /// reference to an object set (a WITH binding or a bare type name).
    /// The type a union of object sets carries: the one branch type every
    /// other branch is or implements. `A union (insert B)` where B implements
    /// A is an A-set, which is what EdgeQL reads it as; requiring the branches
    /// to name the same type refuses a get-or-create over an interface.
    fn common_union_type(&self, branches: &[(String, String)]) -> Option<String> {
        let covers_all = |candidate: &String| {
            branches.iter().all(|(t, _)| {
                t == candidate
                    || self
                        .resolve_type(t)
                        .map(|td| Self::is_or_implements(td, candidate))
                        .unwrap_or(false)
            })
        };
        if let Some(branch) = branches.iter().map(|(t, _)| t.clone()).find(&covers_all) {
            return Some(branch);
        }
        // None of the branches is the others' supertype, but they may still
        // share one — `IncomingTransformer union OutgoingTransformer` are both
        // `Transformer`. The first branch's ancestors are the only candidates,
        // since a common type has to be among them.
        let first = self.resolve_type(&branches.first()?.0).ok()?;
        first
            .interfaces
            .iter()
            .chain(first.parents.iter())
            .find(|ancestor| covers_all(ancestor))
            .cloned()
    }

    fn object_union_branches(&self, expr: &Expr) -> Option<Vec<(String, String)>> {
        fn flatten<'e>(expr: &'e Expr, out: &mut Vec<&'e Expr>) {
            match expr {
                Expr::Union(a, b) => {
                    flatten(a, out);
                    flatten(b, out);
                }
                other => out.push(other),
            }
        }
        if !matches!(expr, Expr::Union(_, _)) {
            return None;
        }
        let mut operands: Vec<&Expr> = vec![];
        flatten(expr, &mut operands);

        let mut branches: Vec<(String, String)> = vec![];
        for operand in operands {
            let Expr::Path(path) = operand else { return None };
            if path.partial || path.steps.len() != 1 {
                return None;
            }
            let ast::PathStep::Name(name) = &path.steps[0] else {
                return None;
            };
            match self.cte_object_type(name) {
                Some(qualified) => branches.push((qualified, format!("@cte:{}", self.cte_sql_name(name)))),
                None => match self.resolve_type(name) {
                    Ok(td) => branches.push((format!("{}::{}", td.module, td.name), td.table.clone())),
                    Err(_) => return None,
                },
            }
        }
        Some(branches)
    }

    /// `select (a union b) { shape }` where every branch is a set of the same
    /// object type — a WITH binding or a bare type name. Each branch becomes
    /// its own bound row; the SQL layer unions them in the FROM clause, so the
    /// shape and modifiers are compiled once, against the shared type.
    ///
    /// `Ok(None)` when the result isn't an object union, leaving the ordinary
    /// single-source path (and its own errors) in charge.
    /// Give every operand of an object union a name to be read by.
    ///
    /// `object_union_branches` recognises operands that already name a
    /// relation -- a type, or a `with` binding -- because a union is emitted
    /// as one relation per branch. An operand written inline (a sub-select, or
    /// an insert in a get-or-create) names nothing yet, so it is hoisted into
    /// a CTE of its own and replaced by that name, leaving an ordinary union
    /// of names behind.
    fn name_union_operands(&mut self, expr: &Expr) -> Result<Option<Expr>, PyQLError> {
        let Expr::Union(left, right) = expr else {
            return Ok(None);
        };
        let mut rewritten = false;
        let mut name_one = |compiler: &mut Self, operand: &Expr| -> Result<Expr, PyQLError> {
            match operand {
                Expr::Union(_, _) => match compiler.name_union_operands(operand)? {
                    Some(inner) => {
                        rewritten = true;
                        Ok(inner)
                    }
                    None => Ok(operand.clone()),
                },
                Expr::SubQuery(stmt) => {
                    let (cte_name, type_name) = compiler.hoist_dml_as_cte(stmt.as_ref())?;
                    // An insert names its subject unqualified (`Credentials`),
                    // a select yields an already-qualified name; a branch that
                    // resolves to no object type is not one of these at all.
                    let Ok(td) = compiler.resolve_type(&type_name) else {
                        return Ok(operand.clone());
                    };
                    compiler
                        .cte_types
                        .insert(cte_name.clone(), format!("{}::{}", td.module, td.name));
                    rewritten = true;
                    Ok(Expr::Path(ast::Path {
                        steps: vec![ast::PathStep::Name(cte_name)],
                        partial: false,
                    }))
                }
                // `a.answers.question union a.current_question` — a walk names
                // no relation either, so it is hoisted the same way an inline
                // select is.
                Expr::Path(path) if !path.partial && path.steps.len() > 1 => {
                    let synthetic = Stmt::Select(ast::SelectStmt {
                        result: operand.clone(),
                        filter: None,
                        order_by: vec![],
                        offset: None,
                        limit: None,
                        lock: None,
                    });
                    let Ok((cte_name, type_name)) = compiler.hoist_dml_as_cte(&synthetic) else {
                        return Ok(operand.clone());
                    };
                    let Ok(td) = compiler.resolve_type(&type_name) else {
                        return Ok(operand.clone());
                    };
                    compiler
                        .cte_types
                        .insert(cte_name.clone(), format!("{}::{}", td.module, td.name));
                    rewritten = true;
                    Ok(Expr::Path(ast::Path {
                        steps: vec![ast::PathStep::Name(cte_name)],
                        partial: false,
                    }))
                }
                other => Ok(other.clone()),
            }
        };
        let left = name_one(self, left)?;
        let right = name_one(self, right)?;
        if !rewritten {
            return Ok(None);
        }
        Ok(Some(Expr::Union(Box::new(left), Box::new(right))))
    }

    /// `A if cond else B` over object sets, as the union it is.
    ///
    /// Picking between two *sets* is not the scalar `CASE` an if/else over
    /// values compiles to: it stands for A's rows when the condition holds and
    /// B's when it does not, which is `(A filter cond) union (B filter not
    /// cond)`. Rewritten here rather than given its own IR, so it reaches the
    /// union machinery that already knows how to read one relation per branch.
    /// Hand a guarded mutation its condition: an insert folds it into its own
    /// `WHERE`, an update or a delete ANDs it onto the rows it narrows to.
    fn set_mutation_guard(&mut self, branch: &Expr, condition: Expr) {
        let stmt = match branch {
            Expr::SubQuery(stmt) => Some(stmt.as_ref()),
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(Expr::SubQuery(stmt)) => Some(stmt.as_ref()),
                _ => None,
            },
            _ => None,
        };
        match stmt {
            Some(Stmt::Update(_)) => self.pending_update_guard = Some(condition),
            Some(Stmt::Delete(_)) => self.pending_delete_guard = Some(condition),
            _ => self.pending_insert_guard = Some(condition),
        }
    }

    fn object_if_else_as_union(&mut self, expr: &Expr) -> Option<Expr> {
        let Expr::IfElse(ie) = expr else {
            return None;
        };
        fn is_empty_set(expr: &Expr) -> bool {
            matches!(expr, Expr::Set(items) if items.is_empty())
        }
        let yields_objects = |branch: &Expr| match branch {
            Expr::Path(p) if !p.partial && p.steps.len() == 1 => match &p.steps[0] {
                ast::PathStep::Name(n) => self.cte_object_type(n).is_some() || self.resolve_type(n).is_ok(),
                _ => false,
            },
            Expr::SubQuery(stmt) => {
                // A select over a walk (`select resource.revisions`) yields
                // objects too, and names no type for `dml_subject_type` to
                // report; what it lands on is what the branch carries.
                if let Some(ast::SelectStmt {
                    result: Expr::Path(path),
                    ..
                }) = innermost_select(stmt.as_ref())
                    && !path.partial
                    && path.steps.len() > 1
                    && let Some(ast::PathStep::Name(root)) = path.steps.first()
                    && let Ok(root_td) = self.resolve_path_root(root)
                {
                    return matches!(
                        self.walk_path_types(root_td, &path.steps[1..], MAX_COMPUTED_SPLICES),
                        (_, Some(_))
                    );
                }
                matches!(
                    self.dml_subject_type(stmt.as_ref()),
                    Ok(name) if self.resolve_type(&name).is_ok()
                )
            }
            // A branch may carry the shape the result is read with.
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(Expr::SubQuery(stmt)) => {
                    matches!(self.dml_subject_type(stmt.as_ref()), Ok(name) if self.resolve_type(&name).is_ok())
                }
                Some(Expr::Path(p)) if !p.partial && p.steps.len() == 1 => match &p.steps[0] {
                    ast::PathStep::Name(n) => self.cte_object_type(n).is_some() || self.resolve_type(n).is_ok(),
                    _ => false,
                },
                _ => false,
            },
            _ => false,
        };
        // `{}` contributes no rows, so the union degenerates to the other
        // branch under its own guard -- which is what Gel's own rewrite
        // (`SELECT A WHERE Cond UNION ALL SELECT B WHERE NOT Cond`) reduces
        // to when one side is empty.
        // A mutation under a condition is *not* handled here. Guarding the
        // branch only filters what is read back: the mutation is its own CTE
        // and Postgres runs it regardless, so `(insert …) if cond else {}`
        // would insert even when the condition is false -- silently, which is
        // far worse than the compile error it replaced. It needs the
        // condition folded into the mutation itself.
        fn mutating_stmt(branch: &Expr) -> Option<&Stmt> {
            match branch {
                Expr::SubQuery(stmt) => Some(stmt.as_ref()),
                Expr::Shape(sh) => match sh.expr.as_ref() {
                    Some(Expr::SubQuery(stmt)) => Some(stmt.as_ref()),
                    _ => None,
                },
                _ => None,
            }
            .filter(|stmt| matches!(stmt, Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_)))
        }
        // Guarding a branch only filters what is read back, while the
        // mutation is its own CTE that Postgres runs regardless -- so the
        // condition has to go into the mutation itself, which is what
        // `set_mutation_guard` arranges for all three.
        let (if_yields_objects, else_yields_objects) = (yields_objects(&ie.if_expr), yields_objects(&ie.else_expr));
        let guard = |branch: &Expr, condition: Expr| {
            Expr::SubQuery(Box::new(Stmt::Select(ast::SelectStmt {
                result: branch.clone(),
                filter: Some(condition),
                order_by: vec![],
                offset: None,
                limit: None,
                lock: None,
            })))
        };
        let negated = Expr::UnaryOp(Box::new(ast::UnaryOp {
            op: ast::UnaryOpKind::Not,
            operand: ie.condition.clone(),
        }));
        let guarded_insert = |branch: &Expr, other: &Expr| {
            mutating_stmt(branch).is_some() && matches!(other, Expr::Set(items) if items.is_empty())
        };
        if guarded_insert(&ie.if_expr, &ie.else_expr) {
            self.set_mutation_guard(&ie.if_expr, ie.condition.clone());
            return Some(ie.if_expr.clone());
        }
        if guarded_insert(&ie.else_expr, &ie.if_expr) {
            let negated = Expr::UnaryOp(Box::new(ast::UnaryOp {
                op: ast::UnaryOpKind::Not,
                operand: ie.condition.clone(),
            }));
            self.set_mutation_guard(&ie.else_expr, negated);
            return Some(ie.else_expr.clone());
        }
        // `(insert …) if not exists existing else (update existing set …)` —
        // the upsert idiom. Both branches mutate, so both carry their own
        // condition; each statement kind has its own pending slot, so two of
        // different kinds can be guarded at once. Two of the *same* kind would
        // have one guard overwrite the other, and fall through to the refusal
        // below rather than compile to a mutation that runs regardless.
        if let (Some(if_stmt), Some(else_stmt)) = (mutating_stmt(&ie.if_expr), mutating_stmt(&ie.else_expr))
            && std::mem::discriminant(if_stmt) != std::mem::discriminant(else_stmt)
        {
            self.set_mutation_guard(&ie.if_expr, ie.condition.clone());
            self.set_mutation_guard(&ie.else_expr, negated);
            return Some(Expr::Union(
                Box::new(ie.if_expr.clone()),
                Box::new(ie.else_expr.clone()),
            ));
        }
        // `existing if exists existing else (insert …)` — the insert still has
        // to carry the condition itself, but the other branch is a set of its
        // own, so the result is Gel's full rewrite: both branches under
        // opposite guards, unioned.
        let reads_objects = |branch: &Expr, yields: bool| mutating_stmt(branch).is_none() && yields;
        if mutating_stmt(&ie.if_expr).is_some() && reads_objects(&ie.else_expr, else_yields_objects) {
            self.set_mutation_guard(&ie.if_expr, ie.condition.clone());
            return Some(Expr::Union(
                Box::new(ie.if_expr.clone()),
                Box::new(guard(&ie.else_expr, negated)),
            ));
        }
        if mutating_stmt(&ie.else_expr).is_some() && reads_objects(&ie.if_expr, if_yields_objects) {
            self.set_mutation_guard(&ie.else_expr, negated);
            return Some(Expr::Union(
                Box::new(guard(&ie.if_expr, ie.condition.clone())),
                Box::new(ie.else_expr.clone()),
            ));
        }
        if mutating_stmt(&ie.if_expr).is_some() || mutating_stmt(&ie.else_expr).is_some() {
            return None;
        }
        let (if_empty, else_empty) = (is_empty_set(&ie.if_expr), is_empty_set(&ie.else_expr));
        if if_empty && else_empty {
            return None;
        }
        if !(if_empty || if_yields_objects) || !(else_empty || else_yields_objects) {
            return None;
        }
        if else_empty {
            return Some(guard(&ie.if_expr, ie.condition.clone()));
        }
        if if_empty {
            return Some(guard(&ie.else_expr, negated));
        }
        Some(Expr::Union(
            Box::new(guard(&ie.if_expr, ie.condition.clone())),
            Box::new(guard(&ie.else_expr, negated)),
        ))
    }

    /// `granted ?? existing` over object sets is the choice `A if exists A
    /// else B` spells, so it reaches the same union machinery. A scalar
    /// coalesce rewritten this way is simply not an object union, and the
    /// caller falls back to compiling what was written.
    fn object_coalesce_as_if_else(expr: &Expr) -> Option<Expr> {
        fn as_if_else(b: &ast::BinOp) -> Option<Expr> {
            (b.op == ast::BinOpKind::Coalesce).then(|| {
                Expr::IfElse(Box::new(ast::IfElse {
                    condition: Expr::UnaryOp(Box::new(ast::UnaryOp {
                        op: ast::UnaryOpKind::Exists,
                        operand: b.left.clone(),
                    })),
                    if_expr: b.left.clone(),
                    else_expr: b.right.clone(),
                }))
            })
        }
        match expr {
            Expr::BinOp(b) => as_if_else(b),
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(Expr::BinOp(b)) => Some(Expr::Shape(Box::new(ast::ShapeExpr {
                    expr: Some(as_if_else(b)?),
                    elements: sh.elements.clone(),
                    marker_offset: sh.marker_offset,
                }))),
                _ => None,
            },
            _ => None,
        }
    }

    fn try_compile_object_union_select(
        &mut self,
        sel: &ast::SelectStmt,
        result_expr: &Expr,
        distinct: bool,
    ) -> Result<Option<IrSelect>, PyQLError> {
        let coalesced;
        let result_expr = match Self::object_coalesce_as_if_else(result_expr) {
            Some(rewritten) => {
                coalesced = rewritten;
                &coalesced
            }
            None => result_expr,
        };
        let as_union;
        let (union_expr, shape_elements): (&Expr, &[ShapeElement]) = match result_expr {
            Expr::Union(_, _) => (result_expr, &[]),
            Expr::IfElse(_) => match self.object_if_else_as_union(result_expr) {
                // One branch empty leaves a single guarded set, not a union;
                // that is an ordinary select over what the branch names.
                Some(rewritten @ Expr::SubQuery(_)) => {
                    return self.compile_select(sel, &rewritten, distinct).map(Some);
                }
                Some(rewritten) if !matches!(rewritten, Expr::Union(_, _)) => {
                    return self.compile_select(sel, &rewritten, distinct).map(Some);
                }
                Some(rewritten) => {
                    as_union = rewritten;
                    (&as_union, &[] as &[ShapeElement])
                }
                None => return Ok(None),
            },
            Expr::Shape(shape) => match &shape.expr {
                Some(inner @ Expr::Union(_, _)) => (inner, shape.elements.as_slice()),
                Some(inner @ Expr::IfElse(_)) => match self.object_if_else_as_union(inner) {
                    Some(Expr::SubQuery(stmt)) => {
                        let shaped = Expr::Shape(Box::new(ast::ShapeExpr {
                            expr: Some(Expr::SubQuery(stmt)),
                            elements: shape.elements.clone(),
                            marker_offset: None,
                        }));
                        return self.compile_select(sel, &shaped, distinct).map(Some);
                    }
                    Some(rewritten) if !matches!(rewritten, Expr::Union(_, _)) => {
                        let shaped = match rewritten {
                            Expr::Shape(_) => rewritten,
                            other => Expr::Shape(Box::new(ast::ShapeExpr {
                                expr: Some(other),
                                elements: shape.elements.clone(),
                                marker_offset: None,
                            })),
                        };
                        return self.compile_select(sel, &shaped, distinct).map(Some);
                    }
                    Some(rewritten) => {
                        as_union = rewritten;
                        (&as_union, shape.elements.as_slice())
                    }
                    None => return Ok(None),
                },
                _ => return Ok(None),
            },
            _ => return Ok(None),
        };

        let named;
        let union_expr = match self.name_union_operands(union_expr)? {
            Some(rewritten) => {
                named = rewritten;
                &named
            }
            None => union_expr,
        };
        let Some(branches) = self.object_union_branches(union_expr) else {
            return Ok(None);
        };

        let Some(first_type) = self.common_union_type(&branches) else {
            let (first_type, _) = &branches[0];
            let (other, _) = branches
                .iter()
                .find(|(t, _)| t != first_type)
                .expect("no common type means at least two differ");
            return Err(self.type_err(&format!(
                "operator 'UNION' cannot be applied to operands of type '{first_type}' and '{other}'"
            )));
        };
        let first_type = &first_type;
        if sel.lock.is_some() {
            return Err(self.type_err(
                "FOR UPDATE/SHARE cannot be used on a UNION — its rows come from more than one \
                 source, which a single locking clause can't target",
            ));
        }
        let td = self.resolve_type(first_type)?;
        let alias = self.fresh_alias();

        self.anchors.push(SelectAnchor {
            type_name: td.name.clone(),
            qualified: format!("{}::{}", td.module, td.name),
            alias: alias.clone(),
            detached: std::mem::take(&mut self.pending_detached),
            declared_on: None,
        });
        let clauses = (|compiler: &mut Self| -> Result<_, PyQLError> {
            let shape = compiler.compile_shape(shape_elements, td, &alias, &td.module)?;
            let filter = sel
                .filter
                .as_ref()
                .map(|f| compiler.compile_expr(f, td, &alias))
                .transpose()?;
            let order_by = sel
                .order_by
                .iter()
                .map(|o| compiler.compile_sort(o, td, &alias))
                .collect::<Result<Vec<_>, _>>()?;
            let offset = sel
                .offset
                .as_ref()
                .map(|e| compiler.compile_expr(e, td, &alias))
                .transpose()?;
            let limit = sel
                .limit
                .as_ref()
                .map(|e| compiler.compile_expr(e, td, &alias))
                .transpose()?;
            Ok((shape, filter, order_by, offset, limit))
        })(self);
        self.anchors.pop();
        let (shape, mut filter, order_by, offset, limit) = clauses?;
        // A select whose subject is a for-loop variable reads the one row that
        // variable holds, not the whole table.
        if let Some(var) = Self::subject_name(result_expr).filter(|n| self.for_var_types.contains_key(n)) {
            let narrowed = IrExpr::BinOp(Box::new(IrBinOp {
                left: IrExpr::ColumnRef {
                    alias: alias.clone(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
                op: ast::BinOpKind::Eq,
                right: self.for_var_ref(&var),
            }));
            filter = and_conditions(filter, vec![narrowed]);
        }

        // `brands union offerings` — types that only share an ancestor carry
        // different columns, so each branch is read as that ancestor: its
        // columns, and the concrete type each row has. An abstract branch's
        // rows already say which type they are.
        let heterogeneous = branches.iter().any(|(t, _)| t != first_type);
        let common_columns = if heterogeneous {
            self.collect_poly_info(first_type).1
        } else {
            vec![]
        };
        let rows = branches
            .into_iter()
            .map(|(type_name, table)| IrRowSource::Bound {
                source: IrSource {
                    poly: if heterogeneous {
                        self.poly_fanout_for(&type_name)
                    } else {
                        None
                    },
                    type_name,
                    table,
                    alias: alias.clone(),
                },
                shape: shape.clone(),
            })
            .collect();

        Ok(Some(IrSelect {
            rows,
            filter,
            order_by,
            offset,
            limit,
            distinct,
            dml_source: None,
            polymorphic: false,
            poly_implementors: vec![],
            poly_columns: common_columns,
            lock: None,
        }))
    }

    /// The bare name a select's result is written as, whether it carries a
    /// shape or not.
    fn subject_name(result_expr: &Expr) -> Option<String> {
        let path = match result_expr {
            Expr::Path(p) => p,
            Expr::Shape(sh) => match sh.expr.as_ref()? {
                Expr::Path(p) => p,
                _ => return None,
            },
            _ => return None,
        };
        if path.partial {
            return None;
        }
        match path.steps.as_slice() {
            [ast::PathStep::Name(n)] => Some(n.clone()),
            _ => None,
        }
    }

    fn compile_select(
        &mut self,
        sel: &ast::SelectStmt,
        result_expr: &Expr,
        distinct: bool,
    ) -> Result<IrSelect, PyQLError> {
        if let Some(union_select) = self.try_compile_object_union_select(sel, result_expr, distinct)? {
            return Ok(union_select);
        }
        let (type_name, shape_elements, inner_stmt, cte_name) = self.extract_type_and_shape(result_expr)?;
        let td = self.resolve_type(&type_name)?;
        let alias = self.fresh_alias();
        let table = match cte_name {
            Some(ref cte) => format!("@cte:{}", cte),
            None => Self::subject_name(result_expr)
                .map(|name| self.row_source_table(&name, td))
                .unwrap_or_else(|| td.table.clone()),
        };
        let source = IrSource {
            poly: self.poly_fanout_for(&format!("{}::{}", td.module, td.name)),
            type_name: format!("{}::{}", td.module, td.name),
            table,
            alias: alias.clone(),
        };

        // On the stack for as long as this select's own clauses are being
        // compiled, so a `detached` select nested in one of them can find the
        // row it is being compared against. See `enclosing_anchor`.
        self.anchors.push(SelectAnchor {
            type_name: td.name.clone(),
            qualified: format!("{}::{}", td.module, td.name),
            alias: alias.clone(),
            detached: std::mem::take(&mut self.pending_detached),
            declared_on: None,
        });
        // A binding read back by name brings whatever its own shape declared
        // (`offering { publisher }`), which is on no type and has to be found
        // through the binding it was written on.
        let declared = match cte_name.as_deref() {
            Some(name) => self.cte_declared_pointers.get(name).cloned().unwrap_or_default(),
            // `select (select T { x := … }) filter .x…` — a nested select's
            // shape declares pointers on no type, just as a binding's does, and
            // the outer select's clauses read them the same way.
            None => inner_stmt
                .and_then(innermost_select)
                .and_then(|inner| match &inner.result {
                    Expr::Shape(sh) => Some(sh.elements.clone()),
                    _ => None,
                })
                .unwrap_or_default(),
        };
        // `*` on a binding takes in what the binding's shape computed, too.
        let splat_over_declared: Vec<ShapeElement>;
        let shape_elements = if shape_elements
            .iter()
            .any(|el| el.splat.is_some() && !matches!(el.path.steps.first(), Some(ast::PathStep::TypeIntersection(_))))
        {
            let named = |name: &str| {
                shape_elements
                    .iter()
                    .any(|el| el.splat.is_none() && path_leaf(&el.path).is_ok_and(|n| n == name))
            };
            let extra: Vec<ShapeElement> = declared
                .iter()
                .filter(|d| d.compexpr.is_some())
                .filter_map(|d| {
                    let name = path_leaf(&d.path).ok()?;
                    (!named(name)).then(|| ShapeElement {
                        path: ast::Path::relative(name),
                        splat: None,
                        nested: None,
                        compexpr: None,
                        op: ast::ShapeOp::Assign,
                        filter: None,
                        order_by: vec![],
                        offset: None,
                        limit: None,
                        marker_offset: None,
                    })
                })
                .collect();
            splat_over_declared = shape_elements.iter().cloned().chain(extra).collect();
            &splat_over_declared[..]
        } else {
            shape_elements
        };
        let outer_declared = std::mem::replace(&mut self.active_declared_pointers, declared);
        let clauses = (|compiler: &mut Self| -> Result<_, PyQLError> {
            let shape = compiler.compile_shape(shape_elements, td, &alias, &td.module)?;
            // This select's own shape declares pointers the same way, and its
            // clauses read them the same way: `select T { x := … } order by .x`
            // is valid EdgeQL, while one shape pointer reading another is not —
            // verified against Gel, which accepts the first and rejects the
            // second. Added only now, after the shape is compiled, so the scope
            // stops where Gel's does.
            compiler
                .active_declared_pointers
                .extend(shape_elements.iter().filter(|el| el.compexpr.is_some()).cloned());
            let filter = sel
                .filter
                .as_ref()
                .map(|f| compiler.compile_expr(f, td, &alias))
                .transpose()?;
            let order_by = sel
                .order_by
                .iter()
                .map(|s| compiler.compile_sort(s, td, &alias))
                .collect::<Result<Vec<_>, _>>()?;
            let offset = sel
                .offset
                .as_ref()
                .map(|e| compiler.compile_expr(e, td, &alias))
                .transpose()?;
            let limit = sel
                .limit
                .as_ref()
                .map(|e| compiler.compile_expr(e, td, &alias))
                .transpose()?;
            Ok((shape, filter, order_by, offset, limit))
        })(self);
        self.anchors.pop();
        self.active_declared_pointers = outer_declared;
        let (shape, mut filter, order_by, offset, limit) = clauses?;

        // A select whose subject is a for-loop variable reads the one row that
        // variable holds; unfiltered it would read the whole table.
        if let Some(var) = Self::subject_name(result_expr).filter(|n| self.for_var_types.contains_key(n)) {
            let narrowed = IrExpr::BinOp(Box::new(IrBinOp {
                left: IrExpr::ColumnRef {
                    alias: alias.clone(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
                op: ast::BinOpKind::Eq,
                right: self.for_var_ref(&var),
            }));
            filter = and_conditions(filter, vec![narrowed]);
        }

        // Compile the inner DML if this is a SELECT-over-DML / SELECT-over-SELECT.
        let dml_source = inner_stmt.map(|s| self.compile_stmt(s).map(Box::new)).transpose()?;
        let mut shape = shape;
        if let Some(dml) = &dml_source {
            // `SELECT (INSERT …)` has no user-written CTE name: the emitter
            // wraps the DML in one of its own (`sql::DML_CTE`), and the
            // junction CTEs are named after it.
            let dml_cte = cte_name.as_deref().unwrap_or(crate::sql::DML_CTE);
            Self::read_nested_links_from_their_ctes(dml, Some(dml_cte), &mut shape);
        }

        let polymorphic = self.is_polymorphic(td);
        let (poly_implementors, poly_columns) = if polymorphic {
            let iface_qname = format!("{}::{}", td.module, td.name);
            (self.find_poly_implementors(&iface_qname), Self::poly_dml_columns(td))
        } else {
            (vec![], vec![])
        };

        // `FOR UPDATE`/`FOR SHARE`/... — only valid when every output row
        // maps 1:1 to a single physical table row, the same restriction
        // Postgres itself enforces (it rejects the same combinations with
        // its own "FOR UPDATE is not allowed with ..." errors). `DISTINCT`
        // and an interface (polymorphic) target both break that mapping;
        // `SELECT (INSERT/UPDATE/DELETE …) { ... }` has nothing left to
        // lock, since the DML already ran by the time this SELECT reads it.
        let lock = match &sel.lock {
            None => None,
            Some(lc) => {
                if distinct {
                    return Err(self.type_err(
                        "FOR UPDATE/SHARE cannot be combined with DISTINCT — Postgres can't \
                         guarantee the result rows map 1:1 to physical table rows",
                    ));
                }
                if polymorphic {
                    return Err(self.type_err(
                        "FOR UPDATE/SHARE cannot be used on an interface type — its rows span \
                         multiple underlying tables, which a single locking clause can't target",
                    ));
                }
                if dml_source.is_some() {
                    return Err(self.type_err(
                        "FOR UPDATE/SHARE cannot be used on SELECT (INSERT/UPDATE/DELETE …) — \
                         there's nothing left to lock once the DML has already run",
                    ));
                }
                Some(IrLockClause {
                    strength: match lc.strength {
                        ast::LockStrength::Update => IrLockStrength::Update,
                        ast::LockStrength::NoKeyUpdate => IrLockStrength::NoKeyUpdate,
                        ast::LockStrength::Share => IrLockStrength::Share,
                        ast::LockStrength::KeyShare => IrLockStrength::KeyShare,
                    },
                    wait: match lc.wait {
                        ast::LockWait::Block => IrLockWait::Block,
                        ast::LockWait::NoWait => IrLockWait::NoWait,
                        ast::LockWait::SkipLocked => IrLockWait::SkipLocked,
                    },
                })
            }
        };

        Ok(IrSelect {
            rows: vec![IrRowSource::Bound { source, shape }],
            filter,
            order_by,
            offset,
            limit,
            distinct,
            dml_source,
            polymorphic,
            poly_implementors,
            poly_columns,
            lock,
        })
    }

    /// Unwrap `Shape(expr, elements)` or bare `Path` from a SELECT result.
    /// Returns (type_name, shape_elements, optional_inner_stmt, optional_cte_name).
    /// The inner stmt is Some when the subject is `(INSERT …)` / `(SELECT …)` etc.
    /// The cte_name is Some when the subject is a WITH-block CTE reference.
    fn extract_type_and_shape<'e>(&self, expr: &'e Expr) -> Result<TypeAndShape<'e>, PyQLError> {
        match expr {
            Expr::Shape(s) => {
                // s.expr is Option<Expr> (not Box), so use as_ref() not as_deref()
                let (type_name, cte_name, inner) = match s.expr.as_ref() {
                    Some(Expr::SubQuery(stmt)) => (self.dml_subject_type(stmt)?, None, Some(stmt.as_ref())),
                    Some(Expr::Path(p)) if !p.partial && p.steps.len() == 1 => {
                        if let ast::PathStep::Name(n) = &p.steps[0] {
                            if let Some(t) = self.for_var_types.get(n.as_str()) {
                                (t.clone(), None, None)
                            } else if let Some(t) = self.cte_types.get(n.as_str()) {
                                if t.contains("::") {
                                    (t.clone(), Some(n.clone()), None)
                                } else {
                                    (self.expr_as_type_name(s.expr.as_ref().unwrap())?, None, None)
                                }
                            } else {
                                (self.expr_as_type_name(s.expr.as_ref().unwrap())?, None, None)
                            }
                        } else {
                            (self.expr_as_type_name(s.expr.as_ref().unwrap())?, None, None)
                        }
                    }
                    Some(inner) => (self.expr_as_type_name(inner)?, None, None),
                    None => {
                        return Err(PyQLError::Type(PyQLTypeError {
                            message: "shape without subject expression".into(),
                            position: Position { line: 0, col: 0 },
                        }));
                    }
                };
                Ok((type_name, &s.elements, inner, cte_name))
            }
            // Bare `SELECT (DML)` without an outer shape
            Expr::SubQuery(stmt) => Ok((self.dml_subject_type(stmt)?, &[], Some(stmt.as_ref()), None)),
            // Bare CTE object reference: `select cte_name`
            Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
                if let ast::PathStep::Name(n) = &p.steps[0] {
                    if let Some(t) = self.for_var_types.get(n.as_str()) {
                        return Ok((t.clone(), &[], None, None));
                    }
                    if let Some(t) = self.cte_types.get(n.as_str())
                        && t.contains("::")
                    {
                        return Ok((t.clone(), &[], None, Some(n.clone())));
                    }
                }
                Ok((self.expr_as_type_name(expr)?, &[], None, None))
            }
            _ => Ok((self.expr_as_type_name(expr)?, &[], None, None)),
        }
    }

    /// True when `expr` is known to hold json, so `expr[…]` reaches into it
    /// with `->` rather than indexing a string or an array. A loop variable
    /// carries no type in the IR, so its `for` registration answers for it.
    fn is_json_expr(&self, ast: &Expr, ir: &IrExpr) -> bool {
        if matches!(infer_ir_type(ir), Some("jsonb")) {
            return true;
        }
        let Expr::Path(path) = ast else {
            return false;
        };
        if path.partial || path.steps.len() != 1 {
            return false;
        }
        let ast::PathStep::Name(name) = &path.steps[0] else {
            return false;
        };
        self.for_vars.get(name.as_str()).is_some_and(|t| t == "jsonb")
    }

    /// The pg type one row of a set-returning call yields — the element type
    /// of the array it unpacks. `None` when the call is not set-returning or
    /// its argument's type is not an array.
    fn set_returning_element_type(&mut self, expr: &Expr) -> Result<Option<String>, PyQLError> {
        if !expr_returns_set(expr) {
            return Ok(None);
        }
        let Expr::FunctionCall(call) = expr else {
            return Ok(None);
        };
        let [argument] = call.args.as_slice() else {
            return Ok(None);
        };
        let compiled = self.compile_free_expr(argument)?;
        let Some(array_type) = infer_ir_type(&compiled) else {
            return Ok(None);
        };
        Ok(array_type
            .strip_suffix("[]")
            .map(|element| literal_sentinel_to_pg(element).to_string()))
    }

    fn compile_for(&mut self, f: &ast::ForStmt) -> Result<IrFor, PyQLError> {
        // A loop straight over a binding: the rows are that binding's, so a
        // walk off the variable reads it rather than the type's own table.
        let iterated_binding = self.resolve_cte_name(&f.iterator).map(|name| self.cte_sql_name(name));
        // Compile the iterator to determine what one loop variable binds to.
        let (iterator, pg_type, yielded_object_type) = match &f.iterator {
            Expr::Set(elems) => {
                let compiled: Result<Vec<_>, _> = elems.iter().map(|e| self.compile_free_expr(e)).collect();
                let exprs = compiled?;
                let raw = exprs.first().and_then(|e| infer_ir_type(e)).unwrap_or("text");
                let pg_type = literal_sentinel_to_pg(raw).to_string();
                (
                    IrForIterator::Values {
                        exprs,
                        pg_type: pg_type.clone(),
                    },
                    pg_type,
                    None,
                )
            }
            // A derived set — every row of it, not the single value a scalar
            // subquery in a one-row `VALUES` would collapse it to.
            Expr::SubQuery(stmt) => {
                let inner = self.compile_stmt(stmt)?;
                if !matches!(inner, IrStmt::Select(_) | IrStmt::PathSelect(_)) {
                    return Err(self.type_err(
                        "for-loop iterator: only a select can be iterated over — \
                         bind the statement in a `with` first",
                    ));
                }
                let yielded = cte_stmt_type(&inner);
                let scalar = !yielded.contains("::");
                let pg_type = if scalar {
                    let raw = if yielded.is_empty() { "text" } else { yielded.as_str() };
                    literal_sentinel_to_pg(raw).to_string()
                } else {
                    "uuid".to_string()
                };
                (
                    IrForIterator::Query {
                        stmt: Box::new(inner),
                        scalar,
                    },
                    pg_type,
                    (!scalar).then_some(yielded),
                )
            }
            // A WITH binding names a set, so the loop runs once per row of
            // it — not once over the single value a scalar subquery would
            // collapse it to.
            Expr::Path(p)
                if !p.partial
                    && p.steps.len() == 1
                    && matches!(&p.steps[0], ast::PathStep::Name(n) if self.cte_types.contains_key(n.as_str())) =>
            {
                let ast::PathStep::Name(name) = &p.steps[0] else {
                    unreachable!("checked by the guard")
                };
                let yielded = self.cte_types.get(name.as_str()).cloned().unwrap_or_default();
                let scalar = !yielded.contains("::");
                let pg_type = if scalar {
                    let raw = if yielded.is_empty() { "text" } else { yielded.as_str() };
                    literal_sentinel_to_pg(raw).to_string()
                } else {
                    "uuid".to_string()
                };
                let source = IrSource {
                    poly: None,
                    type_name: yielded.clone(),
                    table: format!("@cte:{}", self.cte_sql_name(name)),
                    alias: self.fresh_alias(),
                };
                (
                    IrForIterator::Query {
                        stmt: Box::new(IrStmt::Select(IrSelect::schema_bound(source, vec![], None))),
                        scalar,
                    },
                    pg_type,
                    (!scalar).then_some(yielded),
                )
            }
            // `for o in invitations.organizations union (…)` — a walk off a
            // binding names a set to iterate just as a sub-select does; it is
            // only written without the parentheses.
            Expr::Path(p) if !p.partial && p.steps.len() > 1 => {
                let synthetic = ast::SelectStmt {
                    result: Expr::Path(p.clone()),
                    filter: None,
                    order_by: vec![],
                    offset: None,
                    limit: None,
                    lock: None,
                };
                let inner = self.compile_stmt(&Stmt::Select(synthetic))?;
                let yielded = cte_stmt_type(&inner);
                let scalar = !yielded.contains("::");
                let pg_type = if scalar {
                    let raw = if yielded.is_empty() { "text" } else { yielded.as_str() };
                    literal_sentinel_to_pg(raw).to_string()
                } else {
                    "uuid".to_string()
                };
                (
                    IrForIterator::Query {
                        stmt: Box::new(inner),
                        scalar,
                    },
                    pg_type,
                    (!scalar).then_some(yielded),
                )
            }
            other => {
                let e = self.compile_free_expr(other)?;
                // A set-returning call is registered as `set of any`, so its
                // own type says nothing — the rows are the argument array's
                // elements, which is where the type comes from.
                let raw = match self.set_returning_element_type(other)? {
                    Some(element) => element,
                    None => literal_sentinel_to_pg(infer_ir_type(&e).unwrap_or("text")).to_string(),
                };
                let pg_type = raw;
                let iterator = if expr_returns_set(other) {
                    IrForIterator::SetReturning {
                        expr: e,
                        pg_type: pg_type.clone(),
                    }
                } else {
                    IrForIterator::Values {
                        exprs: vec![e],
                        pg_type: pg_type.clone(),
                    }
                };
                (iterator, pg_type, None)
            }
        };

        // The CTE name this loop's iterator is emitted under, claimed from the
        // statement's one namespace so no sibling loop and no binding can end
        // up under it too. The emitter spells it `_for_<slot>`.
        let slot = self
            .claim_generated_cte_name(&format!("_for_{}", f.var))
            .strip_prefix("_for_")
            .unwrap_or(&f.var)
            .to_string();
        let prev_slot = self.for_var_slots.insert(f.var.clone(), slot.clone());
        // Register the for variable so the body can reference it.
        let prev = self.for_vars.insert(f.var.clone(), pg_type.clone());
        let prev_cte = match iterated_binding {
            Some(name) => self.for_var_ctes.insert(f.var.clone(), name),
            None => self.for_var_ctes.remove(&f.var),
        };
        let prev_type = match yielded_object_type {
            Some(qualified) => self.for_var_types.insert(f.var.clone(), qualified),
            None => self.for_var_types.remove(&f.var),
        };
        let hoisted_before = self.hoisted_ctes.len();
        self.for_scope.push(slot.clone());
        let body = self.compile_stmt(&f.body);
        self.for_scope.pop();
        let body = body?;
        let body_ctes: Vec<IrCteDef> = self.hoisted_ctes.split_off(hoisted_before);
        // Restore previous for-var (or remove if none existed).
        match prev {
            Some(old) => {
                self.for_vars.insert(f.var.clone(), old);
            }
            None => {
                self.for_vars.remove(&f.var);
            }
        }
        match prev_type {
            Some(old) => {
                self.for_var_types.insert(f.var.clone(), old);
            }
            None => {
                self.for_var_types.remove(&f.var);
            }
        }
        match prev_cte {
            Some(old) => {
                self.for_var_ctes.insert(f.var.clone(), old);
            }
            None => {
                self.for_var_ctes.remove(&f.var);
            }
        }
        match prev_slot {
            Some(old) => {
                self.for_var_slots.insert(f.var.clone(), old);
            }
            None => {
                self.for_var_slots.remove(&f.var);
            }
        }

        // Checked here rather than left to the SQL emitter: `emit_for_stmt`
        // only implements these three body kinds, and reaching it with any
        // other one used to abort the process instead of reporting a PyQL
        // error the caller could act on.
        let body_kind = match &body {
            IrStmt::Insert(_) | IrStmt::Select(_) | IrStmt::PathSelect(_) => None,
            // An update is driven from the iteration itself (`UPDATE … FROM
            // <iterated set>`) rather than from a LATERAL, which cannot hold
            // DML. A multi-link mutation inside one would need its junction
            // rows driven from the iteration too, which it is not yet.
            // An append whose value is the loop variable itself can be driven
            // from the iteration (`emit_for_ml_append_cte`); anything more
            // would need its junction rows correlated in a way they are not.
            IrStmt::Update(upd)
                if upd.assignments.is_empty()
                    && upd.rewrites.is_empty()
                    && !upd.multi_link_appends.is_empty()
                    && upd
                        .multi_link_appends
                        .iter()
                        .all(|a| crate::sql::append_value_is_the_loop_variable(&a.values, &f.var))
                    && upd.multi_link_clears.is_empty()
                    && upd.multi_link_replaces.is_empty()
                    && upd.multi_link_removals.is_empty()
                    && upd.poly_implementors.is_empty() =>
            {
                None
            }
            IrStmt::Update(upd)
                if upd.multi_link_appends.is_empty()
                    && upd.multi_link_clears.is_empty()
                    && upd.multi_link_replaces.is_empty()
                    && upd.multi_link_removals.is_empty()
                    && upd.poly_implementors.is_empty() =>
            {
                None
            }
            IrStmt::Update(_) if std::env::var("PYLON_DBG_FORUPD").is_ok() => None,
            // `update x set { ml += (insert T { … }) }` — the insert runs once
            // per iteration, driven from the same rows the update is, and the
            // junction pairs each with the id that iteration generated. Only
            // appends: a clear/remove/replace has no such pairing.
            IrStmt::Update(upd)
                if upd.assignments.is_empty()
                    && upd.rewrites.is_empty()
                    && !upd.multi_link_appends.is_empty()
                    && upd.multi_link_clears.is_empty()
                    && upd.multi_link_replaces.is_empty()
                    && upd.multi_link_removals.is_empty()
                    && upd.poly_implementors.is_empty()
                    && upd
                        .multi_link_appends
                        .iter()
                        .all(|a| crate::sql::per_iteration_insert(a, &upd.nested_ctes).is_some()) =>
            {
                None
            }
            IrStmt::Update(_) => Some("update"),
            IrStmt::Delete(_) => Some("delete"),
            // `for line in … union (for component in … union (insert …))` —
            // one iterator CTE per loop, joined on the key the inner carries.
            // Only an insert innermost: anything else would need its own rows
            // driven from the pair, which they are not.
            IrStmt::For(inner) if matches!(inner.body.as_ref(), IrStmt::Insert(_)) => None,
            IrStmt::For(_) => Some("nested for"),
            IrStmt::Group(_) => Some("group"),
            _ => Some("this statement"),
        };
        if let Some(kind) = body_kind {
            return Err(self.type_err(&format!(
                "for-loop body: {kind} is not supported as a `for` body — use insert or select"
            )));
        }

        Ok(IrFor {
            var_name: slot,
            iterator,
            body: Box::new(body),
            body_ctes,
        })
    }

    fn compile_group(&mut self, g: &ast::GroupStmt) -> Result<IrGroup, PyQLError> {
        // Resolve the subject type — may be a schema type, a CTE alias, or a
        // walk. A walk (`group a.names by …`) names rows rather than a type:
        // the group runs over what it lands on, narrowed below to the rows it
        // yields, the same way `update a.preferences` narrows its own target.
        // The steps used to be joined with `::` and looked up as a type name,
        // which reported `a.names` as an unknown type `a::names`.
        let mut walked: Option<&ast::Path> = None;
        let (type_name, cte_name) = match &g.subject {
            Expr::Path(p) if !p.partial => match p.steps.as_slice() {
                [ast::PathStep::Name(n)] => {
                    if let Some(t) = self.cte_types.get(n.as_str()) {
                        (t.clone(), Some(n.clone()))
                    } else {
                        (n.clone(), None)
                    }
                }
                [ast::PathStep::Name(root), rest @ ..]
                    if !rest.is_empty()
                        && let Ok(root_td) = self.resolve_path_root(root)
                        && let (_, Some(target)) = self.walk_path_types(root_td, rest, MAX_COMPUTED_SPLICES) =>
                {
                    walked = Some(p);
                    (format!("{}::{}", target.module, target.name), None)
                }
                _ => {
                    return Err(PyQLError::Type(PyQLTypeError {
                        message: format!("unsupported group subject: {:?}", g.subject),
                        position: Position { line: 0, col: 0 },
                    }));
                }
            },
            _ => {
                return Err(PyQLError::Type(PyQLTypeError {
                    message: "group subject must be a type name".to_string(),
                    position: Position { line: 0, col: 0 },
                }));
            }
        };

        let td = self.resolve_type(&type_name)?;
        let alias = self.fresh_alias();
        let fq_type_name = format!("{}::{}", td.module, td.name);
        let table = match cte_name {
            Some(ref cte) => format!("@cte:{}", cte),
            None => td.table.clone(),
        };
        let source = IrSource {
            poly: self.poly_fanout_for(&fq_type_name),
            type_name: fq_type_name.clone(),
            table,
            alias: alias.clone(),
        };
        let module = td.module.clone();

        // Compile the element shape. No explicit shape → implicit { id }.
        let shape = self.compile_shape(g.shape.as_deref().unwrap_or(&[]), td, &alias, &module)?;

        // Build a map from using-alias → compiled expression.
        let td = self.resolve_type(&type_name)?;
        let mut using_map: HashMap<String, IrExpr> = HashMap::new();
        for (alias_name, expr) in &g.using {
            let ir = self.compile_expr(expr, td, &alias)?;
            using_map.insert(alias_name.clone(), ir);
        }

        // Compile BY keys: each is either an Ident (using-alias ref) or a partial Path (.prop).
        let mut keys: Vec<(String, IrExpr)> = vec![];
        let td = self.resolve_type(&type_name)?;
        for by_expr in &g.by {
            match by_expr {
                Expr::Path(p) if p.partial && p.steps.len() == 1 => {
                    if let ast::PathStep::Name(prop) = &p.steps[0] {
                        // `.prop` shorthand: infer alias = prop name, expr = column ref.
                        let ir = self.compile_expr(by_expr, td, &alias)?;
                        keys.push((prop.clone(), ir));
                    } else {
                        return Err(PyQLError::Type(PyQLTypeError {
                            message: "group by path must be a simple property".to_string(),
                            position: Position { line: 0, col: 0 },
                        }));
                    }
                }
                Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
                    if let ast::PathStep::Name(name) = &p.steps[0] {
                        // Bare ident: must be a using alias.
                        let ir = using_map.get(name).ok_or_else(|| {
                            PyQLError::Type(PyQLTypeError {
                                message: format!("group by references unknown alias '{}'", name),
                                position: Position { line: 0, col: 0 },
                            })
                        })?;
                        keys.push((name.clone(), ir.clone()));
                    } else {
                        return Err(PyQLError::Type(PyQLTypeError {
                            message: "group by identifier must be a simple name".to_string(),
                            position: Position { line: 0, col: 0 },
                        }));
                    }
                }
                _ => {
                    return Err(PyQLError::Type(PyQLTypeError {
                        message: format!("unsupported group by expression: {:?}", by_expr),
                        position: Position { line: 0, col: 0 },
                    }));
                }
            }
        }

        // `filter` restricts the grouped rows; `order by`/`offset`/`limit`
        // apply within each group, so they're compiled against the same
        // element scope the shape is.
        let td = self.resolve_type(&type_name)?;
        let synthetic = ast::SelectStmt {
            result: g.subject.clone(),
            filter: g.filter.clone(),
            order_by: g.order_by.clone(),
            offset: g.offset.clone(),
            limit: g.limit.clone(),
            lock: None,
        };
        let (filter, order_by, offset, limit) = self.compile_path_modifiers(&synthetic, td, &alias)?;
        // A walked subject groups only the rows the walk reaches, not every
        // row of the type it happens to land on.
        let filter = match walked {
            Some(subject) => {
                let subject = subject.clone();
                let rows = self.compile_subject_path_rows(&subject, &alias)?;
                and_conditions(filter, vec![rows])
            }
            None => filter,
        };

        Ok(IrGroup {
            source,
            shape,
            keys,
            filter,
            order_by,
            offset,
            limit,
            output: IrGroupOutput::Groups,
        })
    }

    fn bind_group(&mut self, name: &str, expr: &Expr) -> Result<bool, PyQLError> {
        let Expr::SubQuery(stmt) = expr else {
            return Ok(false);
        };
        let Stmt::Group(g) = stmt.as_ref() else {
            return Ok(false);
        };
        let grp = self.compile_group(g)?;
        self.group_bindings.insert(name.to_string(), grp);
        Ok(true)
    }

    /// `select (group S using k := E by k) { n := count(.elements) }`. Each
    /// pointer is compiled over the grouped rows of `S`: `.key.k` stands for
    /// `E` itself, which is constant within a group, and an aggregate over
    /// `.elements.p` for the same aggregate over `.p`, which the `GROUP BY`
    /// then takes per group.
    fn compile_group_projection(
        &mut self,
        sel: &ast::SelectStmt,
        g: &ast::GroupStmt,
        elements: &[ShapeElement],
    ) -> Result<IrGroup, PyQLError> {
        if sel.filter.is_some() {
            return Err(self.type_err("a shape over a `group` does not support filter"));
        }
        if !g.order_by.is_empty() || g.offset.is_some() || g.limit.is_some() {
            return Err(self.type_err(
                "a `group` read through a shape does not support order by, offset or limit on its elements",
            ));
        }
        let mut grp = self.compile_group(g)?;
        // `.key.k` reads the key as the `GROUP BY` already compiled it:
        // compiling it a second time would give a walk fresh aliases, and
        // Postgres only accepts a grouped expression it can match verbatim.
        let keys: Vec<String> = grp.keys.iter().map(|(name, _)| name.clone()).collect();
        for (name, key) in &grp.keys {
            self.inline_bindings.insert(group_key_binding(name), key.clone());
        }
        let compiled = self.compile_group_projection_parts(sel, &grp, &keys, elements);
        for name in &keys {
            self.inline_bindings.remove(&group_key_binding(name));
        }
        let (pointers, order_by, offset, limit) = compiled?;
        grp.output = IrGroupOutput::Projection(Box::new(IrGroupProjection {
            pointers,
            order_by,
            offset,
            limit,
        }));
        Ok(grp)
    }

    #[allow(clippy::type_complexity)]
    fn compile_group_projection_parts(
        &mut self,
        sel: &ast::SelectStmt,
        grp: &IrGroup,
        keys: &[String],
        elements: &[ShapeElement],
    ) -> Result<(Vec<IrShapePointer>, Vec<IrSort>, Option<IrExpr>, Option<IrExpr>), PyQLError> {
        let td = self.resolve_type(&grp.source.type_name)?;
        let mut rewritten = Vec::with_capacity(elements.len());
        for element in elements {
            let (Some(compexpr), [ast::PathStep::Name(_)]) = (&element.compexpr, element.path.steps.as_slice()) else {
                return Err(self.type_err(
                    "only computed pointers (`name := …`) can be read off a `group` — e.g. `k := .key.name`",
                ));
            };
            let mut element = element.clone();
            element.compexpr = Some(self.rewrite_group_refs(compexpr, keys, td)?);
            rewritten.push(element);
        }
        let alias = grp.source.alias.clone();
        let module = td.module.clone();
        // `td` is here so `.key`/`.elements` resolve, but the row this
        // projects is the group's, not one of `td`'s: an `id` added to it
        // reads a column no GROUP BY covers.
        let pointers = self.without_implicit_id(|this| this.compile_shape(&rewritten, td, &alias, &module))?;
        let order_by = sel
            .order_by
            .iter()
            .map(|sort| {
                Ok(ast::SortExpr {
                    expr: self.rewrite_group_refs(&sort.expr, keys, td)?,
                    direction: sort.direction.clone(),
                    nones: sort.nones.clone(),
                })
            })
            .collect::<Result<Vec<_>, PyQLError>>()?;
        let synthetic = ast::SelectStmt {
            result: Expr::Path(ast::Path::absolute(grp.source.type_name.clone())),
            filter: None,
            order_by,
            offset: sel.offset.clone(),
            limit: sel.limit.clone(),
            lock: None,
        };
        let (_, order_by, offset, limit) = self.compile_path_modifiers(&synthetic, td, &alias)?;
        Ok((pointers, order_by, offset, limit))
    }

    fn rewrite_group_refs(&self, expr: &Expr, keys: &[String], td: &TypeDescriptor) -> Result<Expr, PyQLError> {
        const AGGREGATES: &[&str] = &["count", "sum", "min", "max", "avg", "array_agg", "all", "any"];
        let rewrite = |e: &Expr| self.rewrite_group_refs(e, keys, td);
        Ok(match expr {
            Expr::Path(p) if p.partial => {
                let name = match p.steps.first() {
                    Some(ast::PathStep::Name(name)) => name.as_str(),
                    _ => "",
                };
                match (name, p.steps.get(1..).unwrap_or_default()) {
                    ("key", [ast::PathStep::Name(key)]) if keys.contains(key) => {
                        Expr::Path(ast::Path::absolute(group_key_binding(key)))
                    }
                    ("key", [ast::PathStep::Name(key)]) => {
                        return Err(self.type_err(&format!("'{key}' is not a key of this group")));
                    }
                    ("elements", _) => {
                        return Err(self.type_err(
                            "`.elements` of a group can only be read through an aggregate over one \
                             of their properties — e.g. `count(.elements)`, `sum(.elements.amount)`",
                        ));
                    }
                    _ => {
                        return Err(self.type_err(&format!(
                            "a group has no pointer '{name}' — read `.key.<name>` or aggregate over `.elements`"
                        )));
                    }
                }
            }
            Expr::FunctionCall(f)
                if f.args.len() == 1
                    && f.kwargs.is_empty()
                    && f.module.as_deref().is_none_or(|m| m == "std")
                    && AGGREGATES.contains(&f.name.as_str())
                    && let Expr::Path(p) = &f.args[0]
                    && p.partial
                    && matches!(p.steps.first(), Some(ast::PathStep::Name(n)) if n == "elements") =>
            {
                let property = match p.steps.get(1..).unwrap_or_default() {
                    [] => "id",
                    [ast::PathStep::Name(prop)] if td.properties.iter().any(|d| &d.name == prop) => prop.as_str(),
                    _ => {
                        return Err(self.type_err(&format!(
                            "'{}' over a group's elements only reads one of their own properties",
                            f.name
                        )));
                    }
                };
                Expr::FunctionCall(ast::FunctionCall {
                    module: f.module.clone(),
                    name: f.name.clone(),
                    args: vec![Expr::Path(ast::Path::relative(property))],
                    kwargs: vec![],
                })
            }
            Expr::FunctionCall(f) => Expr::FunctionCall(ast::FunctionCall {
                module: f.module.clone(),
                name: f.name.clone(),
                args: f.args.iter().map(rewrite).collect::<Result<_, _>>()?,
                kwargs: f
                    .kwargs
                    .iter()
                    .map(|(k, v)| Ok((k.clone(), rewrite(v)?)))
                    .collect::<Result<_, PyQLError>>()?,
            }),
            Expr::BinOp(b) => Expr::BinOp(Box::new(ast::BinOp {
                left: rewrite(&b.left)?,
                op: b.op.clone(),
                right: rewrite(&b.right)?,
            })),
            Expr::UnaryOp(u) => Expr::UnaryOp(Box::new(ast::UnaryOp {
                op: u.op.clone(),
                operand: rewrite(&u.operand)?,
            })),
            Expr::TypeCast(c) => Expr::TypeCast(Box::new(ast::TypeCast {
                expr: rewrite(&c.expr)?,
                ty: c.ty.clone(),
            })),
            Expr::IfElse(ie) => Expr::IfElse(Box::new(ast::IfElse {
                if_expr: rewrite(&ie.if_expr)?,
                condition: rewrite(&ie.condition)?,
                else_expr: rewrite(&ie.else_expr)?,
            })),
            other => other.clone(),
        })
    }

    /// `for g in (group S by k) union (select g.elements order by … limit n)`
    /// — the first `n` rows of `S` per key. `None` for any other `for`.
    fn compile_group_elements(&mut self, f: &ast::ForStmt) -> Result<Option<IrGroup>, PyQLError> {
        let Stmt::Select(body) = f.body.as_ref() else {
            return Ok(None);
        };
        let unmodified =
            body.filter.is_none() && body.order_by.is_empty() && body.offset.is_none() && body.limit.is_none();
        let (inner, shape) = match &body.result {
            Expr::Shape(sh) if unmodified => match &sh.expr {
                Some(Expr::SubQuery(stmt)) => match stmt.as_ref() {
                    Stmt::Select(inner) => (inner, Some(sh.elements.as_slice())),
                    _ => return Ok(None),
                },
                _ => return Ok(None),
            },
            _ => (body, None),
        };
        let reads_elements = matches!(&inner.result, Expr::Path(p) if !p.partial
            && matches!(p.steps.as_slice(), [ast::PathStep::Name(var), ast::PathStep::Name(elements)]
                if var == &f.var && elements == "elements"));
        if !reads_elements {
            return Ok(None);
        }
        let mut grp = match &f.iterator {
            Expr::SubQuery(stmt) => match stmt.as_ref() {
                Stmt::Group(g) => self.compile_group(g)?,
                _ => return Ok(None),
            },
            Expr::Path(p) if !p.partial => match p.steps.as_slice() {
                [ast::PathStep::Name(name)] => match self.group_bindings.get(name) {
                    Some(grp) => grp.clone(),
                    None => return Ok(None),
                },
                _ => return Ok(None),
            },
            _ => return Ok(None),
        };
        let ordered = !inner.order_by.is_empty() || inner.offset.is_some() || inner.limit.is_some();
        if ordered && (!grp.order_by.is_empty() || grp.offset.is_some() || grp.limit.is_some()) {
            return Err(self.type_err(
                "a group that already orders or limits its elements cannot be ordered or limited again by a `for` over it",
            ));
        }
        let td = self.resolve_type(&grp.source.type_name)?;
        let alias = grp.source.alias.clone();
        let synthetic = ast::SelectStmt {
            result: Expr::Path(ast::Path::absolute(grp.source.type_name.clone())),
            ..inner.clone()
        };
        let (filter, order_by, offset, limit) = self.compile_path_modifiers(&synthetic, td, &alias)?;
        grp.filter = and_conditions(grp.filter, filter.into_iter().collect());
        if ordered {
            grp.order_by = order_by;
            grp.offset = offset;
            grp.limit = limit;
        }
        if let Some(shape) = shape {
            let module = td.module.clone();
            grp.shape = self.compile_shape(shape, td, &alias, &module)?;
        }
        grp.output = IrGroupOutput::Elements;
        Ok(Some(grp))
    }

    /// The key a single-link assignment stores, for the values that name a
    /// row rather than compute one. `None` for anything the generic
    /// expression route already handles.
    fn compile_link_key(&mut self, expr: &Expr, td: &TypeDescriptor, alias: &str) -> Result<Option<IrExpr>, PyQLError> {
        // A one-element set is that element — `credentials := {
        // (insert Credentials { … }) }` says the same thing as assigning the
        // insert directly.
        let value = match expr {
            Expr::Set(elements) if elements.len() == 1 => &elements[0],
            other => other,
        };
        match value {
            // `link := (select { <T>a.id, <T>b.id } limit 1)` — a set literal
            // of keys, read for the one value its clauses leave.
            Expr::SubQuery(inner_stmt)
                if matches!(inner_stmt.as_ref(), Stmt::Select(sel) if matches!(sel.result, Expr::Set(_))) =>
            {
                let IrStmt::Select(select) = self.compile_stmt(inner_stmt)? else {
                    return Ok(None);
                };
                if !select.rows.iter().all(|r| matches!(r, IrRowSource::Free(IrFreeExpr::Scalar(_)))) {
                    return Ok(None);
                }
                Ok(Some(IrExpr::ScalarSubquery(Box::new(select))))
            }
            // Link assignment via subquery: `company := (SELECT Company FILTER ...)`
            // Compile as a scalar subquery returning the target pk (the FK uuid).
            Expr::SubQuery(inner_stmt) => self.compile_link_subquery(inner_stmt).map(Some),
            // `created_by := account_of_transaction()` — an object-returning
            // function names the row to link to, so what is stored is its key,
            // the same as for a select. The schema itself writes this as a
            // link default.
            Expr::FunctionCall(fc) => self.try_compile_fn_scalar_subquery(fc, &["id".to_string()], None, None),
            // `credentials := (update c set { … }) if exists(c) else (insert
            // Credentials { … })` — each mutation carries its own condition,
            // so exactly one branch yields the row to link.
            Expr::IfElse(ie)
                if [&ie.if_expr, &ie.else_expr].iter().any(|b| {
                    matches!(b, Expr::SubQuery(s) if matches!(s.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_)))
                }) =>
            {
                let Some(rewritten) = self.object_if_else_as_union(value) else {
                    return Ok(None);
                };
                self.compile_link_key(&rewritten, td, alias)
            }
            Expr::Union(a, b) => {
                let (Some(left), Some(right)) = (self.compile_link_key(a, td, alias)?, self.compile_link_key(b, td, alias)?)
                else {
                    return Ok(None);
                };
                // A hoisted mutation's key is read by subquery: joined into
                // the statement instead, the branch that wrote nothing would
                // leave no row to update.
                let hoisted = |key: IrExpr| match key {
                    IrExpr::ColumnRef { alias, column, .. } if column == "id" => IrExpr::CteRef {
                        name: alias,
                        scalar: false,
                        pg_type: None,
                    },
                    other => other,
                };
                Ok(Some(IrExpr::FunctionCall(IrFunctionCall {
                    return_pg_type: None,
                    schema: None,
                    name: "coalesce".to_string(),
                    args: vec![hoisted(left), hoisted(right)],
                    sql_template: None,
                })))
            }
            // `by := account_of_transaction() if cond else {}` — each branch
            // names a row (or none) the same way.
            Expr::IfElse(ie) => {
                if ![&ie.if_expr, &ie.else_expr].iter().any(|b| matches!(b, Expr::FunctionCall(_))) {
                    return Ok(None);
                }
                Ok(Some(IrExpr::IfElse(Box::new(IrIfElse {
                    condition: self.compile_expr(&ie.condition, td, alias)?,
                    if_: self.compile_link_branch(&ie.if_expr, td, alias)?,
                    else_: self.compile_link_branch(&ie.else_expr, td, alias)?,
                }))))
            }
            _ => Ok(None),
        }
    }

    fn compile_link_branch(&mut self, branch: &Expr, td: &TypeDescriptor, alias: &str) -> Result<IrExpr, PyQLError> {
        if matches!(branch, Expr::Set(elements) if elements.is_empty()) {
            return Ok(IrExpr::Null);
        }
        match self.compile_link_key(branch, td, alias)? {
            Some(key) => Ok(key),
            None => self.compile_expr(branch, td, alias),
        }
    }

    /// `.teams { owning := … }.owning` — a walk, and a pointer its shape
    /// declares read back off each row it lands on. `None` for anything
    /// else, including a field the shape does not compute.
    fn compile_shape_field_select(
        &mut self,
        expr: &Expr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<Option<IrPathSelect>, PyQLError> {
        let Expr::FieldAccess { expr: inner, field } = expr else {
            return Ok(None);
        };
        let Expr::Shape(sh) = inner.as_ref() else {
            return Ok(None);
        };
        let Some(Expr::Path(base)) = sh.expr.as_ref() else {
            return Ok(None);
        };
        let Some(value) = sh
            .elements
            .iter()
            .find(|el| matches!(el.path.steps.as_slice(), [ast::PathStep::Name(n)] if n == field))
            .and_then(|el| el.compexpr.clone())
        else {
            return Ok(None);
        };
        let (rooted, correlate) = if base.partial {
            let Some((td, alias)) = ctx else {
                return Ok(None);
            };
            let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
            steps.extend(base.steps.iter().cloned());
            (ast::Path { steps, partial: false }, Some(alias.to_string()))
        } else if base.steps.len() > 1 {
            (base.clone(), None)
        } else if let [ast::PathStep::Name(root)] = base.steps.as_slice()
            && let Ok(root_td) = self.resolve_path_root(root)
        {
            // A walk needs a step: `T[is T]` lands on the same objects.
            let narrowing = ast::PathStep::TypeIntersection(ast::ObjectRef {
                module: Some(root_td.module.clone()),
                name: root_td.name.clone(),
            });
            (
                ast::Path {
                    steps: vec![base.steps[0].clone(), narrowing],
                    partial: false,
                },
                None,
            )
        } else {
            return Ok(None);
        };
        let synthetic = ast::SelectStmt {
            result: Expr::Path(rooted.clone()),
            filter: None,
            order_by: vec![],
            offset: None,
            limit: None,
            lock: None,
        };
        let mut ps = self.compile_path_select(&synthetic, &rooted, &[], false)?;
        if let Some(alias) = correlate {
            Self::correlate_path_select(&mut ps, &alias);
        }
        let IrPathResult::Object { alias, type_name, .. } = &ps.result else {
            return Err(self.type_err(&format!(
                "'{field}' is read off a walk that lands on a value, which has no shape"
            )));
        };
        let (alias, type_name) = (alias.clone(), type_name.clone());
        let td = self.resolve_type(&type_name)?;
        let value = self.compile_expr(&value, td, &alias)?;
        // A computed standing for a set is an array per row; the field reads
        // its elements, so the rows of all of them make up one set.
        let value = if yields_array(&value) {
            IrExpr::FunctionCall(IrFunctionCall {
                return_pg_type: None,
                schema: None,
                name: "unnest".to_string(),
                args: vec![value],
                sql_template: None,
            })
        } else {
            value
        };
        ps.result = IrPathResult::Scalar(value, None);
        Ok(Some(ps))
    }

    /// `l.addon.id` — an absolute walk that lands on a property, so it yields
    /// values rather than objects.
    fn is_scalar_walk(&self, expr: &Expr) -> bool {
        let Expr::Path(p) = expr else { return false };
        let (Some(ast::PathStep::Name(root)), false) = (p.steps.first(), p.partial) else {
            return false;
        };
        let (Some(ast::PathStep::Name(leaf)), [_, middle @ .., _]) = (p.steps.last(), p.steps.as_slice()) else {
            return false;
        };
        let Ok(root_td) = self.resolve_path_root(root) else {
            return false;
        };
        let owner = if middle.is_empty() {
            Some(root_td)
        } else {
            self.walk_path_types(root_td, middle, MAX_COMPUTED_SPLICES).1
        };
        owner.is_some_and(|td| Self::resolve_property(td, leaf).is_some())
    }

    /// `a.id union b.id` — each operand compiled as the select it stands
    /// for, the rows of all of them concatenated.
    fn compile_scalar_union(&mut self, expr: &Expr) -> Result<IrStmt, PyQLError> {
        fn operands<'e>(expr: &'e Expr, out: &mut Vec<&'e Expr>) {
            match expr {
                Expr::Union(a, b) => {
                    operands(a, out);
                    operands(b, out);
                }
                other => out.push(other),
            }
        }
        let mut exprs = vec![];
        operands(expr, &mut exprs);
        let mut branches = Vec::with_capacity(exprs.len());
        for operand in exprs {
            let stmt = match operand {
                Expr::SubQuery(stmt) => stmt.as_ref().clone(),
                other => Stmt::Select(ast::SelectStmt {
                    result: other.clone(),
                    filter: None,
                    order_by: vec![],
                    offset: None,
                    limit: None,
                    lock: None,
                }),
            };
            branches.push(self.compile_stmt(&stmt)?);
        }
        let types: Vec<String> = branches.iter().map(cte_stmt_type).collect();
        let first = types.iter().find(|t| !t.is_empty()).cloned().unwrap_or_default();
        if let Some(other) = types
            .iter()
            .find(|t| t.contains("::") || (!t.is_empty() && **t != first))
        {
            let display = |t: &str| {
                if t.contains("::") {
                    t.to_string()
                } else {
                    pg_type_to_pyql(t).to_string()
                }
            };
            return Err(self.type_err(&format!(
                "operator 'UNION' cannot be applied to operands of type '{}' and '{}'",
                display(&first),
                display(other)
            )));
        }
        Ok(IrStmt::ScalarUnion(branches))
    }

    /// Extract the target type name from a DML or inner SELECT statement.
    fn dml_subject_type(&self, stmt: &Stmt) -> Result<String, PyQLError> {
        match stmt {
            Stmt::Insert(ins) => Ok(ins.subject.qualified_name()),
            Stmt::Update(upd) => self.subject_type_name(&upd.subject),
            Stmt::Delete(del) => self.subject_type_name(&del.subject),
            Stmt::With(w) => self.dml_subject_type(&w.stmt),
            Stmt::For(f) => self.dml_subject_type(&f.body),
            Stmt::Analyze(inner) => self.dml_subject_type(inner),
            Stmt::Group(g) => self.expr_as_type_name(&g.subject),
            Stmt::Select(sel) => {
                // <Module::Type>expr — type name comes from the cast target
                if let Expr::TypeCast(tc) = &sel.result
                    && let Some((module, name)) = tc.ty.as_named()
                    && module.map(|m| m != "std").unwrap_or(false)
                {
                    return Ok(name.to_string());
                }
                // `select resource.revisions` — a walk names no type of its
                // own; what it lands on is the type the statement yields.
                if let Expr::Path(path) = &sel.result
                    && !path.partial
                    && path.steps.len() > 1
                    && let Some(ast::PathStep::Name(root)) = path.steps.first()
                    && let Ok(root_td) = self.resolve_path_root(root)
                    && let (_, Some(target)) = self.walk_path_types(root_td, &path.steps[1..], MAX_COMPUTED_SPLICES)
                {
                    return Ok(format!("{}::{}", target.module, target.name));
                }
                // SELECT-over-SELECT: get the type from the inner select's result
                let (type_name, _, _, _) = self.extract_type_and_shape(&sel.result)?;
                Ok(type_name)
            }
        }
    }

    /// `id in (…)` over the rows a DML subject path traverses to, so a
    /// mutation written against a traversal touches those rows and no others.
    fn compile_subject_path_rows(&mut self, subject: &ast::Path, target_alias: &str) -> Result<IrExpr, PyQLError> {
        // Traversing to `.id` rather than stopping at the objects: a path that
        // ends on a link or a type intersection has nothing to project, and the
        // ids are what the narrowing compares against anyway.
        let mut steps = subject.steps.clone();
        steps.push(ast::PathStep::Name("id".to_string()));
        let ids = ast::Path { steps, partial: false };
        let synthetic = ast::SelectStmt {
            result: Expr::Path(ids.clone()),
            filter: None,
            order_by: vec![],
            offset: None,
            limit: None,
            lock: None,
        };
        let rows = self.compile_path_select(&synthetic, &ids, &[], false)?;
        Ok(IrExpr::BinOp(Box::new(IrBinOp {
            left: IrExpr::ColumnRef {
                alias: target_alias.to_string(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
            op: ast::BinOpKind::In,
            right: IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(rows)))),
        })))
    }

    /// The type a DML subject names, however it is written: a type, a `with`
    /// binding, or a traversal that ends on one.
    fn subject_type_name(&self, subject: &Expr) -> Result<String, PyQLError> {
        if let Expr::Path(p) = subject
            && p.steps.len() > 1
            && let Some(ast::PathStep::Name(root)) = p.steps.first()
            && let Ok(root_td) = self.resolve_path_root(root)
            && let (_, Some(target)) = self.walk_path_types(root_td, &p.steps[1..], MAX_COMPUTED_SPLICES)
        {
            return Ok(format!("{}::{}", target.module, target.name));
        }
        // A subject that is just a `with` binding names rows, not a type, so
        // the type is the one the binding was bound to. `compile_update`
        // wants the binding's own name (it narrows the update to those rows);
        // a reader asking what type the statement yields wants this.
        if let Expr::Path(p) = subject
            && !p.partial
            && let [ast::PathStep::Name(root)] = p.steps.as_slice()
            && let Some(bound) = self.cte_object_type(root)
        {
            return Ok(bound);
        }
        self.expr_as_type_name(subject)
    }

    fn expr_as_type_name(&self, expr: &Expr) -> Result<String, PyQLError> {
        if std::env::var("PYLON_DBG_SUBJ").is_ok() {
            eprintln!(
                "DBG subj {:.90?}
{}",
                expr,
                std::backtrace::Backtrace::force_capture()
            );
        }
        match expr {
            // `detached T` names the same type; the prefix only says the set
            // is not correlated with the enclosing one.
            Expr::Detached(inner) => self.expr_as_type_name(inner),
            Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
                if let ast::PathStep::Name(n) = &p.steps[0] {
                    return Ok(n.clone());
                }
                Err(self.type_err("expected a type name"))
            }
            // `select (a union b)` as a SELECT-over-SELECT subject: every
            // branch carries the same object type, and that is the subject.
            Expr::Union(_, _) => {
                let branches = self
                    .object_union_branches(expr)
                    .ok_or_else(|| self.type_err("expected a type name as SELECT subject"))?;
                self.common_union_type(&branches)
                    .ok_or_else(|| self.type_err("expected a type name as SELECT subject"))
            }
            // `placed.line_items` — a walk names no type of its own; the type
            // meant is the one it lands on, which is how `dml_subject_type`
            // already reads the same path.
            Expr::Path(p)
                if !p.partial
                    && p.steps.len() > 1
                    && let Some(ast::PathStep::Name(root)) = p.steps.first()
                    && let Ok(root_td) = self.resolve_path_root(root)
                    && let (_, Some(target)) = self.walk_path_types(root_td, &p.steps[1..], MAX_COMPUTED_SPLICES) =>
            {
                Ok(format!("{}::{}", target.module, target.name))
            }
            _ => Err(self.type_err("expected a type name as SELECT subject")),
        }
    }

    // ── INSERT ────────────────────────────────────────────────────────────────────

    fn compile_insert(&mut self, ins: &ast::InsertStmt) -> Result<IrInsert, PyQLError> {
        // Isolate this insert's own nested-DML discoveries (see
        // `pending_nested_ctes`'s doc comment) from whatever an enclosing
        // compile (e.g. this insert itself being the nested DML inside an
        // *outer* insert's link value) had pending, so each level attaches
        // only its own CTEs to its own `IrInsert`.
        let outer_pending_nested_ctes = std::mem::take(&mut self.pending_nested_ctes);
        let type_name = ins.subject.qualified_name();
        let td = self.resolve_type(&type_name)?;
        if td.abstract_ && td.materialized {
            return Err(self.type_err(&format!(
                "cannot insert into interface type '{}::{}'; insert into a concrete type instead",
                td.module, td.name
            )));
        }
        let alias = self.fresh_alias();
        let target = IrSource {
            poly: None,
            type_name: format!("{}::{}", td.module, td.name),
            table: td.table.clone(),
            alias: alias.clone(),
        };

        // Multi-link shape elements (`tags := ...` / `tags += ...`) populate
        // the junction table once the row exists; everything else goes
        // through the normal scalar/link assignment path.
        let mut shape = ins.shape.clone();
        for link in &td.links {
            let unset = !shape.iter().any(|el| path_leaf(&el.path).is_ok_and(|n| n == link.name));
            for rw in link.rewrites.iter().filter(|rw| rw.on & 1 != 0) {
                if let Some(value) = subject_default_insert(&rw.handler, &link.name)
                    && unset
                {
                    shape.push(ShapeElement {
                        path: ast::Path::relative(&link.name),
                        splat: None,
                        nested: None,
                        compexpr: Some(value),
                        op: ShapeOp::Assign,
                        filter: None,
                        order_by: vec![],
                        offset: None,
                        limit: None,
                        marker_offset: None,
                    });
                }
            }
        }
        // Pointer defaults the shape leaves out. Gel applies every default by
        // expanding it into the insert's own shape (`_gen_pointers_from_defaults`);
        // the ones a column DEFAULT can hold are left to it here, so only the
        // rest — a default reading a session global, or selecting the object to
        // link to — is expanded.
        for (pointer, pyql) in inlined_pointer_defaults(td, self.schema) {
            if shape.iter().any(|el| path_leaf(&el.path).is_ok_and(|n| n == pointer)) {
                continue;
            }
            let value = crate::parse::parse_pointer_expr(&pyql)?;
            shape.push(default_shape_element(&pointer, value));
        }
        let mut multi_link_appends = vec![];
        let mut scalar_elements: Vec<ShapeElement> = vec![];
        for el in &shape {
            let pointer_name = match path_leaf(&el.path) {
                Ok(n) => n,
                Err(_) => {
                    scalar_elements.push(el.clone());
                    continue;
                }
            };
            if let Some(ml) = Self::resolve_multilink(td, pointer_name) {
                match el.op {
                    ShapeOp::Remove => {
                        return Err(self.type_err(&format!(
                            "cannot use `-=` for multi-link '{pointer_name}' in an insert; \
                         there is nothing to remove from yet"
                        )));
                    }
                    ShapeOp::Assign | ShapeOp::Append => {
                        if let Some(expr) = &el.compexpr {
                            let (jt, module, src_col, tgt_col, through_td) =
                                self.own_multilink_junction_info(td, ml)?;
                            let values = self.compile_multilink_values(expr, td, &alias, through_td)?;
                            multi_link_appends.push(IrMultiLinkMutation {
                                junction_table: jt,
                                module,
                                source_col: src_col,
                                target_col: tgt_col,
                                values,
                                single: false,
                            });
                        }
                    }
                }
            } else if let Some(l) = Self::resolve_link(td, pointer_name).filter(|l| l.is_junction_backed()) {
                // A junction-backed single link is "a multi-link capped to
                // one row" (D1) — on insert there's nothing to replace yet,
                // so `:=` populates the junction table the same way a
                // multi-link's own `:=`/`+=` does above.
                if matches!(el.op, ShapeOp::Remove) {
                    return Err(self.type_err(&format!(
                        "cannot use `-=` for link '{pointer_name}' in an insert; \
                         there is nothing to remove from yet"
                    )));
                }
                if let Some(expr) = &el.compexpr {
                    // `:= {}` / `:= <Type>{}` at insert time — same as
                    // omitting the pointer entirely: nothing to append, no
                    // junction row created yet.
                    if !is_empty_set_expr(expr) {
                        let (jt, module, src_col, tgt_col, through_td) = self.own_link_junction_info(td, l)?;
                        let values = self.compile_multilink_values(expr, td, &alias, through_td)?;
                        multi_link_appends.push(IrMultiLinkMutation {
                            junction_table: jt,
                            module,
                            source_col: src_col,
                            target_col: tgt_col,
                            values,
                            single: true,
                        });
                    }
                }
            } else {
                scalar_elements.push(el.clone());
            }
        }

        let assignments = self.compile_assignments(&scalar_elements, td, &alias)?;
        // Rewrites apply in the table's own `BEFORE` trigger — see
        // `export::rewrite_trigger_infos`.
        let rewrites = vec![];
        let unless_conflict = match ins.unless_conflict.as_ref() {
            Some(uc) => {
                let (conflict, else_appends) = self.compile_conflict(uc, td)?;
                multi_link_appends.extend(else_appends);
                Some(conflict)
            }
            None => None,
        };
        let returning = Self::pk_returning(td);
        let type_name = format!("{}::{}", td.module, td.name);
        let enqueue_vector = td
            .vector_indexes
            .iter()
            .map(|vi| VectorEnqueueInfo {
                type_name: type_name.clone(),
                index_name: vi.index_name.clone(),
            })
            .collect();
        let enqueue_search = collect_search_enqueue(td, &type_name, "index");
        let nested_ctes = std::mem::replace(&mut self.pending_nested_ctes, outer_pending_nested_ctes);

        let guard = match self.pending_insert_guard.take() {
            Some(condition) => Some(self.compile_expr(&condition, td, &alias)?),
            None => None,
        };
        // Only a `for` body's nested insert needs to name its own id (see
        // `IrInsert::id_default_sql`); carried here because the schema is in
        // scope, and ignored everywhere else.
        let id_default_sql =
            Self::resolve_property(td, "id").map(|p| p.default_sql.clone().unwrap_or_else(|| "uuidv7()".to_string()));
        Ok(IrInsert {
            guard,
            target,
            assignments,
            unless_conflict,
            rewrites,
            id_default_sql,
            returning,
            enqueue_vector,
            enqueue_search,
            multi_link_appends,
            nested_ctes,
        })
    }

    fn compile_assignments(
        &mut self,
        elements: &[ShapeElement],
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<Vec<(String, IrExpr)>, PyQLError> {
        self.compile_assignments_inner(elements, td, alias, false)
    }

    fn compile_assignments_for_update(
        &mut self,
        elements: &[ShapeElement],
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<Vec<(String, IrExpr)>, PyQLError> {
        self.compile_assignments_inner(elements, td, alias, true)
    }

    fn compile_assignments_inner(
        &mut self,
        elements: &[ShapeElement],
        td: &TypeDescriptor,
        alias: &str,
        deny_readonly: bool,
    ) -> Result<Vec<(String, IrExpr)>, PyQLError> {
        // A value assigned in a mutation body is not output, and a link value
        // among them compiles to a one-column correlated subquery — an implicit
        // `id` beside the column it selects would make that subquery illegal.
        self.without_implicit_id(|this| this.compile_assignments_rows(elements, td, alias, deny_readonly))
    }

    fn compile_assignments_rows(
        &mut self,
        elements: &[ShapeElement],
        td: &TypeDescriptor,
        alias: &str,
        deny_readonly: bool,
    ) -> Result<Vec<(String, IrExpr)>, PyQLError> {
        elements
            .iter()
            .map(|el| {
                let pointer_name = path_leaf(&el.path)?;
                let expr = el.compexpr.as_ref().ok_or_else(|| {
                    PyQLError::Type(PyQLTypeError {
                        message: format!("INSERT pointer '{pointer_name}' has no value expression"),
                        position: Position { line: 0, col: 0 },
                    })
                })?;

                // Validate the pointer exists
                let column = if let Some(p) = Self::resolve_property(td, pointer_name) {
                    // A primary-key ("id") property: an UPDATE never allows
                    // reassigning it (deny_readonly is true there, regardless
                    // of the session config); an INSERT only allows an
                    // explicit value when allow_user_specified_id is set.
                    if p.is_pk && (deny_readonly || !self.config.allow_user_specified_id) {
                        return Err(PyQLError::Type(PyQLTypeError {
                            message: "cannot assign to property 'id'".to_string(),
                            position: Position { line: 0, col: 0 },
                        }));
                    }
                    if deny_readonly && p.is_readonly {
                        return Err(PyQLError::Type(PyQLTypeError {
                            message: format!("cannot update property '{pointer_name}': it is declared as read-only"),
                            position: Position { line: 0, col: 0 },
                        }));
                    }
                    p.name.clone()
                } else if let Some(l) = Self::resolve_link(td, pointer_name) {
                    if deny_readonly && l.is_readonly {
                        return Err(PyQLError::Type(PyQLTypeError {
                            message: format!("cannot update link '{pointer_name}': it is declared as read-only"),
                            position: Position { line: 0, col: 0 },
                        }));
                    }
                    if l.is_junction_backed() {
                        // Reachable only via `UNLESS CONFLICT ... ELSE (UPDATE
                        // ... SET { ... })` — `compile_insert`/`compile_update`'s
                        // own shape-classification loop intercepts a junction-
                        // backed link before it ever reaches this generic
                        // scalar-assignment path; the ELSE clause has no
                        // junction-mutation mechanism of its own to reuse.
                        return Err(PyQLError::Type(PyQLTypeError {
                            message: format!(
                                "'{pointer_name}' is a junction-backed link and cannot be \
                                 assigned inside an UNLESS CONFLICT ELSE clause"
                            ),
                            position: Position { line: 0, col: 0 },
                        }));
                    }
                    // Link assignment via subquery: `company := (SELECT Company FILTER ...)`
                    // Compile as a scalar subquery returning the target pk (the FK uuid).
                    // A one-element set is that element — `credentials := {
                    // (insert Credentials { … }) }` says the same thing as
                    // assigning the insert directly.
                    let fk_col = format!("{}_id", l.name);
                    if let Some(ir_expr) = self.compile_link_key(expr, td, alias)? {
                        return Ok((fk_col, ir_expr));
                    }
                    fk_col
                } else if Self::resolve_multilink(td, pointer_name).is_some() {
                    // Same reach as the junction-backed link above: the
                    // shape-classification loop in `compile_insert` and
                    // `compile_update` takes multi-links first, so one only
                    // arrives here from an `UNLESS CONFLICT ... ELSE` clause,
                    // which has no junction-mutation mechanism to reuse.
                    // Saying the pointer does not exist sends the reader
                    // looking for a typo in a name that is plainly right.
                    return Err(PyQLError::Type(PyQLTypeError {
                        message: format!(
                            "'{pointer_name}' is a multi-link and cannot be mutated inside an \
                             UNLESS CONFLICT ELSE clause"
                        ),
                        position: Position { line: 0, col: 0 },
                    }));
                } else if Self::resolve_multilink(td, pointer_name).is_some() {
                    return Err(self.field_err(pointer_name, &format!("{}::{}", td.module, td.name)));
                } else if self.resolve_computed(td, pointer_name).is_some() {
                    // Reported as "no link or property 'x'. Did you mean 'x'?"
                    // before: the suggester's name list includes computeds,
                    // the resolution above does not, so it handed back the very
                    // name it had just refused.
                    return Err(self.type_err(&format!(
                        "cannot assign to '{pointer_name}': it is a computed pointer on \
                         {}::{}, which has no stored column to write",
                        td.module, td.name
                    )));
                } else {
                    return Err(self.field_err(pointer_name, &format!("{}::{}", td.module, td.name)));
                };

                // `{}` (empty set) in assignment position means NULL.
                let ir_expr = if matches!(expr, Expr::Set(v) if v.is_empty()) {
                    IrExpr::Null
                } else {
                    self.compile_expr(expr, td, alias)?
                };
                Ok((column, ir_expr))
            })
            .collect()
    }

    // ── UPDATE ────────────────────────────────────────────────────────────────────

    fn compile_update(&mut self, upd: &ast::UpdateStmt) -> Result<IrUpdate, PyQLError> {
        // Taken before anything nested is compiled, so a nested statement
        // cannot pick up a guard meant for this one.
        let pending_guard = self.pending_update_guard.take();
        // See `compile_insert`'s identical save/restore of `pending_nested_ctes`.
        let outer_pending_nested_ctes = std::mem::take(&mut self.pending_nested_ctes);
        // `update (select T filter …).link set { … }` — the subject walks off a
        // sub-select rather than off a named root. The select is hoisted into
        // the statement's own WITH and the walk re-rooted at that binding,
        // giving the `with s := (select …) update s.link set { … }` spelling
        // the path branch below already handles.
        if !matches!(&upd.subject, Expr::Path(_)) {
            let (base, fields) = Self::peel_field_access_chain(&upd.subject);
            if let Expr::SubQuery(inner_stmt) = base
                && !fields.is_empty()
                && matches!(inner_stmt.as_ref(), Stmt::Select(_))
            {
                let inner = self.compile_stmt(inner_stmt)?;
                let cte_name = self.fresh_nested_cte_name();
                let type_name = self.register_cte(&cte_name, &inner);
                self.hoisted_ctes.push(IrCteDef {
                    name: cte_name.clone(),
                    stmt: inner,
                    type_name,
                    correlated_to: None,
                });
                let mut steps = vec![ast::PathStep::Name(cte_name)];
                steps.extend(fields.into_iter().map(ast::PathStep::Name));
                let rerooted = ast::UpdateStmt {
                    subject: Expr::Path(ast::Path { steps, partial: false }),
                    filter: upd.filter.clone(),
                    shape: upd.shape.clone(),
                };
                self.pending_nested_ctes = outer_pending_nested_ctes;
                self.pending_update_guard = pending_guard;
                return self.compile_update(&rerooted);
            }
        }
        // `update account.preferences[is IndividualPreferences] set …` — the
        // subject is a traversal rather than a name, so the rows to update are
        // the ones it lands on: the table is the type the walk ends on, and the
        // update is narrowed to the ids the traversal yields.
        if let Expr::Path(subject) = &upd.subject
            && subject.steps.len() > 1
            && let Some(ast::PathStep::Name(root)) = subject.steps.first()
            && let Ok(root_td) = self.resolve_path_root(root)
            && let (_, Some(target_td)) = self.walk_path_types(root_td, &subject.steps[1..], MAX_COMPUTED_SPLICES)
        {
            let narrowed = ast::UpdateStmt {
                subject: Expr::Path(ast::Path {
                    steps: vec![ast::PathStep::Name(format!("{}::{}", target_td.module, target_td.name))],
                    partial: false,
                }),
                filter: upd.filter.clone(),
                shape: upd.shape.clone(),
            };
            self.pending_nested_ctes = outer_pending_nested_ctes;
            self.pending_update_guard = pending_guard;
            let mut ir = self.compile_update(&narrowed)?;
            // Built after the update, so the comparison names that update's own
            // alias: with a nested statement's CTE in the FROM, a bare `id`
            // could mean either relation.
            let rows = self.compile_subject_path_rows(subject, &ir.target.alias)?;
            ir.filter = Some(and_conditions(ir.filter.take(), vec![rows]).expect("row set is present"));
            return Ok(ir);
        }
        let type_name = self.expr_as_type_name(&upd.subject)?;
        // `update account set …` where `account` is a `with` binding: the
        // binding names the rows to update, so it decides the table *and*
        // narrows the update to its own rows. Without the narrowing this would
        // resolve to the type and rewrite every row in the table.
        let bound_rows = self.cte_object_type(&type_name);
        // `for p in … union (update p set …)` — the same for a loop variable,
        // which names the one row this iteration holds. Without it the UPDATE
        // went out with no WHERE at all and rewrote every row of the table.
        let iterated = self
            .for_var_types
            .contains_key(&type_name)
            .then(|| self.for_var_ref(&type_name));
        let td = self.resolve_path_root(&type_name)?;
        let alias = self.fresh_alias();
        let target = IrSource {
            poly: None,
            type_name: format!("{}::{}", td.module, td.name),
            table: td.table.clone(),
            alias: alias.clone(),
        };

        let declared_filter = upd
            .filter
            .as_ref()
            .map(|f| self.compile_expr(f, td, &alias))
            .transpose()?;
        let filter = match bound_rows {
            Some(_) => {
                let membership = IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: alias.clone(),
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    },
                    op: ast::BinOpKind::In,
                    right: IrExpr::ArrayFromSelect(Box::new(IrArraySource::Select(IrSelect::schema_bound(
                        IrSource {
                            poly: None,
                            type_name: format!("{}::{}", td.module, td.name),
                            table: format!("@cte:{type_name}"),
                            alias: self.fresh_alias(),
                        },
                        vec![],
                        None,
                    )))),
                }));
                Some(and_conditions(declared_filter, vec![membership]).expect("membership is present"))
            }
            None => declared_filter,
        };
        let filter = match iterated {
            Some(value) => {
                let this_row = IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: alias.clone(),
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    },
                    op: ast::BinOpKind::Eq,
                    right: value,
                }));
                Some(and_conditions(filter, vec![this_row]).expect("the row condition is present"))
            }
            None => filter,
        };
        // `(update cart set { … }) if not exists(existing) else {}` — the
        // condition narrows the rows this update touches. Left to filter what
        // is read back instead, the update would still run.
        let filter = match pending_guard {
            Some(condition) => {
                let guard = self.compile_expr(&condition, td, &alias)?;
                and_conditions(filter, vec![guard])
            }
            None => filter,
        };

        // Classify shape elements by kind.
        let mut multi_link_clears = vec![];
        let mut multi_link_replaces = vec![];
        let mut multi_link_appends = vec![];
        let mut multi_link_removals = vec![];
        let mut scalar_elements: Vec<ShapeElement> = vec![];

        for el in &upd.shape {
            let pointer_name = match path_leaf(&el.path) {
                Ok(n) => n,
                Err(_) => {
                    scalar_elements.push(el.clone());
                    continue;
                }
            };

            if let Some(ml) = Self::resolve_multilink(td, pointer_name) {
                let (jt, module, src_col, tgt_col, through_td) = self.own_multilink_junction_info(td, ml)?;

                match el.op {
                    ShapeOp::Assign => {
                        let is_empty = el
                            .compexpr
                            .as_ref()
                            .map(|e| matches!(e, Expr::Set(v) if v.is_empty()))
                            .unwrap_or(false);
                        if is_empty {
                            // := {} — clear all junction rows
                            multi_link_clears.push(IrMultiLinkClear {
                                junction_table: jt,
                                module,
                                source_col: src_col,
                            });
                        } else if let Some(expr) = &el.compexpr {
                            // := expr — replace (clear + insert)
                            multi_link_clears.push(IrMultiLinkClear {
                                junction_table: jt.clone(),
                                module: module.clone(),
                                source_col: src_col.clone(),
                            });
                            let values = self.compile_multilink_values(expr, td, &alias, through_td)?;
                            multi_link_replaces.push(IrMultiLinkMutation {
                                junction_table: jt,
                                module,
                                source_col: src_col,
                                target_col: tgt_col,
                                values,
                                single: false,
                            });
                        }
                    }
                    ShapeOp::Append => {
                        if let Some(expr) = &el.compexpr {
                            let values = self.compile_multilink_values(expr, td, &alias, through_td)?;
                            multi_link_appends.push(IrMultiLinkMutation {
                                junction_table: jt,
                                module,
                                source_col: src_col,
                                target_col: tgt_col,
                                values,
                                single: false,
                            });
                        }
                    }
                    ShapeOp::Remove => {
                        if let Some(expr) = &el.compexpr {
                            let values = self.compile_multilink_values(expr, td, &alias, through_td)?;
                            if has_any_link_props(&values) {
                                return Err(self.type_err(
                                    "link properties (`@prop := value`) cannot be assigned \
                                     when removing a link (`-=`)",
                                ));
                            }
                            multi_link_removals.push(IrMultiLinkMutation {
                                junction_table: jt,
                                module,
                                source_col: src_col,
                                target_col: tgt_col,
                                values,
                                single: false,
                            });
                        }
                    }
                }
            } else if let Some(l) = Self::resolve_link(td, pointer_name).filter(|l| l.is_junction_backed()) {
                // Same replace-via-clear-then-insert shape a multi-link's
                // own `:=` uses — only `:=` is meaningful for a single
                // link, whether FK-backed or junction-backed.
                if !matches!(el.op, ShapeOp::Assign) {
                    return Err(self.type_err(&format!(
                        "'{pointer_name}' is a single link; only `:=` is supported, not `+=`/`-=`"
                    )));
                }
                let (jt, module, src_col, tgt_col, through_td) = self.own_link_junction_info(td, l)?;
                let is_empty = el.compexpr.as_ref().map(is_empty_set_expr).unwrap_or(false);
                if is_empty {
                    // := {} — clear the junction row
                    multi_link_clears.push(IrMultiLinkClear {
                        junction_table: jt,
                        module,
                        source_col: src_col,
                    });
                } else if let Some(expr) = &el.compexpr {
                    multi_link_clears.push(IrMultiLinkClear {
                        junction_table: jt.clone(),
                        module: module.clone(),
                        source_col: src_col.clone(),
                    });
                    let values = self.compile_multilink_values(expr, td, &alias, through_td)?;
                    multi_link_replaces.push(IrMultiLinkMutation {
                        junction_table: jt,
                        module,
                        source_col: src_col,
                        target_col: tgt_col,
                        values,
                        single: true,
                    });
                }
            } else {
                scalar_elements.push(el.clone());
            }
        }

        let assignments = self.compile_assignments_for_update(&scalar_elements, td, &alias)?;
        // See the insert's own: rewrites apply in the table's `BEFORE` trigger.
        let rewrites = vec![];
        let returning = Self::pk_returning(td);

        let (poly_implementors, poly_columns) = if self.is_polymorphic(td) {
            (
                self.find_poly_implementors(&format!("{}::{}", td.module, td.name)),
                Self::poly_dml_columns(td),
            )
        } else {
            (vec![], vec![])
        };

        // Only enqueue indexes whose source pointers are touched by this update.
        let written_cols: std::collections::HashSet<&str> = assignments.iter().map(|(c, _)| c.as_str()).collect();
        let type_name = format!("{}::{}", td.module, td.name);
        let enqueue_vector: Vec<VectorEnqueueInfo> = td
            .vector_indexes
            .iter()
            .filter(|vi| vi.pointers.iter().any(|f| written_cols.contains(f.as_str())))
            .map(|vi| VectorEnqueueInfo {
                type_name: type_name.clone(),
                index_name: vi.index_name.clone(),
            })
            .collect();
        let enqueue_search = collect_search_enqueue(td, &type_name, "index");
        // Nested-DML CTEs (see IrUpdate::nested_ctes) compose with every
        // other UPDATE shape — multi-link mutation, interface-type fan-out,
        // and vector/search enqueue each have their own emitter branch
        // (emit_update_stmt / emit_poly_update_stmt) that now prepends
        // these CTEs and adds the FROM clause a hoisted CTE reference needs.
        let nested_ctes = std::mem::replace(&mut self.pending_nested_ctes, outer_pending_nested_ctes);

        Ok(IrUpdate {
            target,
            filter,
            assignments,
            rewrites,
            returning,
            multi_link_clears,
            multi_link_replaces,
            multi_link_appends,
            multi_link_removals,
            poly_implementors,
            poly_columns,
            enqueue_vector,
            enqueue_search,
            nested_ctes,
        })
    }

    /// Extract junction table info for a multi-link (or a junction-backed
    /// single link, which shares this exact storage shape — D2):
    /// (junction_table, module, source_col, target_col, through_td).
    /// `through_td` is the junction type's own TypeDescriptor for a
    /// `Through[...]` link (needed to validate/compile `@prop := expr`
    /// link-property assignments against its real properties) — `None` for
    /// a Standard (implicit) junction table, which has no user-declared
    /// properties at all.
    fn junction_info_for(
        &mut self,
        td: &TypeDescriptor,
        name: &str,
        target: &str,
        through: &Option<String>,
    ) -> Result<(String, String, String, String, Option<&'a TypeDescriptor>), PyQLError> {
        let (junction_table, module, source_col, target_col, through_td) =
            self.own_junction_info_for(td, name, target, through)?;
        let owner_derived = through_td.is_none_or(|through_td| through_td.junction);
        let junction_table = if owner_derived {
            self.owner_junction(td, name, through_td)
        } else {
            junction_table
        };
        Ok((junction_table, module, source_col, target_col, through_td))
    }

    /// The junction a read of `td`'s multi-link `name` goes through: its own
    /// table, or, when `td` has subtypes, the union of theirs beside it.
    fn owner_junction(&self, td: &TypeDescriptor, name: &str, through_td: Option<&TypeDescriptor>) -> String {
        let own = format!("{}.{}", td.table, name);
        if !self.has_subtypes(td) {
            return own;
        }
        let tables = self
            .find_poly_implementors(&format!("{}::{}", td.module, td.name))
            .into_iter()
            .map(|implementor| (implementor.module, format!("{}.{}", implementor.table, name)))
            .collect::<Vec<_>>();
        let mut columns = vec!["source".to_string(), "target".to_string()];
        if let Some(through_td) = through_td {
            columns.extend(Self::poly_dml_columns(through_td).into_iter().filter(|c| c != "id"));
        }
        super::inherited_junction(&tables, &columns)
    }

    /// `junction_info_for` naming the owner's own junction table, which is
    /// the one a write to that owner's rows goes to.
    fn own_junction_info_for(
        &mut self,
        td: &TypeDescriptor,
        name: &str,
        target: &str,
        through: &Option<String>,
    ) -> Result<(String, String, String, String, Option<&'a TypeDescriptor>), PyQLError> {
        match through {
            None => Ok((
                format!("{}.{}", td.table, name),
                td.module.clone(),
                "source".to_string(),
                "target".to_string(),
                None,
            )),
            Some(through_qname) => {
                let through_td = self.resolve_type(through_qname)?;
                let src_type = format!("{}::{}", td.module, td.name);
                let source_col = through_td
                    .links
                    .iter()
                    .find(|l| l.target == src_type)
                    .map(|l| l.name.clone())
                    .unwrap_or_else(|| "source".to_string());
                // A self-referencing through-link (source type == target
                // type, e.g. Person.friends via a PersonFriend with two
                // Person-typed links) would otherwise match the same link
                // for both sides — prefer a differently-named one first,
                // matching the tie-break already used for the read-side
                // join resolution elsewhere in this file.
                let target_col = through_td
                    .links
                    .iter()
                    .find(|l| l.target == target && l.name != source_col)
                    .or_else(|| through_td.links.iter().find(|l| l.target == target))
                    .map(|l| l.name.clone())
                    .unwrap_or_else(|| "target".to_string());
                // A dedicated `@pylon.junction` type has no physical table
                // of its own — `emit_one_junction_table` always names it
                // `"{owner.table}.{name}"`, one per *owner* (so that e.g.
                // an interface-inherited junction-backed link gets one
                // physically separate table per concrete implementor,
                // never a single table shared — and thus impossibly
                // FK'd — across several). `through_td.table` only holds
                // the right name here by accident, for the common case of
                // exactly one owner ever referencing that junction type
                // (the Python walker pre-renames it for that one owner).
                // A non-junction "through" type, in contrast, *is* a real,
                // independently-queryable object with its own genuine
                // table — `through_td.table` is correct for that case and
                // must stay as-is.
                let (junction_table, junction_module) = if through_td.junction {
                    (format!("{}.{}", td.table, name), td.module.clone())
                } else {
                    (through_td.table.clone(), through_td.module.clone())
                };
                Ok((
                    junction_table,
                    junction_module,
                    source_col,
                    target_col,
                    Some(through_td),
                ))
            }
        }
    }

    fn multilink_junction_info(
        &mut self,
        td: &TypeDescriptor,
        ml: &MultiLinkDescriptor,
    ) -> Result<(String, String, String, String, Option<&'a TypeDescriptor>), PyQLError> {
        self.junction_info_for(td, &ml.name, &ml.target, &ml.through)
    }

    fn own_multilink_junction_info(
        &mut self,
        td: &TypeDescriptor,
        ml: &MultiLinkDescriptor,
    ) -> Result<(String, String, String, String, Option<&'a TypeDescriptor>), PyQLError> {
        self.own_junction_info_for(td, &ml.name, &ml.target, &ml.through)
    }

    fn own_link_junction_info(
        &mut self,
        td: &TypeDescriptor,
        l: &LinkDescriptor,
    ) -> Result<(String, String, String, String, Option<&'a TypeDescriptor>), PyQLError> {
        self.own_junction_info_for(td, &l.name, &l.target, &l.through)
    }

    /// Same as `multilink_junction_info`, for a junction-backed single link.
    fn link_junction_info(
        &mut self,
        td: &TypeDescriptor,
        l: &LinkDescriptor,
    ) -> Result<(String, String, String, String, Option<&'a TypeDescriptor>), PyQLError> {
        self.junction_info_for(td, &l.name, &l.target, &l.through)
    }

    /// Build the `IrMultiLinkJoin` a multi-link or junction-backed single
    /// link's forward read-side join uses (`IrPathJoin::Multi`, a shape's
    /// `IrMultiLinkPointer`, or — for a junction-backed single link — the
    /// junction variant of `IrSingleLinkCorrelation`).
    fn build_multilink_join(
        &mut self,
        td: &TypeDescriptor,
        name: &str,
        target: &str,
        through: &Option<String>,
    ) -> Result<IrMultiLinkJoin, PyQLError> {
        if let Some(through_qname) = through {
            let through_td = self.resolve_type(through_qname)?;
            if through_td.junction {
                // See `junction_info_for`'s doc comment: a dedicated
                // junction type's physical table is always owner-derived
                // (one per concrete implementor), never `through_td.table`
                // itself.
                Ok(IrMultiLinkJoin::Standard {
                    junction_table: self.owner_junction(td, name, Some(through_td)),
                    module: td.module.clone(),
                })
            } else {
                let source_qname = format!("{}::{}", td.module, td.name);
                let source_col = through_td
                    .links
                    .iter()
                    .find(|l| l.target == source_qname)
                    .ok_or_else(|| {
                        PyQLError::Type(PyQLTypeError {
                            message: format!("through type {through_qname} has no link to {source_qname}"),
                            position: Position { line: 0, col: 0 },
                        })
                    })?
                    .name
                    .clone();
                let target_col = through_td
                    .links
                    .iter()
                    .find(|l| l.target == target && l.name != source_col)
                    .or_else(|| through_td.links.iter().find(|l| l.target == target))
                    .ok_or_else(|| {
                        PyQLError::Type(PyQLTypeError {
                            message: format!("through type {through_qname} has no link to target {target}"),
                            position: Position { line: 0, col: 0 },
                        })
                    })?
                    .name
                    .clone();
                Ok(IrMultiLinkJoin::Through {
                    junction_table: through_td.table.clone(),
                    module: through_td.module.clone(),
                    source_col,
                    target_col,
                })
            }
        } else {
            let junction_table = self.owner_junction(td, name, None);
            Ok(IrMultiLinkJoin::Standard {
                junction_table: match self.junction_read_overrides.get(&junction_table) {
                    Some(o) => o.junction.clone(),
                    None => junction_table,
                },
                module: td.module.clone(),
            })
        }
    }

    /// Compile the RHS of a multilink `+=`, `-=`, or `:= expr` into an
    /// `IrMultiLinkValues`. `td`/`alias` are the record being updated (link-
    /// property value expressions like `@weight := <float64>$w` compile
    /// against this scope, same as any other UPDATE SET assignment — they
    /// cannot reference the linked target's own properties, only the outer
    /// record's or bound params/literals). `through_td` is the junction
    /// type's own TypeDescriptor for a `Through[...]` multi-link, or `None`
    /// for a Standard junction (which has no properties to assign).
    fn compile_multilink_values(
        &mut self,
        expr: &Expr,
        td: &'a TypeDescriptor,
        alias: &str,
        through_td: Option<&'a TypeDescriptor>,
    ) -> Result<IrMultiLinkValues, PyQLError> {
        // Same reason as `compile_assignments_inner`: these rows are the
        // junction's target ids, not output, and each value is read as one
        // column.
        self.without_implicit_id(|this| this.compile_multilink_values_inner(expr, td, alias, through_td))
    }

    fn compile_multilink_values_inner(
        &mut self,
        expr: &Expr,
        td: &'a TypeDescriptor,
        alias: &str,
        through_td: Option<&'a TypeDescriptor>,
    ) -> Result<IrMultiLinkValues, PyQLError> {
        // `a union b` — combine both sides; each keeps its own link_props
        // (different targets in one `+=` can carry different property values).
        if let Expr::Union(a, b) = expr {
            let left = self.compile_multilink_values(a, td, alias, through_td)?;
            let right = self.compile_multilink_values(b, td, alias, through_td)?;
            return Ok(IrMultiLinkValues {
                source: IrMultiLinkValueSource::Union(Box::new(left), Box::new(right)),
                link_props: vec![],
            });
        }

        // `emails := (insert …) if exists($email) else {}` — the same choice
        // between two sets the select path reads, and the same rewrite: the
        // insert carries the condition itself, since Postgres runs a
        // data-modifying CTE whether or not anything reads it.
        if matches!(expr, Expr::IfElse(_))
            && let Some(rewritten) = self.object_if_else_as_union(expr)
        {
            return self.compile_multilink_values(&rewritten, td, alias, through_td);
        }

        // `notifications += (select .notifications { @read_at := … } filter …)`
        // — the link properties sit *inside* the select. Lifted out, the shape
        // branch below assigns them and the bare select goes down the
        // relative-path branch, which is what each already knows how to do.
        if let Expr::SubQuery(inner) = expr
            && let Stmt::Select(sel) = inner.as_ref()
            && let Expr::Shape(sh) = &sel.result
            && !sh.elements.is_empty()
            && sh
                .elements
                .iter()
                .all(|el| matches!(el.path.steps.as_slice(), [ast::PathStep::LinkProp(_)]))
            && let Some(base) = sh.expr.clone()
        {
            let lifted = Expr::Shape(Box::new(ast::ShapeExpr {
                expr: Some(Expr::SubQuery(Box::new(Stmt::Select(ast::SelectStmt {
                    result: base,
                    ..sel.clone()
                })))),
                elements: sh.elements.clone(),
                marker_offset: sh.marker_offset,
            }));
            return self.compile_multilink_values(&lifted, td, alias, through_td);
        }

        // `expr { @prop := value, ... }` — link-property assignments layered
        // onto an inner target-selecting expression.
        if let Expr::Shape(shape) = expr {
            let inner_expr = shape
                .expr
                .as_ref()
                .ok_or_else(|| self.type_err("multilink value shape must have a base expression"))?;
            let mut inner = self.compile_multilink_values(inner_expr, td, alias, through_td)?;
            // `(select .notifications { @read_at := … @read_at })` — over a
            // walk of a link with properties, `@prop` reads the row's current
            // value off the junction that walk crosses.
            let walked_junction = match (&inner.source, inner_expr) {
                (IrMultiLinkValueSource::PathSelect(ps), Expr::SubQuery(stmt)) => {
                    match (stmt.as_ref(), ps.joins.last()) {
                        (Stmt::Select(sel), Some(IrPathJoin::Multi { junction_alias, .. })) => match &sel.result {
                            Expr::Path(p) if p.partial => match p.steps.as_slice() {
                                [ast::PathStep::Name(link)] => Self::resolve_multilink(td, link)
                                    .and_then(|m| m.through.clone())
                                    .map(|through| (through, junction_alias.clone())),
                                _ => None,
                            },
                            _ => None,
                        },
                        _ => None,
                    }
                }
                _ => None,
            };

            let Some(through) = through_td else {
                return Err(self.type_err(
                    "link properties (`@prop := value`) are only valid on a multi-link \
                     declared with `Through[...]`",
                ));
            };

            for el in &shape.elements {
                let prop_name = match el.path.steps.as_slice() {
                    [ast::PathStep::LinkProp(name)] => name.clone(),
                    _ => return Err(self.type_err("only `@prop := value` link-property assignments are valid here")),
                };
                let prop = Self::resolve_property(through, &prop_name)
                    .ok_or_else(|| self.field_err(&prop_name, &format!("{}::{}", through.module, through.name)))?;
                if prop.is_readonly {
                    return Err(self.type_err(&format!(
                        "cannot set link property '{prop_name}': it is declared as read-only"
                    )));
                }
                let value_expr = el
                    .compexpr
                    .as_ref()
                    .ok_or_else(|| self.type_err(&format!("link property '{prop_name}' must be assigned a value")))?;
                let scoped = walked_junction.is_some();
                if scoped {
                    self.link_prop_scope.push(walked_junction.clone());
                }
                let ir_expr = self.compile_expr(value_expr, td, alias);
                if scoped {
                    self.link_prop_scope.pop();
                }
                inner.link_props.push((prop.name.clone(), ir_expr?));
            }
            return Ok(inner);
        }

        // `prices := assert_distinct(<union>)` — the assert checks the targets
        // before they become junction rows, and passes them through otherwise.
        if let Expr::FunctionCall(f) = expr
            && (f.module.is_none() || f.module.as_deref() == Some("std"))
            && matches!(f.name.as_str(), "assert_exists" | "assert_distinct")
            && let [arg] = f.args.as_slice()
        {
            let arg = arg.clone();
            let inner = self.compile_multilink_values(&arg, td, alias, through_td)?;
            // The ids travel through the check as a plain array and come back
            // unnested, which leaves no row for a per-target link property to
            // ride along on.
            let mut props = vec![];
            crate::sql::collect_link_prop_names(&inner, &mut props);
            if !props.is_empty() {
                return Err(self.type_err(&format!(
                    "'{}' cannot be applied to a link that carries link properties ({}) —                      the check reads the targets alone",
                    f.name,
                    props.join(", "),
                )));
            }
            let message = self.assert_message(f, Some((td, alias)))?;
            return Ok(IrMultiLinkValues {
                source: IrMultiLinkValueSource::Asserted {
                    fn_name: f.name.clone(),
                    inner: Box::new(inner),
                    message,
                },
                link_props: vec![],
            });
        }

        // `translations := (select { teaser, title })` — a select with no
        // clauses of its own is the expression it wraps, and the forms below
        // already know what to do with that. Left wrapped, a free row source
        // (a set literal, a union) reaches the generic subquery arm and is
        // refused, while the identical unwrapped `{ teaser, title }` compiles.
        if let Expr::SubQuery(inner) = expr
            && let Stmt::Select(sel) = inner.as_ref()
            && sel.filter.is_none()
            && sel.order_by.is_empty()
            && sel.offset.is_none()
            && sel.limit.is_none()
            && matches!(sel.result, Expr::Set(_) | Expr::Union(_, _))
        {
            let result = sel.result.clone();
            return self.compile_multilink_values(&result, td, alias, through_td);
        }

        // CTE reference: bare name matching a registered CTE
        if let Some(name) = self.resolve_cte_name(expr) {
            return Ok(IrMultiLinkValues {
                source: IrMultiLinkValueSource::CteRef(name.to_string()),
                link_props: vec![],
            });
        }

        // `{ a, b }` — a set literal of targets, each contributing its own rows.
        if let Expr::Set(elements) = expr
            && !elements.is_empty()
        {
            let mut combined: Option<IrMultiLinkValues> = None;
            for element in elements {
                let one = self.compile_multilink_values(element, td, alias, through_td)?;
                combined = Some(match combined {
                    None => one,
                    Some(previous) => IrMultiLinkValues {
                        source: IrMultiLinkValueSource::Union(Box::new(previous), Box::new(one)),
                        link_props: vec![],
                    },
                });
            }
            return Ok(combined.expect("elements is non-empty"));
        }

        // `social_accounts := (for p in … union (insert …))` — the loop's rows
        // are the link's targets, read back from the CTE it is hoisted into,
        // the same way a bare nested insert is.
        if let Expr::SubQuery(inner) = expr
            && let Stmt::For(_) = inner.as_ref()
        {
            let (cte_name, _) = self.hoist_dml_as_cte(inner.as_ref())?;
            return Ok(IrMultiLinkValues {
                source: IrMultiLinkValueSource::CteRef(cte_name),
                link_props: vec![],
            });
        }

        // `emails := (insert Email { … })` — a nested insert whose rows become
        // the link's targets, read back from the CTE it is hoisted into.
        if let Expr::SubQuery(inner) = expr
            && matches!(inner.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_))
        {
            let cte_name = self.hoist_nested_dml(inner)?;
            return Ok(IrMultiLinkValues {
                source: IrMultiLinkValueSource::CteRef(cte_name),
                link_props: vec![],
            });
        }

        // `emails := (select .emails filter .primary)` — a relative path here
        // is relative to the row being written, so it is rooted at that type
        // and correlated back to it; compiled bare it has no object to
        // resolve against and reads as a free select.
        if let Expr::SubQuery(inner) = expr
            && let Stmt::Select(sel) = inner.as_ref()
            && let Expr::Path(path) = &sel.result
            && path.partial
        {
            let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
            steps.extend(path.steps.iter().cloned());
            let rooted = ast::Path { steps, partial: false };
            let synthetic = ast::SelectStmt {
                result: Expr::Path(rooted.clone()),
                filter: sel.filter.clone(),
                order_by: sel.order_by.clone(),
                offset: sel.offset.clone(),
                limit: sel.limit.clone(),
                lock: None,
            };
            let mut ps = self.compile_path_select(&synthetic, &rooted, &[], false)?;
            Self::correlate_path_select(&mut ps, alias);
            return Ok(IrMultiLinkValues {
                source: IrMultiLinkValueSource::PathSelect(Box::new(ps)),
                link_props: vec![],
            });
        }

        // Parenthesised subquery
        if let Expr::SubQuery(inner) = expr {
            return match self.compile_stmt(inner)? {
                IrStmt::Select(s) if matches!(s.rows.as_slice(), [IrRowSource::Bound { .. }]) => {
                    Ok(IrMultiLinkValues {
                        source: IrMultiLinkValueSource::Select(Box::new(s)),
                        link_props: vec![],
                    })
                }
                IrStmt::PathSelect(ps) => Ok(IrMultiLinkValues {
                    source: IrMultiLinkValueSource::PathSelect(Box::new(ps)),
                    link_props: vec![],
                }),
                _ => Err(self.type_err("multilink value must resolve to a SELECT or path query")),
            };
        }

        if let Expr::FunctionCall(fc) = expr {
            let synthetic = ast::SelectStmt {
                result: expr.clone(),
                filter: None,
                order_by: vec![],
                offset: None,
                limit: None,
                lock: None,
            };
            if let Some(fs) = self.try_compile_fn_object_select(fc, &[], &synthetic, false)? {
                return Ok(IrMultiLinkValues {
                    source: IrMultiLinkValueSource::Function(Box::new(fs)),
                    link_props: vec![],
                });
            }
        }

        // Absolute path expression (type reference or path traversal)
        if let Expr::Path(p) = expr
            && !p.partial
        {
            let fake_sel = ast::SelectStmt {
                result: expr.clone(),
                filter: None,
                order_by: vec![],
                offset: None,
                limit: None,
                lock: None,
            };
            return match self.compile_stmt(&Stmt::Select(fake_sel))? {
                IrStmt::PathSelect(ps) => Ok(IrMultiLinkValues {
                    source: IrMultiLinkValueSource::PathSelect(Box::new(ps)),
                    link_props: vec![],
                }),
                IrStmt::Select(s) if matches!(s.rows.as_slice(), [IrRowSource::Bound { .. }]) => {
                    Ok(IrMultiLinkValues {
                        source: IrMultiLinkValueSource::Select(Box::new(s)),
                        link_props: vec![],
                    })
                }
                _ => Err(self.type_err("expected a path expression for multilink value")),
            };
        }

        Err(self.type_err("multilink value must be a CTE reference, parenthesised subquery, or type path"))
    }

    // ── DELETE ────────────────────────────────────────────────────────────────────

    fn compile_delete(&mut self, del: &ast::DeleteStmt) -> Result<IrDelete, PyQLError> {
        // Taken before anything nested is compiled, so a nested statement
        // cannot pick up a guard meant for this one.
        let pending_guard = self.pending_delete_guard.take();
        let type_name = self.expr_as_type_name(&del.subject)?;
        // `delete previous` where `previous` is a `with` binding: the binding
        // names the rows to delete, so it decides the table *and* narrows the
        // delete to its own rows — exactly as `compile_update` does. Without
        // the narrowing this would resolve to the type and empty the table.
        let bound_rows = self.cte_object_type(&type_name);
        let td = self.resolve_path_root(&type_name)?;
        let alias = self.fresh_alias();
        let target = IrSource {
            poly: None,
            type_name: format!("{}::{}", td.module, td.name),
            table: td.table.clone(),
            alias: alias.clone(),
        };

        let declared_filter = del
            .filter
            .as_ref()
            .map(|f| self.compile_expr(f, td, &alias))
            .transpose()?;
        let filter = match bound_rows {
            Some(_) => {
                let membership = IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: alias.clone(),
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    },
                    op: ast::BinOpKind::In,
                    right: IrExpr::ArrayFromSelect(Box::new(IrArraySource::Select(IrSelect::schema_bound(
                        IrSource {
                            poly: None,
                            type_name: format!("{}::{}", td.module, td.name),
                            table: format!("@cte:{type_name}"),
                            alias: self.fresh_alias(),
                        },
                        vec![],
                        None,
                    )))),
                }));
                Some(and_conditions(declared_filter, vec![membership]).expect("membership is present"))
            }
            None => declared_filter,
        };
        let filter = match pending_guard {
            Some(condition) => {
                let guard = self.compile_expr(&condition, td, &alias)?;
                and_conditions(filter, vec![guard])
            }
            None => filter,
        };

        let returning = Self::pk_returning(td);

        let (poly_implementors, poly_columns) = if self.is_polymorphic(td) {
            (
                self.find_poly_implementors(&format!("{}::{}", td.module, td.name)),
                Self::poly_dml_columns(td),
            )
        } else {
            (vec![], vec![])
        };
        let qname = format!("{}::{}", td.module, td.name);
        let enqueue_search = collect_search_enqueue(td, &qname, "delete");

        Ok(IrDelete {
            target,
            filter,
            returning,
            poly_implementors,
            poly_columns,
            enqueue_search,
        })
    }

    // ── Shape compilation ─────────────────────────────────────────────────────────

    fn compile_shape(
        &mut self,
        elements: &[ShapeElement],
        td: &TypeDescriptor,
        alias: &str,
        module: &str,
    ) -> Result<Vec<IrShapePointer>, PyQLError> {
        if elements.is_empty() {
            // No explicit shape: implicit { id } only.
            return Ok(Self::pk_returning(td));
        }

        let mut pointers = vec![];
        for el in elements {
            if let Some(splat) = &el.splat {
                // Check if this is a type-intersection splat: [is Type].*
                if let Some(ast::PathStep::TypeIntersection(type_ref)) = el.path.steps.first() {
                    let type_ref = type_ref.clone();
                    pointers.extend(self.compile_type_intersection_splat(&type_ref, splat, td, alias)?);
                } else {
                    pointers.extend(self.compile_splat(splat, td, alias, module)?);
                }
            } else {
                pointers.push(self.compile_shape_element(el, td, alias, module)?);
            }
        }
        self.prepend_implicit_id(&mut pointers, td);
        Ok(pointers)
    }

    /// Put `id` at the front of a shape that did not select one, as Gel's
    /// `_get_shape_configuration_inner` does for every binary-protocol query
    /// (`gel-python` asks for it unconditionally, so every query jaldis ever
    /// ran against Gel had it). Without it, `o.id` on a shape like
    /// `options: { value }` reads as unset rather than as the row's id.
    ///
    /// Skipped wherever Gel skips it: inside a mutation's own body and under
    /// a cast to `json` — see `implicit_id_in_shapes`. A shape that names `id`
    /// itself keeps its own pointer, and its position, untouched.
    fn prepend_implicit_id(&self, pointers: &mut Vec<IrShapePointer>, td: &TypeDescriptor) {
        if !self.implicit_id_in_shapes {
            return;
        }
        let Some(pk) = td.properties.iter().find(|p| p.is_pk) else {
            return;
        };
        if pointers.iter().any(|p| p.alias() == pk.name) {
            return;
        }
        pointers.insert(
            0,
            IrShapePointer::Scalar(IrScalarPointer {
                implicit_id: true,
                marker_offset: None,
                alias: pk.name.clone(),
                column: pk.name.clone(),
                pg_type: pk.pg_type.clone(),
                tuple_shape: None,
            }),
        );
    }

    /// Run `body` with implicit ids suppressed, restoring the previous setting
    /// however it ends — Gel spells this `with ctx.new(): bodyctx
    /// .implicit_id_in_shapes = False` around the same constructs.
    fn without_implicit_id<T>(&mut self, body: impl FnOnce(&mut Self) -> Result<T, PyQLError>) -> Result<T, PyQLError> {
        let saved = std::mem::replace(&mut self.implicit_id_in_shapes, false);
        let result = body(self);
        self.implicit_id_in_shapes = saved;
        result
    }

    /// Expand `*` → all scalars; `**` → all scalars + all single links with implicit `{ id }`.
    fn compile_splat(
        &mut self,
        splat: &ast::Splat,
        td: &TypeDescriptor,
        alias: &str,
        module: &str,
    ) -> Result<Vec<IrShapePointer>, PyQLError> {
        let mut pointers: Vec<IrShapePointer> = td
            .properties
            .iter()
            .map(|p| {
                IrShapePointer::Scalar(IrScalarPointer {
                    implicit_id: false,
                    marker_offset: None,
                    alias: p.name.clone(),
                    column: p.name.clone(),
                    pg_type: p.pg_type.clone(),
                    tuple_shape: self.resolve_property_tuple_shape(p),
                })
            })
            .collect();

        for cd in &td.computed.clone() {
            // `*` is properties; links arrive only with `**`. A computed
            // standing for objects is a link however it is written, so it
            // waits for the deep form too.
            if matches!(splat, ast::Splat::Shallow) && self.computed_is_object_valued(cd, td) {
                continue;
            }
            pointers.push(self.compile_declared_computed(cd, td, alias, module, None, &[])?);
        }

        if matches!(splat, ast::Splat::Deep) {
            for l in &td.links {
                let target_td = self.resolve_type(&l.target)?;
                let sub_alias = self.fresh_alias();
                // `**` fetches every property (not further nested links) of
                // a linked object — a `Shallow` (`*`) expansion of the
                // target type, one level deep. Recursing with `Deep` here
                // instead would walk the target's own links too, which for
                // a two-way or cyclic link graph never terminates.
                let target_module = target_td.module.clone();
                let sub_shape = self.compile_splat(&ast::Splat::Shallow, target_td, &sub_alias, &target_module)?;
                let subquery = IrSelect::schema_bound(
                    IrSource {
                        poly: self.link_target_fanout(target_td),
                        type_name: format!("{}::{}", target_td.module, target_td.name),
                        table: target_td.table.clone(),
                        alias: sub_alias.clone(),
                    },
                    sub_shape,
                    None,
                );
                let correlation = if l.is_junction_backed() {
                    let join = self.build_multilink_join(td, &l.name, &l.target, &l.through)?;
                    IrSingleLinkCorrelation::Junction {
                        join,
                        target_pk: "id".to_string(),
                    }
                } else {
                    IrSingleLinkCorrelation::Fk {
                        fk_column: format!("{}_id", l.name),
                        target_pk: "id".to_string(),
                    }
                };
                pointers.push(IrShapePointer::SingleLink(IrSingleLinkPointer {
                    marker_offset: None,
                    alias: l.name.clone(),
                    correlation,
                    subquery,
                    link_properties: vec![],
                }));
            }

            for ml in &td.multilinks {
                let sub_alias = self.fresh_alias();
                let target_td = self.resolve_type(&ml.target)?;
                // See the single-link loop above — same Shallow-not-Deep
                // reasoning applies to multilink targets.
                let target_module = target_td.module.clone();
                let sub_shape = self.compile_splat(&ast::Splat::Shallow, target_td, &sub_alias, &target_module)?;

                let join = if let Some(through_qname) = &ml.through {
                    let through_td = self.resolve_type(through_qname)?;
                    if through_td.junction {
                        // See `junction_info_for`'s doc comment: owner-derived.
                        IrMultiLinkJoin::Standard {
                            junction_table: self.owner_junction(td, &ml.name, Some(through_td)),
                            module: td.module.clone(),
                        }
                    } else {
                        let source_qname = format!("{}::{}", td.module, td.name);
                        let source_col = through_td
                            .links
                            .iter()
                            .find(|l| l.target == source_qname)
                            .ok_or_else(|| {
                                PyQLError::Type(PyQLTypeError {
                                    message: format!(
                                        "through type {through_qname} has no link to source type {source_qname}"
                                    ),
                                    position: Position { line: 0, col: 0 },
                                })
                            })?
                            .name
                            .clone();
                        let target_col = through_td
                            .links
                            .iter()
                            .find(|l| l.target == ml.target && l.name != source_col)
                            .or_else(|| through_td.links.iter().find(|l| l.target == ml.target))
                            .ok_or_else(|| {
                                PyQLError::Type(PyQLTypeError {
                                    message: format!(
                                        "through type {through_qname} has no link to target type {}",
                                        ml.target
                                    ),
                                    position: Position { line: 0, col: 0 },
                                })
                            })?
                            .name
                            .clone();
                        IrMultiLinkJoin::Through {
                            junction_table: through_td.table.clone(),
                            module: through_td.module.clone(),
                            source_col,
                            target_col,
                        }
                    }
                } else {
                    // See `junction_info_for`: the junction table is named
                    // after the owner and lives in the owner's schema, which a
                    // splat reaching in from another module is not.
                    IrMultiLinkJoin::Standard {
                        junction_table: self.owner_junction(td, &ml.name, None),
                        module: td.module.clone(),
                    }
                };

                let subquery = self.link_target_select(
                    target_td,
                    IrSource {
                        poly: None,
                        type_name: format!("{}::{}", target_td.module, target_td.name),
                        table: target_td.table.clone(),
                        alias: sub_alias.clone(),
                    },
                    sub_shape,
                );

                let link_properties = self.splat_link_properties(ml)?;
                pointers.push(IrShapePointer::MultiLink(IrMultiLinkPointer {
                    marker_offset: None,
                    alias: ml.name.clone(),
                    join,
                    subquery,
                    link_properties,
                    single: false,
                }));
            }
        }

        Ok(pointers)
    }

    /// The link properties a splat over a multi-link's targets carries: every
    /// property of its `@pylon.junction` through type, as Gel's splat does.
    fn splat_link_properties(&self, ml: &MultiLinkDescriptor) -> Result<Vec<IrLinkProp>, PyQLError> {
        let Some(through_qname) = &ml.through else {
            return Ok(vec![]);
        };
        let through_td = self.resolve_type(through_qname)?;
        if !through_td.junction {
            return Ok(vec![]);
        }
        Ok(through_td
            .properties
            .iter()
            .filter(|p| p.name != "id")
            .map(|p| IrLinkProp { name: p.name.clone() })
            .collect())
    }

    // ── Type-intersection helpers ─────────────────────────────────────────────────

    /// Expand `[is ConcreteType].*` → scalar subqueries for each non-inherited property.
    fn compile_type_intersection_splat(
        &mut self,
        type_ref: &ast::ObjectRef,
        splat: &ast::Splat,
        parent_td: &TypeDescriptor,
        parent_alias: &str,
    ) -> Result<Vec<IrShapePointer>, PyQLError> {
        let type_name = match &type_ref.module {
            Some(m) => format!("{}::{}", m, type_ref.name),
            None => type_ref.name.clone(),
        };
        let concrete_td = self.resolve_type(&type_name)?;
        let concrete_qname = format!("{}::{}", concrete_td.module, concrete_td.name);
        let concrete_table = concrete_td.table.clone();

        // Interface properties: those in the parent (interface) td
        let interface_props: std::collections::HashSet<String> =
            parent_td.properties.iter().map(|p| p.name.clone()).collect();

        // Emit scalar subquery for each property not already in the interface
        let props: Vec<_> = concrete_td
            .properties
            .iter()
            .filter(|p| !interface_props.contains(&p.name))
            .cloned()
            .collect();

        // Same for computed pointers not already defined on the interface —
        // `[is Concrete].*` must include the concrete type's own computed
        // properties (e.g. `full_name`), not just its stored properties.
        let interface_computed: std::collections::HashSet<String> =
            parent_td.computed.iter().map(|c| c.name.clone()).collect();
        let computed: Vec<_> = concrete_td
            .computed
            .iter()
            .filter(|c| !interface_computed.contains(&c.name))
            .filter(|c| !matches!(splat, ast::Splat::Shallow) || !self.computed_is_object_valued(c, concrete_td))
            .cloned()
            .collect();

        // For deep splat, also include links
        let links: Vec<_> = if matches!(splat, ast::Splat::Deep) {
            concrete_td.links.to_vec()
        } else {
            vec![]
        };

        let mut pointers = vec![];
        for prop in props {
            let sub_alias = self.fresh_alias();
            let filter = IrExpr::BinOp(Box::new(IrBinOp {
                left: IrExpr::ColumnRef {
                    alias: sub_alias.clone(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
                op: ast::BinOpKind::Eq,
                right: IrExpr::ColumnRef {
                    alias: parent_alias.to_string(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
            }));
            let subquery = IrSelect::schema_bound(
                IrSource {
                    poly: None,
                    type_name: concrete_qname.clone(),
                    table: concrete_table.clone(),
                    alias: sub_alias,
                },
                vec![IrShapePointer::Scalar(IrScalarPointer {
                    implicit_id: false,
                    marker_offset: None,
                    alias: prop.name.clone(),
                    column: prop.name.clone(),
                    pg_type: prop.pg_type.clone(),
                    tuple_shape: self.resolve_property_tuple_shape(&prop),
                })],
                Some(filter),
            );
            pointers.push(IrShapePointer::Computed(IrComputedPointer {
                marker_offset: None,
                alias: prop.name.clone(),
                expr: IrExpr::Subquery(Box::new(subquery)),
            }));
        }

        for cd in computed {
            let sub_alias = self.fresh_alias();
            let filter = IrExpr::BinOp(Box::new(IrBinOp {
                left: IrExpr::ColumnRef {
                    alias: sub_alias.clone(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
                op: ast::BinOpKind::Eq,
                right: IrExpr::ColumnRef {
                    alias: parent_alias.to_string(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
            }));
            let expr_ast = crate::parse::parse_pointer_expr(&cd.expression).map_err(PyQLError::Syntax)?;
            let inner_ir = self.compile_expr(&expr_ast, concrete_td, &sub_alias)?;
            let subquery = IrSelect::schema_bound(
                IrSource {
                    poly: None,
                    type_name: concrete_qname.clone(),
                    table: concrete_table.clone(),
                    alias: sub_alias,
                },
                vec![IrShapePointer::Computed(IrComputedPointer {
                    marker_offset: None,
                    alias: cd.name.clone(),
                    expr: inner_ir,
                })],
                Some(filter),
            );
            pointers.push(IrShapePointer::Computed(IrComputedPointer {
                marker_offset: None,
                alias: cd.name.clone(),
                expr: IrExpr::Subquery(Box::new(subquery)),
            }));
        }

        // For deep splat, include single-link pointers as subqueries
        for link in links {
            let target_td = self.resolve_type(&link.target)?;
            let sub_alias = self.fresh_alias();
            let filter = if link.is_junction_backed() {
                let (jt_table, jt_module, jt_src_col, jt_tgt_col, _) =
                    self.junction_info_for(concrete_td, &link.name, &link.target, &link.through)?;
                let jt_alias = self.fresh_alias();
                let jt_filter = IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::BinOp(Box::new(IrBinOp {
                        left: IrExpr::ColumnRef {
                            alias: jt_alias.clone(),
                            column: jt_src_col,
                            pg_type: "uuid".to_string(),
                        },
                        op: ast::BinOpKind::Eq,
                        right: IrExpr::ColumnRef {
                            alias: parent_alias.to_string(),
                            column: "id".to_string(),
                            pg_type: "uuid".to_string(),
                        },
                    })),
                    op: ast::BinOpKind::And,
                    right: IrExpr::BinOp(Box::new(IrBinOp {
                        left: IrExpr::ColumnRef {
                            alias: jt_alias.clone(),
                            column: jt_tgt_col,
                            pg_type: "uuid".to_string(),
                        },
                        op: ast::BinOpKind::Eq,
                        right: IrExpr::ColumnRef {
                            alias: sub_alias.clone(),
                            column: "id".to_string(),
                            pg_type: "uuid".to_string(),
                        },
                    })),
                }));
                let exists_select = IrSelect::schema_bound(
                    IrSource {
                        poly: None,
                        type_name: format!("{}::__jt__", jt_module),
                        table: jt_table,
                        alias: jt_alias,
                    },
                    vec![],
                    Some(jt_filter),
                );
                IrExpr::UnaryOp(Box::new(IrUnaryOp {
                    op: ast::UnaryOpKind::Exists,
                    operand: IrExpr::Subquery(Box::new(exists_select)),
                }))
            } else {
                IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: sub_alias.clone(),
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    },
                    op: ast::BinOpKind::Eq,
                    right: IrExpr::ColumnRef {
                        alias: parent_alias.to_string(),
                        column: format!("{}_id", link.name),
                        pg_type: "uuid".to_string(),
                    },
                }))
            };
            let sub_shape = Self::pk_returning(target_td);
            let subquery = IrSelect::schema_bound(
                IrSource {
                    poly: self.link_target_fanout(target_td),
                    type_name: format!("{}::{}", target_td.module, target_td.name),
                    table: target_td.table.clone(),
                    alias: sub_alias,
                },
                sub_shape,
                Some(filter),
            );
            pointers.push(IrShapePointer::Computed(IrComputedPointer {
                marker_offset: None,
                alias: link.name.clone(),
                expr: IrExpr::Subquery(Box::new(subquery)),
            }));
        }

        Ok(pointers)
    }

    /// Compile `[is ConcreteType].pointer_name` → `IrShapePointer`.
    fn compile_type_intersection_pointer(
        &mut self,
        type_ref: &ast::ObjectRef,
        tail_steps: &[ast::PathStep],
        parent_alias: &str,
        marker_offset: Option<usize>,
    ) -> Result<IrShapePointer, PyQLError> {
        let expr = self.compile_type_intersection_expr_steps(type_ref, tail_steps, parent_alias)?;
        // Alias is the last Name step
        let alias = match tail_steps.last() {
            Some(ast::PathStep::Name(n)) => n.clone(),
            _ => return Err(self.type_err("type intersection must end with a pointer name")),
        };
        Ok(IrShapePointer::Computed(IrComputedPointer {
            alias,
            expr,
            marker_offset,
        }))
    }

    /// Compile `[is Type].name` as an `IrExpr` (for computed pointer / expression context).
    fn compile_type_intersection_expr(
        &mut self,
        steps: &[ast::PathStep],
        td: &TypeDescriptor,
        parent_alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        use ast::PathStep;
        let type_ref = match steps.first() {
            Some(PathStep::TypeIntersection(tr)) => tr.clone(),
            _ => return Err(self.type_err("expected type intersection")),
        };
        // The fast path reads one stored column off the narrowed type.
        // Anything else — a computed, a link, further traversal — falls
        // through to the general builder, rooted at the narrowed type
        // (whose rows share the interface row's id).
        match self.compile_type_intersection_expr_steps(&type_ref, &steps[1..], parent_alias) {
            Ok(ir) => Ok(ir),
            Err(fast_path_err) => {
                let p = ast::Path {
                    steps: steps.to_vec(),
                    partial: true,
                };
                self.compile_partial_path_as_subquery(&p, td, parent_alias)
                    .map_err(|_| fast_path_err)
            }
        }
    }

    /// Shared: build scalar subquery for `[is ConcreteType]` + tail pointer steps.
    fn compile_type_intersection_expr_steps(
        &mut self,
        type_ref: &ast::ObjectRef,
        tail_steps: &[ast::PathStep],
        parent_alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        use ast::PathStep;
        let type_name = match &type_ref.module {
            Some(m) => format!("{}::{}", m, type_ref.name),
            None => type_ref.name.clone(),
        };
        let concrete_td = self.resolve_type(&type_name)?;
        let concrete_qname = format!("{}::{}", concrete_td.module, concrete_td.name);
        let concrete_table = concrete_td.table.clone();

        let pointer_name = match tail_steps.first() {
            Some(PathStep::Name(n)) => n.as_str(),
            _ => return Err(self.type_err("type intersection must be followed by a pointer name, e.g. [is Type].name")),
        };

        let prop = concrete_td
            .properties
            .iter()
            .find(|p| p.name == pointer_name)
            .ok_or_else(|| self.field_err(pointer_name, &concrete_qname))?;
        let prop_name = prop.name.clone();
        let prop_type = prop.pg_type.clone();

        let sub_alias = self.fresh_alias();
        let filter = IrExpr::BinOp(Box::new(IrBinOp {
            left: IrExpr::ColumnRef {
                alias: sub_alias.clone(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
            op: ast::BinOpKind::Eq,
            right: IrExpr::ColumnRef {
                alias: parent_alias.to_string(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
        }));

        let poly = self.poly_fanout_for(&concrete_qname);
        Ok(IrExpr::Subquery(Box::new(IrSelect::schema_bound(
            IrSource {
                poly,
                type_name: concrete_qname,
                table: concrete_table,
                alias: sub_alias,
            },
            vec![IrShapePointer::Scalar(IrScalarPointer {
                implicit_id: false,
                marker_offset: None,
                alias: prop_name.clone(),
                column: prop_name,
                pg_type: prop_type,
                tuple_shape: self.resolve_property_tuple_shape(prop),
            })],
            Some(filter),
        ))))
    }

    fn compile_shape_element(
        &mut self,
        el: &ShapeElement,
        td: &TypeDescriptor,
        alias: &str,
        module: &str,
    ) -> Result<IrShapePointer, PyQLError> {
        // Type intersection pointer: [is Type].pointer_name (without compexpr)
        if let Some(ast::PathStep::TypeIntersection(type_ref)) = el.path.steps.first()
            && el.compexpr.is_none()
            && el.path.steps.len() >= 2
        {
            // `[is T].configs: { … }` — a shape says the pointer is read as
            // objects, which the scalar route below cannot give: it resolves
            // a stored property and nothing else.
            if let Some(nested) = el.nested.as_deref()
                && !nested.is_empty()
                && let Some(ast::PathStep::Name(leaf)) = el.path.steps.last()
                && let Some(ptr) = self.try_compile_pointer_expr(
                    &leaf.clone(),
                    &Expr::Path(el.path.clone()),
                    td,
                    alias,
                    module,
                    el.marker_offset,
                    nested,
                )?
            {
                return Ok(ptr);
            }
            let type_ref = type_ref.clone();
            return self.compile_type_intersection_pointer(&type_ref, &el.path.steps[1..], alias, el.marker_offset);
        }

        let pointer_name = path_leaf(&el.path)?;

        // __type__ is a virtual property: the fully-qualified type name as a string.
        // It's always injected at position 0 for internal use; explicit inclusion adds
        // it as a regular computed pointer at a later position so Python can read it.
        if pointer_name == "__type__" && el.compexpr.is_none() {
            let expr = if self.is_polymorphic(td) {
                IrExpr::ColumnRef {
                    alias: alias.to_string(),
                    column: "__type__".to_string(),
                    pg_type: "text".to_string(),
                }
            } else {
                IrExpr::Literal(IrLiteral::Str(format!("{}::{}", td.module, td.name)))
            };
            return Ok(IrShapePointer::Computed(IrComputedPointer {
                marker_offset: el.marker_offset,
                alias: "__type__".to_string(),
                expr,
            }));
        }

        // `p := assert_exists(.prices { … })` — the assert is a check on the
        // pointer's own set, not part of a value expression, so the pointer is
        // compiled from the argument and the check reads the rows it
        // aggregates. Taken as an expression instead, an object-valued
        // argument is "part of a larger expression", which is exactly what an
        // object-returning function refuses.
        if let Some(compexpr) = &el.compexpr
            && let Some((call, value_expr, check_expr)) =
                Self::asserted_pointer_expr(compexpr, el.nested.as_deref().unwrap_or(&[]))
        {
            let element_for = |expr: Expr| ShapeElement {
                compexpr: Some(expr),
                nested: None,
                ..el.clone()
            };
            // Compiled speculatively: a scalar argument's assert is an ordinary
            // function call and belongs on the expression path below, and an
            // argument that does not compile at all should report its own error
            // from there rather than this one.
            if let Ok(ptr) = self.compile_shape_element(&element_for(value_expr), td, alias, module)
                && ptr.is_object_pointer()
            {
                let check = match check_expr {
                    Some(expr) => Some(self.compile_shape_element(&element_for(expr), td, alias, module)?),
                    None => None,
                };
                let message = self.assert_message(&call, Some((td, alias)))?;
                return Ok(IrShapePointer::Asserted(Box::new(IrAssertedPointer {
                    fn_name: call.name,
                    inner: ptr,
                    check,
                    message,
                })));
            }
        }

        // `t := (select .teams limit 1) if cond else {}` — one branch names
        // objects and the other nothing, so the pointer is that branch with
        // the condition folded into its own filter.
        if let Some(compexpr) = &el.compexpr
            && let Some(guarded) = guarded_object_branch(compexpr)
        {
            let element = ShapeElement {
                compexpr: Some(guarded),
                ..el.clone()
            };
            return self.compile_shape_element(&element, td, alias, module);
        }

        // Computed override: `pointer := expr`
        if let Some(compexpr) = &el.compexpr {
            // A link-valued RHS (`.multilink`, `.<backlink[is T] { … }`,
            // `(select .link filter … limit 1)`) is a pointer in its own
            // right, not an expression — see `try_compile_pointer_expr`.
            // `(select .resource { rev := … }) { changed_at := .rev.created_at }`
            // — a shape written at the point of use replaces the one the
            // subject carries, so whatever that one declared has to stay in
            // scope or the replacement cannot read it.
            let inner_declared: Vec<ShapeElement> = Self::replaced_subject_shape(compexpr)
                .iter()
                .filter(|e| e.compexpr.is_some())
                .cloned()
                .collect();
            let restore = (!inner_declared.is_empty()).then(|| {
                let mut scope = self.active_declared_pointers.clone();
                scope.extend(inner_declared);
                std::mem::replace(&mut self.active_declared_pointers, scope)
            });
            let pointer = self.try_compile_pointer_expr(
                pointer_name,
                compexpr,
                td,
                alias,
                module,
                el.marker_offset,
                el.nested.as_deref().unwrap_or(&[]),
            );
            if let Some(previous) = restore {
                self.active_declared_pointers = previous;
            }
            if let Some(ptr) = pointer? {
                return Ok(ptr);
            }
            // `p := marketplace::retrieve_listing_prices(.id) { amount }` — an
            // object-returning call written inline. A declared computed with
            // the same body already takes this route; a shape written on it
            // belongs to the rows it yields.
            if let Some((fc, call_nested)) = Self::object_call_with_shape(compexpr, el.nested.as_deref())
                && let Some(fs) = self.compile_fn_object_source(fc, &call_nested)?
            {
                return Ok(IrShapePointer::Computed(IrComputedPointer {
                    marker_offset: el.marker_offset,
                    alias: pointer_name.to_string(),
                    expr: IrExpr::ArrayFromSelect(Box::new(IrArraySource::ObjectFunction(Box::new(fs)))),
                }));
            }
            let ir = self.compile_expr(compexpr, td, alias)?;
            // Cross-scope TypeIs: promote to set-valued shape pointer.
            if let IrExpr::ArrayFromSelect(src) = ir {
                if let IrArraySource::RawExpr {
                    source,
                    poly_implementors,
                    poly_columns,
                    expr,
                } = *src
                {
                    return Ok(IrShapePointer::ScalarSet(IrScalarSetPointer {
                        alias: pointer_name.to_string(),
                        source,
                        poly_implementors,
                        poly_columns,
                        bool_expr: expr,
                    }));
                }
                return Ok(IrShapePointer::Computed(IrComputedPointer {
                    marker_offset: el.marker_offset,
                    alias: pointer_name.to_string(),
                    expr: IrExpr::ArrayFromSelect(src),
                }));
            }
            return Ok(IrShapePointer::Computed(IrComputedPointer {
                marker_offset: el.marker_offset,
                alias: pointer_name.to_string(),
                expr: ir,
            }));
        }

        // Scalar property
        if let Some(p) = Self::resolve_property(td, pointer_name) {
            return Ok(IrShapePointer::Scalar(IrScalarPointer {
                implicit_id: false,
                marker_offset: el.marker_offset,
                alias: pointer_name.to_string(),
                column: p.name.clone(),
                pg_type: p.pg_type.clone(),
                tuple_shape: self.resolve_property_tuple_shape(p),
            }));
        }

        // Single link
        if let Some(l) = Self::resolve_link(td, pointer_name) {
            let target_td = self.resolve_type(&l.target)?;
            let sub_alias = self.fresh_alias();
            let nested_elements = el.nested.as_deref().unwrap_or(&[]);

            // A junction-backed link can carry `@prop` read references
            // (e.g. `spouse: { name, @since }`), the same as a multi-link's
            // own nested shape (`compile_multilink_pointer`) — partition
            // those out before compiling the rest as a regular shape.
            let (regular_els, link_properties): (Vec<ShapeElement>, Vec<IrLinkProp>) = if l.is_junction_backed() {
                let mut regular = Vec::new();
                let mut props = Vec::new();
                for nel in nested_elements {
                    if let [ast::PathStep::LinkProp(name)] = nel.path.steps.as_slice() {
                        props.push(IrLinkProp { name: name.clone() });
                    } else {
                        regular.push(nel.clone());
                    }
                }
                (regular, props)
            } else {
                (nested_elements.to_vec(), vec![])
            };

            let sub_shape = self.compile_shape(&regular_els, target_td, &sub_alias, &target_td.module.clone())?;
            let subquery = self.link_target_select(
                target_td,
                IrSource {
                    poly: None,
                    type_name: format!("{}::{}", target_td.module, target_td.name),
                    table: target_td.table.clone(),
                    alias: sub_alias,
                },
                sub_shape,
            );
            let correlation = if l.is_junction_backed() {
                let join = self.build_multilink_join(td, &l.name, &l.target, &l.through)?;
                IrSingleLinkCorrelation::Junction {
                    join,
                    target_pk: "id".to_string(),
                }
            } else {
                IrSingleLinkCorrelation::Fk {
                    fk_column: format!("{}_id", l.name),
                    target_pk: "id".to_string(),
                }
            };
            return Ok(IrShapePointer::SingleLink(IrSingleLinkPointer {
                marker_offset: el.marker_offset,
                alias: pointer_name.to_string(),
                correlation,
                subquery,
                link_properties,
            }));
        }

        // Multi-link
        if Self::resolve_multilink(td, pointer_name).is_some() {
            return self.compile_multilink_pointer(pointer_name, pointer_name, td, alias, module, el);
        }

        // Schema-defined computed pointer
        if let Some(cd) = self.resolve_computed(td, pointer_name) {
            return self.compile_declared_computed(
                &cd,
                td,
                alias,
                module,
                el.marker_offset,
                el.nested.as_deref().unwrap_or(&[]),
            );
        }

        // Declared by the binding this shape is read off, rather than by the
        // type — compiled against the binding's own row, as it was written.
        if let Some(declared) = self
            .active_declared_pointers
            .iter()
            .find(|d| path_leaf(&d.path).is_ok_and(|n| n == pointer_name))
            .cloned()
            && let Some(expr) = declared.compexpr.clone()
        {
            let nested = if el.nested.as_deref().unwrap_or(&[]).is_empty() {
                declared.nested.clone().unwrap_or_default()
            } else {
                el.nested.clone().unwrap_or_default()
            };
            return self.compile_computed_expr(pointer_name, &expr, td, alias, module, el.marker_offset, &nested, None);
        }

        Err(self.field_err(pointer_name, &format!("{}::{}", td.module, td.name)))
    }

    /// A computed pointer whose path walks *through* a multi-valued step before
    /// landing on objects — `members := .memberships.member`.
    ///
    /// Rooted at the enclosing type and correlated back to the enclosing row,
    /// exactly as `compile_partial_path_as_subquery` does for a value, then
    /// aggregated so the rows survive as rows.
    #[allow(clippy::too_many_arguments)]
    fn compile_chained_link_pointer(
        &mut self,
        pointer_name: &str,
        path: &ast::Path,
        td: &TypeDescriptor,
        alias: &str,
        nested: &[ShapeElement],
        modifiers: Option<&ast::SelectStmt>,
        multi: bool,
        tail: usize,
    ) -> Result<IrShapePointer, PyQLError> {
        let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
        steps.extend(path.steps.iter().cloned());
        let full_path = ast::Path { steps, partial: false };
        let synthetic = ast::SelectStmt {
            result: Expr::Path(full_path.clone()),
            filter: modifiers.and_then(|m| m.filter.clone()),
            order_by: modifiers.map(|m| m.order_by.clone()).unwrap_or_default(),
            offset: modifiers.and_then(|m| m.offset.clone()),
            limit: modifiers.and_then(|m| m.limit.clone()),
            lock: None,
        };
        let mut path_select = self.compile_path_select_with_tail(&synthetic, &full_path, nested, false, tail)?;
        Self::correlate_path_select(&mut path_select, alias);
        // A walk that crosses a multi step stands for a set, so it is
        // aggregated; one that cannot is a single object and is read as one,
        // rather than an array of length one.
        let expr = if multi {
            IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(path_select))))
        } else {
            IrExpr::ObjectPathSubquery(Box::new(path_select))
        };
        Ok(IrShapePointer::Computed(IrComputedPointer {
            marker_offset: None,
            alias: pointer_name.to_string(),
            expr,
        }))
    }

    fn compile_multilink_pointer(
        &mut self,
        output_alias: &str,
        ml_name: &str,
        td: &TypeDescriptor,
        _parent_alias: &str,
        module: &str,
        el: &ShapeElement,
    ) -> Result<IrShapePointer, PyQLError> {
        let ml = Self::resolve_multilink(td, ml_name)
            .expect("caller verified multilink exists")
            .clone();
        let target_td = self.resolve_type(&ml.target)?;
        let sub_alias = self.fresh_alias();
        let nested_elements = el.nested.as_deref().unwrap_or(&[]);

        // Partition @prop link-property elements from regular shape elements.
        let mut link_properties: Vec<IrLinkProp> = Vec::new();
        let mut regular_els: Vec<ShapeElement> = Vec::new();
        for nel in nested_elements {
            if let [ast::PathStep::LinkProp(name)] = nel.path.steps.as_slice() {
                link_properties.push(IrLinkProp { name: name.clone() });
            } else {
                regular_els.push(nel.clone());
            }
        }
        let has_splat = nested_elements.iter().any(|nel| {
            nel.splat.is_some() && !matches!(nel.path.steps.first(), Some(ast::PathStep::TypeIntersection(_)))
        });
        if has_splat {
            for prop in self.splat_link_properties(&ml)? {
                if !link_properties.iter().any(|existing| existing.name == prop.name) {
                    link_properties.push(prop);
                }
            }
        }

        let sub_shape = self.compile_shape(&regular_els, target_td, &sub_alias, &target_td.module.clone())?;

        let join = if let Some(through_qname) = &ml.through {
            let through_td = self.resolve_type(through_qname)?;
            if through_td.junction {
                // Junction type: columns are always named `source` and
                // `target`. See `junction_info_for`'s doc comment: the
                // physical table is owner-derived, never `through_td.table`.
                IrMultiLinkJoin::Standard {
                    junction_table: self.owner_junction(td, ml_name, Some(through_td)),
                    module: td.module.clone(),
                }
            } else {
                let source_qname = format!("{}::{}", td.module, td.name);
                let source_col = through_td
                    .links
                    .iter()
                    .find(|l| l.target == source_qname)
                    .ok_or_else(|| {
                        PyQLError::Type(PyQLTypeError {
                            message: format!("through type {through_qname} has no link to source type {source_qname}"),
                            position: Position { line: 0, col: 0 },
                        })
                    })?
                    .name
                    .clone();
                let target_col = through_td
                    .links
                    .iter()
                    .find(|l| l.target == ml.target && l.name != source_col)
                    .or_else(|| through_td.links.iter().find(|l| l.target == ml.target))
                    .ok_or_else(|| {
                        PyQLError::Type(PyQLTypeError {
                            message: format!("through type {through_qname} has no link to target type {}", ml.target),
                            position: Position { line: 0, col: 0 },
                        })
                    })?
                    .name
                    .clone();
                IrMultiLinkJoin::Through {
                    junction_table: through_td.table.clone(),
                    module: through_td.module.clone(),
                    source_col,
                    target_col,
                }
            }
        } else {
            IrMultiLinkJoin::Standard {
                junction_table: self.owner_junction(td, ml_name, None),
                module: module.to_string(),
            }
        };

        // `@prop` in this link's own modifiers reads the junction row, so
        // the through type has to be in scope while they compile.
        self.link_prop_scope
            .push(ml.through.clone().map(|t| (t, "jt".to_string())));
        let modifiers = (|c: &mut Self| -> Result<SelectModifiers, PyQLError> {
            Ok((
                el.filter
                    .as_ref()
                    .map(|f| c.compile_expr(f, target_td, &sub_alias))
                    .transpose()?,
                el.order_by
                    .iter()
                    .map(|s| c.compile_sort(s, target_td, &sub_alias))
                    .collect::<Result<_, _>>()?,
                el.offset
                    .as_ref()
                    .map(|e| c.compile_expr(e, target_td, &sub_alias))
                    .transpose()?,
                el.limit
                    .as_ref()
                    .map(|e| c.compile_expr(e, target_td, &sub_alias))
                    .transpose()?,
            ))
        })(self);
        self.link_prop_scope.pop();
        let (filter, order_by, offset, limit) = modifiers?;
        let subquery = IrSelect {
            rows: vec![IrRowSource::Bound {
                source: IrSource {
                    poly: self.link_target_fanout(target_td),
                    type_name: format!("{}::{}", target_td.module, target_td.name),
                    table: target_td.table.clone(),
                    alias: sub_alias.clone(),
                },
                shape: sub_shape,
            }],
            filter,
            order_by,
            offset,
            limit,
            distinct: false,
            dml_source: None,
            polymorphic: false,
            poly_implementors: vec![],
            poly_columns: vec![],
            lock: None,
        };

        Ok(IrShapePointer::MultiLink(IrMultiLinkPointer {
            marker_offset: el.marker_offset,
            alias: output_alias.to_string(),
            join,
            subquery,
            link_properties,
            single: false,
        }))
    }

    /// Compile `pointer := .<backlink_name[is OwnerType] { shape }` (a
    /// backlink used as a computed pointer inside another type's shape —
    /// the missing piece that made backlinks unusable for anything beyond
    /// `filter exists .<...>`). Mirrors `compile_multilink_pointer`'s
    /// shape/subquery construction, but the owner type's rows are
    /// correlated in reverse: via their own FK column for a single-link
    /// backlink source (`IrMultiLinkJoin::BacklinkFk`), or via the same
    /// junction table a forward multi-link would use with the owner/current
    /// column roles swapped (`IrMultiLinkJoin::BacklinkJunction`).
    fn compile_backlink_pointer(
        &mut self,
        output_alias: &str,
        path: &ast::Path,
        current_qname: &str,
        nested_elements: &[ShapeElement],
        marker_offset: Option<usize>,
        modifiers: Option<&ast::SelectStmt>,
    ) -> Result<IrShapePointer, PyQLError> {
        use ast::PathStep;

        let backlink_name = match path.steps.first() {
            Some(PathStep::Backlink(n)) => n.clone(),
            _ => return Err(self.type_err("internal: expected backlink step")),
        };
        let type_ref = match path.steps.get(1) {
            Some(PathStep::TypeIntersection(tr)) => tr,
            _ => {
                return Err(PyQLError::Type(PyQLTypeError {
                    message: format!(
                        "backlink '.< {backlink_name}' requires a type intersection, \
                     e.g.: .< {backlink_name}[is SomeType]"
                    ),
                    position: Position { line: 0, col: 0 },
                }));
            }
        };
        if path.steps.len() > 2 {
            return Err(self.type_err(
                "further path traversal after a backlink shape is not yet supported \
                 (e.g. '.<link[is Type].property') — attach a nested shape instead: \
                 '.<link[is Type] { property }'",
            ));
        }

        let type_name = match &type_ref.module {
            Some(m) => format!("{}::{}", m, type_ref.name),
            None => type_ref.name.clone(),
        };
        let owner_td = self.backlink_owner(self.resolve_type(&type_name)?, &backlink_name, current_qname)?;
        let owner_qname = format!("{}::{}", owner_td.module, owner_td.name);

        let join = if let Some(l) = owner_td
            .links
            .iter()
            .find(|l| l.name == backlink_name && self.link_target_reaches(&l.target, current_qname))
        {
            if l.is_junction_backed() {
                let (junction_table, module, owner_col, current_col, _) = self.link_junction_info(owner_td, l)?;
                IrMultiLinkJoin::BacklinkJunction {
                    junction_table,
                    module,
                    owner_col,
                    current_col,
                }
            } else {
                IrMultiLinkJoin::BacklinkFk {
                    fk_col: format!("{}_id", backlink_name),
                }
            }
        } else if let Some(ml) = owner_td
            .multilinks
            .iter()
            .find(|ml| ml.name == backlink_name && self.link_target_reaches(&ml.target, current_qname))
            .cloned()
        {
            let (junction_table, module, _, _, _) = self.multilink_junction_info(owner_td, &ml)?;
            IrMultiLinkJoin::BacklinkJunction {
                junction_table,
                module,
                owner_col: "source".to_string(),
                current_col: "target".to_string(),
            }
        } else {
            return Err(PyQLError::Type(PyQLTypeError {
                message: format!(
                    "type {} has no link or multi-link '{}' pointing to {}",
                    owner_qname, backlink_name, current_qname,
                ),
                position: Position { line: 0, col: 0 },
            }));
        };

        let sub_alias = self.fresh_alias();
        let sub_shape = self.compile_shape(nested_elements, owner_td, &sub_alias, &owner_td.module.clone())?;

        // The `pointer := expr` grammar (`parse_shape_element`'s `:=`
        // branch) never parses trailing FILTER/ORDER BY/OFFSET/LIMIT after
        // the RHS expression — those per-link modifiers only exist on the
        // separate no-`:=` "bare inclusion with nested shape" parse path
        // that `compile_multilink_pointer`'s other call site reads
        // `el.filter` etc. from. Writing the RHS as a sub-select
        // (`pointer := (select .<link[is T] { … } filter … limit 1)`) is the
        // way to get them here, and `modifiers` carries that inner select.
        let (filter, order_by, offset, limit) = match modifiers {
            Some(sel) => self.compile_path_modifiers(sel, owner_td, &sub_alias)?,
            None => (None, vec![], None, None),
        };
        let subquery = IrSelect {
            rows: vec![IrRowSource::Bound {
                source: IrSource {
                    poly: self.poly_fanout_for(&owner_qname),
                    type_name: owner_qname,
                    table: owner_td.table.clone(),
                    alias: sub_alias.clone(),
                },
                shape: sub_shape,
            }],
            filter,
            order_by,
            offset,
            limit,
            distinct: false,
            dml_source: None,
            polymorphic: false,
            poly_implementors: vec![],
            poly_columns: vec![],
            lock: None,
        };

        Ok(IrShapePointer::MultiLink(IrMultiLinkPointer {
            alias: output_alias.to_string(),
            join,
            subquery,
            link_properties: vec![],
            marker_offset,
            single: self.backlink_is_single(owner_td, &backlink_name, current_qname) || limits_to_one(modifiers),
        }))
    }

    /// Compile a pointer the *schema* declares as computed (as opposed to one
    /// written inline in the query). A declared computed whose expression is
    /// a sub-select over a link — `(select .emails filter .primary limit 1)`
    /// — is an object pointer, exactly as if it had been written inline, so
    /// it takes the same route; everything else is a scalar expression.
    /// An object-returning function call as a row source, with the shape the
    /// pointer asked for (its target's own pk when none was written).
    fn compile_fn_object_source(
        &mut self,
        fc: &ast::FunctionCall,
        nested: &[ShapeElement],
    ) -> Result<Option<IrFunctionSelect>, PyQLError> {
        let Some(fd) = self.schema.functions.iter().find(|f| {
            let module_matches = fc.module.as_deref().map(|m| m == f.module.as_str()).unwrap_or(true);
            module_matches && f.name == fc.name && f.return_is_object
        }) else {
            return Ok(None);
        };
        let (fn_module, fn_name, return_type_name) = (fd.module.clone(), fd.name.clone(), fd.return_pg_type.clone());
        let return_td = self.resolve_type(&return_type_name)?;
        let alias = self.fresh_alias();
        let shape = if nested.is_empty() {
            Self::pk_returning(return_td)
        } else {
            self.compile_shape(nested, return_td, &alias, &return_td.module)?
        };
        let mut args = fc
            .args
            .iter()
            .map(|a| self.compile_free_expr(a))
            .collect::<Result<Vec<_>, _>>()?;
        // A function reading a session global takes them as its first
        // argument — the same forwarding a select over the call gets.
        if let Some(globals) = self.globals_arg_for_call(&format!("{fn_module}::{fn_name}"))? {
            args.insert(0, globals);
        }
        Ok(Some(IrFunctionSelect {
            fn_module,
            fn_name,
            fn_args: args,
            alias,
            type_name: format!("{}::{}", return_td.module, return_td.name),
            polymorphic: false,
            poly_implementors: vec![],
            poly_columns: vec![],
            shape,
            filter: None,
            order_by: vec![],
            offset: None,
            limit: None,
            distinct: false,
        }))
    }

    /// `assert_exists(x)`, `assert_exists(x { … })`, `assert_distinct(x) { … }`
    /// — the assert, the set it checks, and the shape to read that set with.
    ///
    /// Only the one-argument forms, and not `assert_single`: the message
    /// overload takes a second argument the wrapper would have to carry, and
    /// `assert_single` returns the element rather than the array, so it does
    /// not fit the check `IrShapePointer::Asserted` emits.
    fn asserted_pointer_expr(expr: &Expr, nested: &[ShapeElement]) -> Option<(ast::FunctionCall, Expr, Option<Expr>)> {
        // `(select assert_distinct(X) { … } limit 1)` — the assert is the
        // select's subject, so it sees the whole set, while the modifiers
        // narrow only what is read back. The two coincide unless a limit or
        // offset is written, and then the check needs its own copy without
        // them, or it would be asserting over the one row that survives.
        // `(select assert_exists(X)) { … }` — the shape after the select is
        // the one its subject passes through.
        if let Expr::Shape(sh) = expr
            && let Some(subquery @ Expr::SubQuery(_)) = sh.expr.as_ref()
        {
            return Self::asserted_pointer_expr(subquery, &sh.elements);
        }
        if let Expr::SubQuery(stmt) = expr
            && let Stmt::Select(sel) = stmt.as_ref()
        {
            let (call, inner, _) = Self::asserted_pointer_expr(&sel.result, nested)?;
            let rebuild = |offset: Option<Expr>, limit: Option<Expr>| {
                Expr::SubQuery(Box::new(Stmt::Select(ast::SelectStmt {
                    result: inner.clone(),
                    filter: sel.filter.clone(),
                    order_by: sel.order_by.clone(),
                    offset,
                    limit,
                    lock: sel.lock.clone(),
                })))
            };
            let value = rebuild(sel.offset.clone(), sel.limit.clone());
            let check = (sel.offset.is_some() || sel.limit.is_some()).then(|| rebuild(None, None));
            return Some((call, value, check));
        }
        // A shape written after the call (`assert_distinct(f(.id)) { amount }`)
        // belongs to the set the assert passes through, so it becomes the
        // inner pointer's shape.
        let (call, nested) = match expr {
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(Expr::FunctionCall(f)) => (f, sh.elements.clone()),
                _ => return None,
            },
            Expr::FunctionCall(f) => (f, nested.to_vec()),
            _ => return None,
        };
        if call.module.is_some() && call.module.as_deref() != Some("std") {
            return None;
        }
        if !matches!(call.name.as_str(), "assert_exists" | "assert_distinct") {
            return None;
        }
        let [arg] = call.args.as_slice() else {
            return None;
        };
        // A shape written after the call belongs to the set the assert passes
        // through, so it is folded onto the argument rather than left as the
        // element's nested shape: a union only reads as objects when the shape
        // sits directly on it.
        let inner = match (&arg, nested.is_empty()) {
            (Expr::Shape(_), _) | (_, true) => arg.clone(),
            _ => Expr::Shape(Box::new(ast::ShapeExpr {
                expr: Some(arg.clone()),
                elements: nested.clone(),
                marker_offset: None,
            })),
        };
        Some((call.clone(), inner, None))
    }

    /// A function call written as a pointer's value, with the shape its rows
    /// are read through — whether that shape sits after the call
    /// (`f(.id) { amount }`) or was parsed as the element's nested shape.
    fn object_call_with_shape<'e>(
        expr: &'e Expr,
        nested: Option<&[ShapeElement]>,
    ) -> Option<(&'e ast::FunctionCall, Vec<ShapeElement>)> {
        match expr {
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(Expr::FunctionCall(f)) => Some((f, sh.elements.clone())),
                _ => None,
            },
            Expr::FunctionCall(f) => Some((f, nested.unwrap_or(&[]).to_vec())),
            _ => None,
        }
    }

    fn compile_declared_computed(
        &mut self,
        cd: &crate::schema::ComputedDescriptor,
        td: &TypeDescriptor,
        alias: &str,
        module: &str,
        marker_offset: Option<usize>,
        nested: &[ShapeElement],
    ) -> Result<IrShapePointer, PyQLError> {
        let expr_ast = crate::parse::parse_pointer_expr(&cd.expression).map_err(PyQLError::Syntax)?;
        let declared_on = self.computed_declared_on(td, &cd.name);
        self.compile_computed_expr(
            &cd.name,
            &expr_ast,
            td,
            alias,
            module,
            marker_offset,
            nested,
            declared_on,
        )
    }

    /// The ancestor `td` inherited computed `name` from, nearest first, or
    /// `None` when `td` declares it itself. See `SelectAnchor::declared_on`.
    fn computed_declared_on(&self, td: &TypeDescriptor, name: &str) -> Option<(String, String)> {
        td.bases
            .iter()
            .chain(td.parents.iter())
            .chain(td.interfaces.iter())
            .filter_map(|qualified| self.resolve_type(qualified).ok())
            .find(|ancestor| ancestor.computed.iter().any(|c| c.name == name))
            .map(|ancestor| (ancestor.name.clone(), format!("{}::{}", ancestor.module, ancestor.name)))
    }

    /// The body of `compile_declared_computed`, for a pointer whose expression
    /// is already parsed — a `with` binding's own shape declares one that way.
    #[allow(clippy::too_many_arguments)]
    fn compile_computed_expr(
        &mut self,
        name: &str,
        expr_ast: &Expr,
        td: &TypeDescriptor,
        alias: &str,
        module: &str,
        marker_offset: Option<usize>,
        nested: &[ShapeElement],
        declared_on: Option<(String, String)>,
    ) -> Result<IrShapePointer, PyQLError> {
        // The object the pointer is computed on stays in scope for the whole
        // expression, including any part of it compiled without a type in
        // hand — a `with` binding's right-hand side, say.
        self.anchors.push(SelectAnchor {
            type_name: td.name.clone(),
            qualified: format!("{}::{}", td.module, td.name),
            alias: alias.to_string(),
            detached: false,
            declared_on,
        });
        let result = (|compiler: &mut Self| -> Result<IrShapePointer, PyQLError> {
            if let Some(ptr) =
                compiler.try_compile_pointer_expr(name, expr_ast, td, alias, module, marker_offset, nested)?
            {
                return Ok(ptr);
            }
            // `manifest := retrieve_connector_manifest(.id)` — a computed whose
            // expression is an object-returning call. The rows it yields are
            // the pointer's objects; read as a plain expression the call is
            // "part of a larger expression", which such a function refuses.
            if let Expr::FunctionCall(fc) = expr_ast
                && let Some(fs) = compiler.compile_fn_object_source(fc, nested)?
            {
                return Ok(IrShapePointer::Computed(IrComputedPointer {
                    marker_offset,
                    alias: name.to_string(),
                    expr: IrExpr::ArrayFromSelect(Box::new(IrArraySource::ObjectFunction(Box::new(fs)))),
                }));
            }
            let ir = compiler.compile_expr(expr_ast, td, alias)?;
            Ok(IrShapePointer::Computed(IrComputedPointer {
                marker_offset,
                alias: name.to_string(),
                expr: ir,
            }))
        })(self);
        self.anchors.pop();
        result
    }

    /// Split a sub-select's result into the path it traverses and the nested
    /// shape attached to it: `select .posts { title }` → `.posts` + `{ title }`,
    /// `select .posts` → `.posts` + no shape.
    fn split_path_result(result: &Expr) -> Option<(&ast::Path, &[ShapeElement])> {
        match result {
            Expr::Path(p) => Some((p, &[])),
            // `(select detached T filter … limit 1).field` — the marker says
            // the set is not correlated with the enclosing one, which is
            // already true of a subject named by its own type.
            Expr::Detached(inner) => Self::split_path_result(inner),
            Expr::Shape(sh) => match &sh.expr {
                Some(Expr::Path(p)) => Some((p, sh.elements.as_slice())),
                _ => None,
            },
            _ => None,
        }
    }

    /// Peel a computed pointer's right-hand side down to the function call
    /// it names and the sub-select's modifiers, if that is its shape:
    /// `latest(.id)` / `(select latest(.id) filter …)`.
    fn function_subject(e: &Expr) -> Option<(&ast::FunctionCall, Option<&ast::SelectStmt>)> {
        match e {
            Expr::FunctionCall(fc) => Some((fc, None)),
            Expr::SubQuery(stmt) => match stmt.as_ref() {
                Stmt::Select(sel) => match &sel.result {
                    Expr::FunctionCall(fc) => Some((fc, Some(sel))),
                    _ => None,
                },
                _ => None,
            },
            _ => None,
        }
    }

    /// The object-returning user function `fc` names, if any.
    fn resolve_object_fn(&self, fc: &ast::FunctionCall) -> Option<&'a FunctionDescriptor> {
        self.schema.functions.iter().find(|f| {
            let module_matches = fc.module.as_deref().map(|m| m == f.module.as_str()).unwrap_or(true);
            module_matches && f.name == fc.name && f.return_is_object
        })
    }

    /// The shape a pointer's subject carried, when a shape written at the
    /// point of use replaced it: `(select .resource { rev := … }) { … }`.
    /// `pointer_subject` drops it, but its declarations are what the
    /// replacement reads `.rev` from.
    fn replaced_subject_shape(e: &Expr) -> &[ShapeElement] {
        let Expr::Shape(sh) = e else { return &[] };
        if sh.elements.is_empty() {
            return &[];
        }
        match sh.expr.as_ref() {
            Some(inner) => Self::pointer_subject(inner).map(|(_, nested, _)| nested).unwrap_or(&[]),
            None => &[],
        }
    }

    /// Peel a computed pointer's right-hand side down to the path it names,
    /// the shape attached to it, and the sub-select carrying its modifiers
    /// (if any): `.posts` / `.posts { title }` / `(select .posts limit 1)` /
    /// `(select .posts { title } limit 1)` / `(select .posts limit 1) { title }`.
    fn pointer_subject(e: &Expr) -> Option<(&ast::Path, &[ShapeElement], Option<&ast::SelectStmt>)> {
        match e {
            Expr::Path(p) => Some((p, &[], None)),
            Expr::SubQuery(stmt) => match stmt.as_ref() {
                Stmt::Select(sel) => {
                    let (p, inner) = Self::split_path_result(&sel.result)?;
                    Some((p, inner, Some(sel)))
                }
                _ => None,
            },
            Expr::Shape(sh) => {
                let (path, inner, modifiers) = Self::pointer_subject(sh.expr.as_ref()?)?;
                let nested = if sh.elements.is_empty() {
                    inner
                } else {
                    sh.elements.as_slice()
                };
                Some((path, nested, modifiers))
            }
            _ => None,
        }
    }

    /// `((select .parents filter … limit 1)).parent` — a computed whose value
    /// is a field access off its own sub-select. Rewritten as the select over
    /// the extended path, plus how many steps the field access contributed:
    /// the modifiers belong to the step *before* them, which is what a walk's
    /// `tail` pins them to.
    fn field_access_over_select(expr: &Expr) -> Option<(ast::SelectStmt, usize)> {
        let (root, fields) = Self::peel_field_access_chain(expr);
        if fields.is_empty() {
            return None;
        }
        let Expr::SubQuery(stmt) = root else { return None };
        let Stmt::Select(sel) = stmt.as_ref() else {
            return None;
        };
        let Expr::Path(path) = &sel.result else { return None };
        if !path.partial {
            return None;
        }
        let mut steps = path.steps.clone();
        let count = fields.len();
        steps.extend(fields.into_iter().map(ast::PathStep::Name));
        Some((
            ast::SelectStmt {
                result: Expr::Path(ast::Path { steps, partial: true }),
                ..sel.clone()
            },
            count,
        ))
    }

    /// A computed pointer whose right-hand side names a *link* rather than
    /// computing a value — `pointer := .multilink`, `:= .multilink { … }`,
    /// `:= .<backlink[is T] { … }`, and any of those wrapped in a sub-select
    /// carrying FILTER/ORDER BY/OFFSET/LIMIT.
    ///
    /// These are pointers in their own right, so they route to the same
    /// builders a bare `pointer: { … } filter … limit N` inclusion uses and
    /// come back as real object pointers (arrays of hydrated objects) rather
    /// than the bare id or EXISTS boolean that compiling them as an
    /// expression would produce. A sub-select's modifiers are exactly the
    /// per-link modifiers that inclusion form already carries, which is what
    /// makes the re-use exact — the `:=` grammar has no trailing-modifier
    /// form of its own.
    ///
    /// Shared by inline `pointer := …` shape elements and schema-declared
    /// computeds, so both kinds behave identically.
    ///
    /// `Ok(None)` means "not a link-valued RHS": the caller compiles it as
    /// an ordinary expression, which is where `(select …).field` — a scalar
    /// — is handled.
    #[allow(clippy::too_many_arguments)]
    fn try_compile_pointer_expr(
        &mut self,
        pointer_name: &str,
        compexpr: &Expr,
        td: &TypeDescriptor,
        alias: &str,
        module: &str,
        marker_offset: Option<usize>,
        nested_override: &[ShapeElement],
    ) -> Result<Option<IrShapePointer>, PyQLError> {
        // A nested shape can sit inside the parens (`(select .posts
        // { title })`) or after them (`(select .posts) { title }`, `.posts
        // { title }`) — the parser folds a trailing `{ }` into an
        // `Expr::Shape` wrapping whatever precedes it, never into
        // `el.nested` (that field is only populated by the separate no-`:=`
        // "bare inclusion with nested shape" parse path).
        // `((select .history order by … limit 1)).release` — the field access
        // continues the walk, and the modifiers stay on the step they were
        // written on.
        if let Some((sel, tail)) = Self::field_access_over_select(compexpr)
            && let Expr::Path(path) = &sel.result
        {
            let (head_steps, tail_steps) = path.steps.split_at(path.steps.len() - tail);
            let (head_multi, head_target) = self.walk_path_types(td, head_steps, MAX_COMPUTED_SPLICES);
            let Some(head_target) = head_target else {
                return Ok(None);
            };
            let (tail_multi, target) = self.walk_path_types(head_target, tail_steps, MAX_COMPUTED_SPLICES);
            if target.is_none() {
                return Ok(None);
            }
            let multi = tail_multi || (head_multi && !limits_to_one(Some(&sel)));
            if !multi && nested_override.is_empty() {
                return Ok(None);
            }
            let path = path.clone();
            return self
                .compile_chained_link_pointer(pointer_name, &path, td, alias, nested_override, Some(&sel), multi, tail)
                .map(Some);
        }
        let Some((path, declared_nested, modifiers)) = Self::pointer_subject(compexpr) else {
            return Ok(None);
        };
        if !path.partial {
            return Ok(None);
        }
        // A shape written at the point of use (`authors { name }` on a
        // declared computed) wins over the one the declaration itself
        // carries, which acts as the default.
        let nested = if nested_override.is_empty() {
            declared_nested
        } else {
            nested_override
        };

        // Only a link pointer of the current type becomes an object pointer;
        // a property (`x := .name`, `x := (select .name)`) is a scalar and
        // belongs on the expression path.
        let ml_name = match path.steps.as_slice() {
            [ast::PathStep::Name(n)] if Self::resolve_multilink(td, n).is_some() => n.clone(),
            // `.<link[is Owner]` — the objects on the other side of the
            // link. Traversing *past* the intersection (`.<link[is
            // Owner].name`) is a value, not an object pointer, so it goes
            // the expression route instead.
            [ast::PathStep::Backlink(_)] | [ast::PathStep::Backlink(_), ast::PathStep::TypeIntersection(_)] => {
                let current_qname = format!("{}::{}", td.module, td.name);
                let path = path.clone();
                let nested = nested.to_vec();
                return self
                    .compile_backlink_pointer(pointer_name, &path, &current_qname, &nested, marker_offset, modifiers)
                    .map(Some);
            }
            // `.memberships.member` — a chain no single-step builder can
            // express: the junction it would need belongs to no one link but
            // to the whole walk. Compiled as a path select and aggregated, so
            // it stays an object pointer instead of collapsing to the bare ids
            // an expression-position path gives — which, worse, was a scalar
            // subquery that failed outright the moment a second row matched.
            // A leading `[is T]` narrows what the walk starts from
            // (`brand := [is BrandOrderLineItem].brand { * }`); the walk
            // itself is the same one a bare name starts.
            steps
                if matches!(
                    steps.first(),
                    Some(ast::PathStep::Name(_) | ast::PathStep::TypeIntersection(_))
                ) =>
            {
                let (multi, target) = self.walk_path_types(td, steps, MAX_COMPUTED_SPLICES);
                // A single-valued walk takes this route only when a shape was
                // written on it (`account := resource.account { id }`), which
                // is what says an object was meant. Without one, a bare
                // `x := .link` still stands for the link's value, as it did
                // before there was an object route at all.
                if target.is_none() || (!multi && nested.is_empty()) {
                    return Ok(None);
                }
                let path = path.clone();
                let nested = nested.to_vec();
                return self
                    .compile_chained_link_pointer(
                        pointer_name,
                        &path,
                        td,
                        alias,
                        &nested,
                        modifiers,
                        multi && !limits_to_one(modifiers),
                        0,
                    )
                    .map(Some);
            }
            _ => return Ok(None),
        };

        let synthetic = ShapeElement {
            path: path.clone(),
            splat: None,
            nested: Some(nested.to_vec()),
            compexpr: None,
            op: ast::ShapeOp::Assign,
            filter: modifiers.and_then(|s| s.filter.clone()),
            order_by: modifiers.map(|s| s.order_by.clone()).unwrap_or_default(),
            offset: modifiers.and_then(|s| s.offset.clone()),
            limit: modifiers.and_then(|s| s.limit.clone()),
            marker_offset,
        };
        let mut pointer = self.compile_multilink_pointer(pointer_name, &ml_name, td, alias, module, &synthetic)?;
        if let IrShapePointer::MultiLink(link) = &mut pointer {
            link.single = limits_to_one(modifiers);
        }
        Ok(Some(pointer))
    }

    /// A sub-statement used as an expression: `(select .emails filter
    /// .primary limit 1).email`, `(select .posts order by .created desc
    /// limit 1).title`.
    ///
    /// Compiles the inner select as a flat path traversal
    /// (`compile_path_select` — the same builder a top-level `select
    /// Person.company.name` uses, so forward links, multi-links, backlinks,
    /// junction-backed links and type intersections all come along) and
    /// returns it as one correlated scalar subquery.
    ///
    /// A *partial* subject path (`.emails`) is relative to the enclosing
    /// object, so it is rooted at the enclosing type and correlated back to
    /// the enclosing row by primary key; an absolute one (`Person.name`) is
    /// independent and needs no correlation.
    ///
    /// `extra_fields` are the `.field` steps of an enclosing field-access
    /// chain. They are spliced onto the subject path rather than applied to
    /// its result, so the subquery projects the scalar column itself instead
    /// of an opaque object id.
    fn compile_subquery_expr(
        &mut self,
        stmt: &Stmt,
        extra_fields: &[String],
        ctx: Option<(&TypeDescriptor, &str)>,
        outer_shape: &[ShapeElement],
    ) -> Result<IrExpr, PyQLError> {
        // `(with x := … select …)` — the bindings have nowhere to live in
        // expression position, so they're hoisted to the enclosing
        // statement's own WITH clause and the inner statement takes over.
        if let Stmt::With(w) = stmt {
            for alias in &w.aliases {
                if self.bind_inline_if_correlated(&alias.name, &alias.expr, ctx)?
                    || self.bind_group(&alias.name, &alias.expr)?
                {
                    continue;
                }
                // The same computed inlined twice — `select M { * } filter … .role`
                // reaches `Membership.role` from both the splat and the filter —
                // hoists its `with` bindings once per inlining, and two CTEs of
                // one name is "WITH query name specified more than once". The
                // bindings are identical, so the first one stands for both; a
                // *different* binding under a name already taken is a real
                // collision and says so rather than silently shadowing.
                match self.hoisted_binding_sources.get(&alias.name) {
                    Some(existing) if *existing == alias.expr => continue,
                    Some(_) => {
                        return Err(self.type_err(&format!(
                            "two different `with` bindings named '{}' end up in one statement; \
                             rename one of them",
                            alias.name
                        )));
                    }
                    None => {}
                }
                let (ir_stmt, correlated_to) = self.compile_binding_in_scope(&alias.expr)?;
                let sql_name = self.claim_cte_sql_name(&alias.name);
                let type_name = self.register_cte(&alias.name, &ir_stmt);
                self.hoisted_binding_sources
                    .insert(alias.name.clone(), alias.expr.clone());
                self.hoisted_ctes.push(IrCteDef {
                    name: sql_name,
                    stmt: ir_stmt,
                    type_name,
                    correlated_to,
                });
            }
            let inner = (*w.stmt).clone();
            return self.compile_subquery_expr(&inner, extra_fields, ctx, outer_shape);
        }

        if extra_fields.is_empty()
            && let Stmt::Select(sel) = stmt
            && let Expr::Shape(sh) = &sel.result
            && let Some(Expr::SubQuery(subject)) = &sh.expr
            && matches!(subject.as_ref(), Stmt::Group(_))
            && let IrStmt::Group(grp) = self.compile_stmt(stmt)?
        {
            return Ok(IrExpr::ArrayFromSelect(Box::new(IrArraySource::Group(Box::new(grp)))));
        }

        // `(select (.<a[is T] union .<b[is T]) { id } limit 1)` — the union's
        // operands are correlated to the enclosing row, so the whole thing is
        // read as one set rather than hoisted branch by branch.
        if let Stmt::Select(inner) = stmt
            && let Expr::Shape(sh) = &inner.result
            && let Some(subject) = sh.expr.as_ref()
            && let Some(operands) = Self::union_of_relative_paths(subject)
            && let Some((td, alias)) = ctx
        {
            let elements = sh.elements.clone();
            let operands_reach_many = self.relative_paths_reach_many(td, &operands);
            let mut branches = Vec::with_capacity(operands.len());
            for path in operands {
                let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
                steps.extend(path.steps.iter().cloned());
                let rooted = ast::Path { steps, partial: false };
                let synthetic = ast::SelectStmt {
                    result: Expr::Path(rooted.clone()),
                    filter: inner.filter.clone(),
                    order_by: vec![],
                    offset: None,
                    limit: None,
                    lock: None,
                };
                let mut ps = self.compile_path_select(&synthetic, &rooted, &elements, false)?;
                Self::correlate_path_select(&mut ps, alias);
                branches.push(ps);
            }
            let limit = inner
                .limit
                .as_ref()
                .map(|l| self.compile_free_expr(l))
                .transpose()?
                .map(Box::new);
            let multi = !matches!(limit.as_deref(), Some(IrExpr::Literal(IrLiteral::Int(1)))) && operands_reach_many;
            return Ok(IrExpr::ObjectPathUnion { branches, limit, multi });
        }
        // `(insert T { … }).id` — a mutation read through a path. The statement
        // itself may only run at the top level of a WITH, so it is hoisted into
        // one and the path is read back off that binding: exactly what the
        // `with x := (insert …) select x.id` spelling already compiles to. With
        // no path to read there is nothing for the mutation to stand in for,
        // which stays an error.
        // Only in free context. Inside a schema-bound shape element
        // (`select Person { x := (insert Company { … }).name }`) the mutation
        // would run once while every row read its result, which is not what
        // writing it there says — that stays rejected.
        if matches!(stmt, Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_))
            && !extra_fields.is_empty()
            && ctx.is_none()
        {
            let type_name = self.dml_subject_type(stmt)?;
            let inner = self.compile_stmt(stmt)?;
            let cte_name = self.fresh_nested_cte_name();
            // `hoisted_ctes`, not `pending_nested_ctes`: this mutation came out
            // of an expression in the enclosing statement, not out of another
            // statement's link assignment, so it belongs to that statement's
            // own WITH. Registering it is what lets the path below resolve
            // against it like any other binding.
            self.register_cte(&cte_name, &inner);
            self.hoisted_ctes.push(IrCteDef {
                name: cte_name.clone(),
                stmt: inner,
                type_name,
                correlated_to: None,
            });
            let mut steps = vec![ast::PathStep::Name(cte_name)];
            steps.extend(extra_fields.iter().cloned().map(ast::PathStep::Name));
            return self.compile_free_path(&ast::Path { steps, partial: false });
        }

        let Stmt::Select(sel) = stmt else {
            return Err(self.subquery_expr_err(stmt));
        };
        let has_modifiers =
            sel.filter.is_some() || !sel.order_by.is_empty() || sel.offset.is_some() || sel.limit.is_some();

        let Some((path, shape_els)) = Self::split_path_result(&sel.result) else {
            // `(select account::owner(.id) filter … limit 1).name` — the
            // function call is the row source the modifiers apply to.
            if let Expr::FunctionCall(fc) = &sel.result {
                let fc = fc.clone();
                if let Some(ir) = self.try_compile_fn_scalar_subquery(&fc, extra_fields, Some(sel), ctx)? {
                    return Ok(ir);
                }
            }
            // `(select <expression>)` with nothing to traverse is just the
            // expression itself. With modifiers to honour it is a statement,
            // not an expression — `(select count(Visit) filter …)` — so it is
            // hoisted into the enclosing WITH and read back by name.
            if has_modifiers {
                let inner = self.compile_stmt(stmt)?;
                let IrStmt::Select(select) = inner else {
                    return Err(self.subquery_expr_err(stmt));
                };
                if !select
                    .rows
                    .iter()
                    .all(|r| matches!(r, IrRowSource::Free(IrFreeExpr::Scalar(_))))
                {
                    return Err(self.subquery_expr_err(stmt));
                }
                let mut ir = IrExpr::ScalarSubquery(Box::new(select));
                for field in extra_fields {
                    ir = Self::project_free_object_field(ir, field);
                }
                return Ok(ir);
            }
            let mut ir = self.compile_expr_ctx(&sel.result, ctx)?;
            for field in extra_fields {
                ir = Self::project_free_object_field(ir, field);
            }
            return Ok(ir);
        };
        // A shape whose pointers are relative paths declares local names for
        // them, readable by the select's own FILTER/ORDER BY and by whatever
        // projects off it — `(select .locators { handle := [is Handle].handle,
        // latest := [is Handle].latest } filter .latest limit 1).handle`. Each
        // is substituted back into its readers, leaving an ordinary shapeless
        // sub-select behind.
        let rewritten_sel;
        let mut sel = sel;
        let mut shape_els = shape_els;
        let mut extra_steps: Vec<ast::PathStep> = extra_fields.iter().map(|f| ast::PathStep::Name(f.clone())).collect();
        if !shape_els.is_empty()
            && let Some(defs) = Self::shape_alias_paths(shape_els)
        {
            extra_steps = extra_fields
                .iter()
                .flat_map(|field| match defs.iter().find(|(name, _)| name == field) {
                    Some((_, definition)) => definition.steps.clone(),
                    None => vec![ast::PathStep::Name(field.clone())],
                })
                .collect();
            rewritten_sel = ast::SelectStmt {
                result: sel.result.clone(),
                filter: sel.filter.clone().map(|f| Self::substitute_shape_aliases(f, &defs)),
                order_by: sel
                    .order_by
                    .iter()
                    .map(|o| ast::SortExpr {
                        expr: Self::substitute_shape_aliases(o.expr.clone(), &defs),
                        direction: o.direction.clone(),
                        nones: o.nones.clone(),
                    })
                    .collect(),
                offset: sel.offset.clone(),
                limit: sel.limit.clone(),
                lock: sel.lock.clone(),
            };
            sel = &rewritten_sel;
            shape_els = &[];
        }

        // A shape only matters when the sub-select's own value is the
        // result. `(select .emails { address } limit 1).address` projects a
        // column straight back out of it, so the shape says nothing the
        // projection doesn't — the same reading EdgeQL gives it.
        // `answer := (select brand::AssessmentAnswer { … } filter … limit 1)`
        // — a select over a named type, carrying the shape its rows are read
        // with. That is an object, not the bare key the branch below gives a
        // shapeless one, so the shape has somewhere to go after all.
        // `(select names { * })` over an object `with` binding reads the
        // binding's rows the same way.
        if !shape_els.is_empty()
            && extra_fields.is_empty()
            && !path.partial
            && let [ast::PathStep::Name(type_name)] = path.steps.as_slice()
            && let Some(root_td) = match self.cte_object_type(type_name) {
                Some(_) => self.resolve_path_root(type_name).ok(),
                None => self.resolve_type(type_name).ok(),
            }
        {
            let alias = self.fresh_alias();
            let binding = self.cte_object_type(type_name).map(|_| type_name.clone());
            let table = match &binding {
                Some(name) => self.row_source_table(name, root_td),
                None => root_td.table.clone(),
            };
            let outer_declared = binding.as_ref().map(|name| {
                let declared = self.cte_declared_pointers.get(name).cloned().unwrap_or_default();
                std::mem::replace(&mut self.active_declared_pointers, declared)
            });
            let modifiers = self.compile_path_modifiers(sel, root_td, &alias);
            let module = root_td.module.clone();
            let shape = self.compile_shape(shape_els, root_td, &alias, &module);
            if let Some(outer) = outer_declared {
                self.active_declared_pointers = outer;
            }
            let (filter, order_by, offset, limit) = modifiers?;
            let shape = shape?;
            let source = IrSource {
                poly: self.poly_fanout_for(&format!("{}::{}", root_td.module, root_td.name)),
                type_name: format!("{}::{}", root_td.module, root_td.name),
                table,
                alias,
            };
            let single = selects_at_most_one(sel, root_td);
            let mut select = IrSelect::schema_bound(source, shape, filter);
            select.order_by = order_by;
            select.offset = offset;
            select.limit = limit;
            // Read as one object, a select yielding several rows aborts the
            // query ("more than one row returned by a subquery").
            return Ok(if single {
                IrExpr::ObjectSubquery(Box::new(select))
            } else {
                IrExpr::ArrayFromSelect(Box::new(IrArraySource::ObjectSelect(Box::new(select))))
            });
        }

        if !shape_els.is_empty() && extra_fields.is_empty() {
            return Err(self.type_err(
                "a sub-select with a shape is not valid in expression context — \
                 assign it to a computed pointer instead, or project a property \
                 off it, e.g. '(select .emails limit 1).address'",
            ));
        }

        // `(with c := … select c)` — the result is the binding itself, which
        // is a value already, not something to traverse from.
        if !path.partial
            && let [ast::PathStep::Name(name)] = path.steps.as_slice()
            && self.is_value_binding(name)
        {
            let mut ir = self.compile_expr_ctx(&sel.result, ctx)?;
            for field in extra_fields {
                ir = Self::project_free_object_field(ir, field);
            }
            return Ok(ir);
        }

        // `(select Company filter .name = 'Acme' limit 1)` — a bare type
        // select has nothing to traverse; in expression position it stands
        // for the object's primary key, which is what a link's value is.
        if !path.partial
            && extra_fields.is_empty()
            && let [ast::PathStep::Name(type_name)] = path.steps.as_slice()
            && let Ok(root_td) = self.resolve_type(type_name)
        {
            let alias = self.fresh_alias();
            let (filter, order_by, offset, limit) = self.compile_path_modifiers(sel, root_td, &alias)?;
            let source = IrSource {
                poly: None,
                type_name: format!("{}::{}", root_td.module, root_td.name),
                table: root_td.table.clone(),
                alias,
            };
            // Never `pk_returning` here: an empty shape is how the emitter
            // spells an EXISTS inner, so a type with no declared pk would
            // quietly become `SELECT 1` instead of a key.
            let pk = root_td.properties.iter().find(|p| p.is_pk);
            let shape = vec![IrShapePointer::Scalar(IrScalarPointer {
                implicit_id: false,
                marker_offset: None,
                alias: "id".to_string(),
                column: pk.map(|p| p.name.clone()).unwrap_or_else(|| "id".to_string()),
                pg_type: pk.map(|p| p.pg_type.clone()).unwrap_or_else(|| "uuid".to_string()),
                tuple_shape: None,
            })];
            let mut select = IrSelect::schema_bound(source, shape, filter);
            select.order_by = order_by;
            select.offset = offset;
            select.limit = limit;
            return Ok(IrExpr::Subquery(Box::new(select)));
        }

        let mut steps = path.steps.clone();
        let correlate = if path.partial {
            let Some((td, alias)) = ctx else {
                return Err(self.type_err(
                    "a relative path in a sub-select needs an enclosing object — \
                     write the type name explicitly, e.g. '(select Person.name)'",
                ));
            };
            steps.insert(0, ast::PathStep::Name(format!("{}::{}", td.module, td.name)));
            Some(alias.to_string())
        } else {
            None
        };
        steps.extend(extra_steps.iter().cloned());
        let full_path = ast::Path { steps, partial: false };

        let mut ps = self.compile_path_select_with_tail(sel, &full_path, outer_shape, false, extra_steps.len())?;
        if let Some(outer_alias) = correlate {
            Self::correlate_path_select(&mut ps, &outer_alias);
        }
        // A shape written after the projection (`(select … limit 1).account
        // { id, name }`) says the object was wanted, not its id, so the walk
        // comes back as one rather than being reduced the way a bare path in
        // expression position is.
        if !outer_shape.is_empty() && matches!(ps.result, IrPathResult::Object { .. }) {
            return Ok(IrExpr::ObjectPathSubquery(Box::new(ps)));
        }
        // `limit 1` is what makes a sub-select over a multi-link single-
        // valued — that is the whole point of `(select .emails filter
        // .primary limit 1).address`. Any other limit, or none, still stands
        // for a set, so it comes back as an array rather than a subquery
        // Postgres would reject the moment a second row showed up.
        let single = matches!(&sel.limit, Some(Expr::Literal(ast::Literal::Int(1))));
        let multi = match &full_path.steps[0] {
            ast::PathStep::Name(root) => {
                let root_td = self.resolve_path_root(root)?;
                // `(select T filter …).field` reads every `T` the filter
                // keeps, unless it pins an exclusive pointer.
                let every_row_of_a_type = !path.partial
                    && self.cte_object_type(root).is_none()
                    && self.resolve_type(root).is_ok()
                    && !selects_at_most_one(sel, root_td);
                every_row_of_a_type || self.path_crosses_multi(root_td, &full_path.steps[1..])
            }
            _ => false,
        };
        if multi && !single && matches!(ps.result, IrPathResult::Scalar(..)) {
            return Ok(IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(
                ps,
            )))));
        }
        Ok(IrExpr::PathSubquery(Box::new(ps)))
    }

    /// `account::owner(.id).name` and `(select account::owner(.id) filter …
    /// limit 1).name` — an object-returning user function used inside a
    /// larger expression, projected down to one of its return type's
    /// columns.
    ///
    /// The call itself stays object-valued (there is no way to inline a
    /// function that returns a row set), so it becomes the FROM clause of a
    /// scalar subquery and `field` becomes what that subquery selects. Only
    /// a property of the return type can be projected — reaching further
    /// (`fn(x).company.name`) would need joins the function row source has
    /// no way to express.
    ///
    /// `Ok(None)` when `fc` doesn't name an object-returning function, so
    /// the caller can fall through to ordinary function-call resolution.
    fn try_compile_fn_scalar_subquery(
        &mut self,
        fc: &ast::FunctionCall,
        fields: &[String],
        modifiers: Option<&ast::SelectStmt>,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<Option<IrExpr>, PyQLError> {
        let fd = self.schema.functions.iter().find(|f| {
            let module_matches = fc.module.as_deref().map(|m| m == f.module.as_str()).unwrap_or(true);
            module_matches && f.name == fc.name && f.return_is_object
        });
        let Some(fd) = fd else { return Ok(None) };
        let (fn_module, fn_name, return_type_name, polymorphic, params) = (
            fd.module.clone(),
            fd.name.clone(),
            fd.return_pg_type.clone(),
            fd.return_is_polymorphic,
            fd.params.clone(),
        );

        let qualified = format!("{fn_module}::{fn_name}");
        let [field] = fields else {
            return Err(self.type_err(&format!(
                "function '{qualified}' returns objects, so using it inside an expression needs \
                 one of its properties, e.g. '{qualified}(…).name'"
            )));
        };
        if params.len() != fc.args.len() {
            return Err(self.type_err(&format!(
                "function '{qualified}' expects {} argument(s), got {}",
                params.len(),
                fc.args.len()
            )));
        }

        let mut fn_args = fc
            .args
            .iter()
            .map(|a| self.compile_expr_ctx(a, ctx))
            .collect::<Result<Vec<_>, _>>()?;
        if let Some(globals) = self.globals_arg_for_call(&qualified)? {
            fn_args.insert(0, globals);
        }

        let td = self.resolve_type(&return_type_name)?;
        let alias = self.fresh_alias();
        let Some(prop) = Self::resolve_property(td, field) else {
            return Err(self.field_err(field, &return_type_name));
        };
        let projected = IrShapePointer::Computed(IrComputedPointer {
            marker_offset: None,
            alias: field.clone(),
            expr: IrExpr::ColumnRef {
                alias: alias.clone(),
                column: prop.name.clone(),
                pg_type: prop.pg_type.clone(),
            },
        });

        let (poly_implementors, poly_columns) = if polymorphic {
            self.collect_poly_info(&return_type_name)
        } else {
            (vec![], vec![])
        };
        let (filter, order_by, offset, limit) = match modifiers {
            Some(sel) => {
                let td = self.resolve_type(&return_type_name)?;
                self.compile_path_modifiers(sel, td, &alias)?
            }
            None => (None, vec![], None, None),
        };

        Ok(Some(IrExpr::FnSubquery(Box::new(IrFunctionSelect {
            fn_module,
            fn_name,
            fn_args,
            alias,
            type_name: return_type_name,
            polymorphic,
            poly_implementors,
            poly_columns,
            shape: vec![projected],
            filter,
            order_by,
            offset,
            limit,
            distinct: false,
        }))))
    }

    /// Whether a declared computed pointer stands for *objects* rather than a
    /// value — `members := .memberships.member`, `primary_email := (select
    /// .emails filter .primary limit 1)`.
    ///
    /// `*` expands to properties and `**` adds links, so a computed belongs to
    /// whichever side its expression lands on. `ComputedDescriptor` carries no
    /// flag saying which, so the expression has to be walked.
    fn computed_is_object_valued(&self, cd: &crate::schema::ComputedDescriptor, td: &TypeDescriptor) -> bool {
        let Ok(expr) = crate::parse::parse_pointer_expr(&cd.expression) else {
            return false;
        };
        let expr = match Self::field_access_over_select(&expr) {
            Some((sel, _)) => Expr::SubQuery(Box::new(Stmt::Select(sel))),
            None => expr,
        };
        let Some((path, _, _)) = Self::pointer_subject(&expr) else {
            return false;
        };
        if !path.partial {
            return false;
        }
        match path.steps.as_slice() {
            // A backlink names the objects on the other side of the link.
            // Traversing past it (`.<author[is Post].title`) is a value again,
            // which the walk below works out for itself.
            [ast::PathStep::Backlink(_)] | [ast::PathStep::Backlink(_), ast::PathStep::TypeIntersection(_)] => true,
            steps => self.walk_path_types(td, steps, MAX_COMPUTED_SPLICES).1.is_some(),
        }
    }

    /// True when traversing `steps` from `td` crosses a multi-valued step —
    /// a multi-link or a backlink. Such a path stands for a *set*, so in
    /// expression position it has to come back as an array rather than a
    /// scalar subquery (which Postgres would reject at run time the moment a
    /// second row showed up).
    fn path_crosses_multi(&self, td: &TypeDescriptor, steps: &[ast::PathStep]) -> bool {
        self.walk_path_types(td, steps, MAX_COMPUTED_SPLICES).0
    }

    /// One correlated walk per operand of a coalesce of relative paths, each
    /// one filtered to the rows where every operand before it came up empty —
    /// which is what makes the arms, read together, mean what `??` means.
    fn coalesce_path_branches(
        &mut self,
        td: &TypeDescriptor,
        alias: &str,
        operands: &[ast::Path],
        elements: &[ast::ShapeElement],
    ) -> Result<Vec<IrPathSelect>, PyQLError> {
        let mut branches: Vec<IrPathSelect> = Vec::with_capacity(operands.len());
        for path in operands {
            let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
            steps.extend(path.steps.iter().cloned());
            let rooted = ast::Path { steps, partial: false };
            let synthetic = ast::SelectStmt {
                result: Expr::Path(rooted.clone()),
                filter: None,
                order_by: vec![],
                offset: None,
                limit: None,
                lock: None,
            };
            let mut ps = self.compile_path_select(&synthetic, &rooted, elements, false)?;
            Self::correlate_path_select(&mut ps, alias);
            let guards: Vec<IrExpr> = branches
                .iter()
                .map(|earlier| {
                    IrExpr::UnaryOp(Box::new(IrUnaryOp {
                        op: ast::UnaryOpKind::Not,
                        operand: IrExpr::UnaryOp(Box::new(IrUnaryOp {
                            op: ast::UnaryOpKind::Exists,
                            operand: IrExpr::PathSubquery(Box::new(earlier.clone())),
                        })),
                    }))
                })
                .collect();
            if !guards.is_empty() {
                ps.filter = and_conditions(ps.filter, guards);
            }
            branches.push(ps);
        }
        Ok(branches)
    }

    /// Whether a relative path lands on objects rather than on values — its
    /// last named step is a link, a multi-link or a backlink. A coalesce over
    /// values is a choice between two sets of scalars, which the ordinary
    /// binary-operator path already reads as one.
    fn path_lands_on_objects(&self, td: &TypeDescriptor, path: &ast::Path) -> bool {
        let Some(last) = path
            .steps
            .iter()
            .rposition(|step| matches!(step, ast::PathStep::Name(_) | ast::PathStep::Backlink(_)))
        else {
            return false;
        };
        match &path.steps[last] {
            ast::PathStep::Backlink(_) => true,
            ast::PathStep::Name(name) => self
                .walk_path_types(td, &path.steps[..last], MAX_COMPUTED_SPLICES)
                .1
                .is_some_and(|owner| {
                    Self::resolve_multilink(owner, name).is_some() || Self::resolve_link(owner, name).is_some()
                }),
            _ => false,
        }
    }

    /// Whether the operands of a union or coalesce of relative paths reach
    /// more than one object between them. A leading type intersection roots
    /// the walk at the intersected type, as `compile_partial_path_as_subquery`
    /// does, so `[is Loop].condition_configs` is read off `Loop`.
    fn relative_paths_reach_many(&self, td: &TypeDescriptor, operands: &[ast::Path]) -> bool {
        operands.iter().any(|path| {
            let (root_td, rest) = match path.steps.first() {
                Some(ast::PathStep::TypeIntersection(tr)) => {
                    let name = match &tr.module {
                        Some(module) => format!("{}::{}", module, tr.name),
                        None => tr.name.clone(),
                    };
                    match self.resolve_type(&name) {
                        Ok(resolved) => (resolved, &path.steps[1..]),
                        Err(_) => return true,
                    }
                }
                _ => (td, &path.steps[..]),
            };
            self.path_crosses_multi(root_td, rest)
        })
    }

    /// Walk `steps` from `td` without compiling anything, reporting whether
    /// any step is multi-valued and what type the walk ends on. A computed
    /// pointer is expanded into the path it stands for — the same splice
    /// `compile_path_select` performs — so `.published.title` is recognized
    /// as multi-valued when `published` resolves to a multi-link.
    ///
    /// Gives up (`None` target) rather than guessing on anything it can't
    /// resolve; the real compile reports the error.
    fn walk_path_types(
        &self,
        td: &'a TypeDescriptor,
        steps: &[ast::PathStep],
        depth: usize,
    ) -> (bool, Option<&'a TypeDescriptor>) {
        let mut current = td;
        let mut multi = false;
        for (i, step) in steps.iter().enumerate() {
            match step {
                // `.<link[is Owner]` names the owner type; a bare `.<link`
                // spans every type declaring it, so that one lands nowhere in
                // particular.
                ast::PathStep::Backlink(backlink_name) => {
                    let Some(ast::PathStep::TypeIntersection(tr)) = steps.get(i + 1) else {
                        return (true, None);
                    };
                    let owner_name = match &tr.module {
                        Some(m) => format!("{}::{}", m, tr.name),
                        None => tr.name.clone(),
                    };
                    let current_qname = format!("{}::{}", current.module, current.name);
                    let single = self
                        .resolve_type(&owner_name)
                        .is_ok_and(|owner| self.backlink_is_single(owner, backlink_name, &current_qname));
                    multi |= !single;
                    continue;
                }
                ast::PathStep::TypeIntersection(tr) => {
                    let name = match &tr.module {
                        Some(m) => format!("{}::{}", m, tr.name),
                        None => tr.name.clone(),
                    };
                    match self.resolve_type(&name) {
                        Ok(t) => current = t,
                        Err(_) => return (multi, None),
                    }
                }
                ast::PathStep::Name(n) => {
                    if let Some(ml) = Self::resolve_multilink(current, n) {
                        multi = true;
                        match self.resolve_type(&ml.target) {
                            Ok(t) => current = t,
                            Err(_) => return (multi, None),
                        }
                        continue;
                    }
                    if let Some(target) = Self::resolve_link(current, n).map(|l| l.target.clone()) {
                        match self.resolve_type(&target) {
                            Ok(t) => current = t,
                            Err(_) => return (multi, None),
                        }
                        continue;
                    }
                    // A computed pointer stands for its own path, or for the
                    // object-returning function it calls.
                    if depth > 0
                        && let Some(cd) = self.resolve_computed(current, n)
                        && let Ok(expr) = crate::parse::parse_pointer_expr(&cd.expression)
                    {
                        if let Some((p, _, modifiers)) = Self::pointer_subject(&expr)
                            && p.partial
                        {
                            let (m, t) = self.walk_path_types(current, &p.steps, depth - 1);
                            // `limit 1` of its own caps the computed at one
                            // row however many its path crosses.
                            let capped = modifiers
                                .is_some_and(|m| matches!(&m.limit, Some(Expr::Literal(ast::Literal::Int(1)))));
                            multi = multi || (m && !capped);
                            match t {
                                Some(t) => current = t,
                                None => return (multi, None),
                            }
                            continue;
                        }
                        if let Some((fc, _)) = Self::function_subject(&expr)
                            && let Some(fd) = self.resolve_object_fn(fc)
                        {
                            multi = multi || fd.return_is_set;
                            match self.resolve_type(&fd.return_pg_type) {
                                Ok(t) => current = t,
                                Err(_) => return (multi, None),
                            }
                            continue;
                        }
                    }
                    // A property (or something unresolvable): the walk ends.
                    return (multi, None);
                }
                _ => return (multi, None),
            }
        }
        (multi, Some(current))
    }

    /// Compile a relative path that the step-by-step expression rules can't
    /// resolve on their own — deeper than two steps, a computed pointer on a
    /// linked type, anything following a backlink — as a single correlated
    /// subquery over the whole traversal.
    ///
    /// `compile_path_select` already implements the general case (forward
    /// links, multi-links, backlinks, junction-backed links, type
    /// intersections, nested tuple fields, "did you mean" on a typo), so the
    /// work here is only to root the path at the enclosing type and
    /// correlate it back to the enclosing row by primary key.
    ///
    /// A leading type intersection is rooted at the *intersected* type
    /// instead: `[is Concrete].col` has to read from Concrete's own table,
    /// which shares the interface row's id.
    fn compile_partial_path_as_subquery(
        &mut self,
        p: &ast::Path,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        let (root_name, rest) = match p.steps.first() {
            Some(ast::PathStep::TypeIntersection(tr)) => {
                let name = match &tr.module {
                    Some(m) => format!("{}::{}", m, tr.name),
                    None => tr.name.clone(),
                };
                (name, &p.steps[1..])
            }
            _ => (format!("{}::{}", td.module, td.name), &p.steps[..]),
        };
        let root_td = self.resolve_type(&root_name)?;
        let multi = self.path_crosses_multi(root_td, rest);

        let mut steps = vec![ast::PathStep::Name(root_name)];
        steps.extend(rest.iter().cloned());
        let full_path = ast::Path { steps, partial: false };
        let synthetic = ast::SelectStmt {
            result: Expr::Path(full_path.clone()),
            filter: None,
            order_by: vec![],
            offset: None,
            limit: None,
            lock: None,
        };
        let mut ps = self.compile_path_select(&synthetic, &full_path, &[], false)?;
        Self::correlate_path_select(&mut ps, alias);
        if multi && matches!(ps.result, IrPathResult::Scalar(..)) {
            Ok(IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(
                ps,
            )))))
        } else {
            Ok(IrExpr::PathSubquery(Box::new(ps)))
        }
    }

    /// A sub-select written relative to the enclosing object (`(select
    /// .emails filter .primary)`, with or without a shape), as a path select
    /// rooted at that object and correlated back to its row.
    ///
    /// Several places compile a sub-select with no context and so lose the
    /// object a relative path hangs off -- it then resolves in free context
    /// and reports the pointer as unknown. `None` when the statement is not
    /// of that shape, so the caller can carry on as before.
    fn relative_subselect(
        &mut self,
        stmt: &Stmt,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<Option<IrPathSelect>, PyQLError> {
        let (Some((td, alias)), Stmt::Select(sel)) = (ctx, stmt) else {
            return Ok(None);
        };
        let (path, shape): (&ast::Path, &[ShapeElement]) = match &sel.result {
            Expr::Path(p) if p.partial => (p, &[]),
            Expr::Shape(sh) => match sh.expr.as_ref() {
                Some(Expr::Path(p)) if p.partial => (p, sh.elements.as_slice()),
                _ => return Ok(None),
            },
            _ => return Ok(None),
        };
        let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
        steps.extend(path.steps.iter().cloned());
        let rooted = ast::Path { steps, partial: false };
        let synthetic = ast::SelectStmt {
            result: Expr::Path(rooted.clone()),
            filter: sel.filter.clone(),
            order_by: sel.order_by.clone(),
            offset: sel.offset.clone(),
            limit: sel.limit.clone(),
            lock: None,
        };
        let mut ps = self.compile_path_select(&synthetic, &rooted, shape, false)?;
        Self::correlate_path_select(&mut ps, alias);
        Ok(Some(ps))
    }

    /// Tie a path select's root row to the enclosing row by primary key —
    /// what makes a relative path's subquery see only the current object's
    /// side of the graph.
    fn correlate_path_select(ps: &mut IrPathSelect, outer_alias: &str) {
        // A trigger's own row may not be in its table yet (`BEFORE INSERT`):
        // the walk starts from the row itself.
        if outer_alias == "NEW" || outer_alias == "OLD" {
            ps.root.table = format!("@row:{outer_alias}");
            ps.root.poly = None;
        }
        let correlation = IrExpr::BinOp(Box::new(IrBinOp {
            left: IrExpr::ColumnRef {
                alias: ps.root.alias.clone(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
            op: ast::BinOpKind::Eq,
            right: IrExpr::ColumnRef {
                alias: outer_alias.to_string(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
        }));
        ps.filter = Some(match ps.filter.take() {
            Some(existing) => IrExpr::BinOp(Box::new(IrBinOp {
                left: correlation,
                op: ast::BinOpKind::And,
                right: existing,
            })),
            None => correlation,
        });
    }

    /// Names the kind of sub-statement that can't stand in for a value, so
    /// the message points at the actual blocker instead of listing every
    /// statement keyword.
    fn subquery_expr_err(&self, stmt: &Stmt) -> PyQLError {
        let what = match stmt {
            Stmt::Insert(_) => "an insert",
            Stmt::Update(_) => "an update",
            Stmt::Delete(_) => "a delete",
            Stmt::With(_) => "a `with` block",
            Stmt::For(_) => "a `for` loop",
            Stmt::Group(_) => "a `group`",
            _ => "this sub-statement",
        };
        self.type_err(&format!(
            "{what} cannot stand in for a value — a sub-statement is only valid in expression \
             position as a select over a path, e.g. '(select .emails filter .primary limit 1).address'"
        ))
    }

    // ── Expression compilation ────────────────────────────────────────────────────

    /// Single expression compiler for both free and schema-bound contexts.
    /// `ctx = Some((td, alias))` when a schema type + SQL alias are in scope
    /// (enables `.property`/`.link` resolution via `compile_path`); `ctx =
    /// None` for free expressions (set literals, tuples, free objects,
    /// scalar function calls not touching a table), via `compile_free_path`
    /// for the `Path` variant. Most arms are identical either way and just
    /// thread `ctx` through recursive calls; the handful that genuinely
    /// diverge (`Path`, `BinOp`, `FunctionCall`, `Set`, `Detached`, `TypeIs`)
    /// branch internally on `ctx` — see each arm's own comment.
    fn compile_expr_ctx(&mut self, expr: &Expr, ctx: Option<(&TypeDescriptor, &str)>) -> Result<IrExpr, PyQLError> {
        match expr {
            // The main free/schema divergence — kept genuinely two-branched
            // (`compile_path` needs a schema type + alias throughout:
            // __type__, absolute-path rewrite, 2-step link/property
            // traversal, computed-pointer recursion; `compile_free_path`
            // only ever resolves for-vars/CTEs/fn-params/enum members).
            // Both share the bare-name lookup via `resolve_name_ref`.
            Expr::Path(p) => match ctx {
                Some((td, alias)) => self.compile_path(p, td, alias),
                None => self.compile_free_path(p),
            },

            // `(select … limit 1).connector.provider[is Individual].staff` — a
            // walk off a sub-select including a step with no expression form.
            Expr::PathStepOn { .. } => match self.try_compile_walk_off_subquery(expr, ctx)? {
                Some(ir) => Ok(ir),
                None => Err(self.type_err(
                    "a type intersection, link property or backlink needs a path, a binding \
                     or a sub-select to walk off",
                )),
            },

            Expr::Literal(lit) => Ok(IrExpr::Literal(match lit {
                Literal::Str(s) => IrLiteral::Str(s.clone()),
                Literal::Int(n) => IrLiteral::Int(*n),
                Literal::Float(f) => IrLiteral::Float(*f),
                Literal::Bool(b) => IrLiteral::Bool(*b),
            })),

            Expr::Parameter(name) => {
                let index = self.param_index(name);
                Ok(IrExpr::Param { index })
            }

            Expr::Global(name) => self.compile_global(name),

            Expr::Index { expr: e, index: i } => {
                let ir_expr = self.compile_expr_ctx(e, ctx)?;
                if self.is_json_expr(e, &ir_expr) {
                    return match &**i {
                        Expr::Literal(Literal::Str(key)) => Ok(IrExpr::JsonbField {
                            expr: Box::new(ir_expr),
                            field: key.clone(),
                        }),
                        Expr::Literal(Literal::Int(n)) if *n >= 0 => Ok(IrExpr::JsonbIndex {
                            expr: Box::new(ir_expr),
                            index: *n as usize,
                        }),
                        _ => Err(self.type_err("indexing json needs a literal key or a literal position")),
                    };
                }
                let ir_index = self.compile_expr_ctx(i, ctx)?;
                let is_array = is_array_expr(&ir_expr);
                Ok(IrExpr::Subscript {
                    expr: Box::new(ir_expr),
                    index: Box::new(ir_index),
                    is_array,
                })
            }

            Expr::Slice {
                expr: e,
                lower: lo,
                upper: hi,
            } => {
                let ir_expr = self.compile_expr_ctx(e, ctx)?;
                let is_array = is_array_expr(&ir_expr);
                let ir_lower = lo.as_ref().map(|x| self.compile_expr_ctx(x, ctx)).transpose()?;
                let ir_upper = hi.as_ref().map(|x| self.compile_expr_ctx(x, ctx)).transpose()?;
                Ok(IrExpr::Slice {
                    expr: Box::new(ir_expr),
                    lower: ir_lower.map(Box::new),
                    upper: ir_upper.map(Box::new),
                    is_array,
                })
            }

            Expr::TypeCast(tc) => {
                // `<AnyType>{}` — an empty set cast to any type, e.g. clearing
                // an optional link (`<Company>{}`) — is always just NULL,
                // regardless of what pg_type the cast target would otherwise
                // resolve to (a schema object type name isn't a scalar cast
                // target at all, so resolve_cast_pg_type couldn't handle it
                // below anyway). Generalizes the same bare-`{}`-in-assignment-
                // position special case in compile_assignments_inner to any
                // expression context.
                if matches!(&tc.expr, Expr::Set(elems) if elems.is_empty()) {
                    return Ok(IrExpr::Null);
                }
                if let ast::TypeExpr::Tuple { elements } = &tc.ty
                    && let Some(ir) = self.try_compile_tuple_literal_cast_ctx(elements, &tc.expr, ctx)?
                {
                    let pg_type = self.resolve_cast_pg_type(&tc.ty)?;
                    let tuple_shape = self.resolve_tuple_cast_shape(&tc.ty);
                    return Ok(IrExpr::TypeCast(Box::new(IrTypeCast {
                        expr: ir,
                        pg_type,
                        tuple_shape,
                    })));
                }
                if let ast::TypeExpr::Array { element } = &tc.ty
                    && let Some(ir) = self.try_compile_array_literal_cast_ctx(element, &tc.expr, ctx)?
                {
                    let pg_type = self.resolve_cast_pg_type(&tc.ty)?;
                    return Ok(IrExpr::TypeCast(Box::new(IrTypeCast {
                        expr: ir,
                        pg_type,
                        tuple_shape: None,
                    })));
                }
                // `<marketplace::BrandAddon>line.listing.id` — casting a key to
                // an object type names the row that key identifies, and in
                // expression position (a link's value, a comparison) the row
                // *is* its key. There is no scalar pg type to cast to, so
                // `resolve_cast_pg_type` below reports the object type as
                // unknown.
                const STDLIB_MODULES: &[&str] = &["std", "cal", "math", "sys", "pgvector", "crypto", "postgis"];
                if let Some((module, name)) = tc.ty.as_named()
                    && module.map(|m| !STDLIB_MODULES.contains(&m)).unwrap_or(false)
                {
                    let qname = match module {
                        Some(m) => format!("{m}::{name}"),
                        None => name.to_string(),
                    };
                    if self.resolve_enum(&qname).is_none()
                        && self.resolve_scalar(&qname).is_none()
                        && self.resolve_named_tuple(&qname).is_none()
                        && self.resolve_type(&qname).is_ok()
                    {
                        return self.compile_expr_ctx(&tc.expr, ctx);
                    }
                }
                // A cast to `json` is an output sink: the text it produces is
                // the value, so an `id` nobody asked for would show up in it.
                // Gel clears the same flag here (`compiler/expr.py`).
                let inner = if casts_to_json(&tc.ty) {
                    self.without_implicit_id(|this| this.compile_expr_ctx(&tc.expr, ctx))?
                } else {
                    self.compile_expr_ctx(&tc.expr, ctx)?
                };
                let pg_type = self.resolve_cast_pg_type(&tc.ty)?;

                // PostgreSQL has no native jsonb -> {uuid, date/time family,
                // interval, array<T>} cast (only jsonb -> {bool, numeric
                // family, text} are native as of PG17+) — there's nothing
                // generic to defer to the way `to_jsonb(x)` covers every
                // scalar in the opposite direction, so extract via `#>>'{}'`
                // (the value's raw text form) and cast that, matching what
                // `to_json`'s own emitted text already round-trips (ISO 8601
                // for datetimes, PG's native interval text, a bare UUID
                // string — see `to_jsonb`'s emission for `<json>x`).
                if infer_ir_type(&inner) == Some("jsonb") {
                    if let ast::TypeExpr::Array { element } = &tc.ty {
                        let elem_pg = self.resolve_cast_pg_type(element)?;
                        let sql_template =
                            format!("ARRAY(SELECT (elem #>> '{{}}')::{elem_pg} FROM jsonb_array_elements($1) AS elem)");
                        return Ok(IrExpr::FunctionCall(super::IrFunctionCall {
                            return_pg_type: None,
                            schema: None,
                            name: "jsonb_array_cast".to_string(),
                            args: vec![inner],
                            sql_template: Some(sql_template),
                        }));
                    }
                    if matches!(
                        pg_type.as_str(),
                        "uuid" | "timestamptz" | "timestamp" | "date" | "time" | "interval"
                    ) {
                        let sql_template = format!("(($1 #>> '{{}}'))::{pg_type}");
                        return Ok(IrExpr::FunctionCall(super::IrFunctionCall {
                            return_pg_type: None,
                            schema: None,
                            name: "jsonb_scalar_cast".to_string(),
                            args: vec![inner],
                            sql_template: Some(sql_template),
                        }));
                    }
                }

                let tuple_shape = self.resolve_tuple_cast_shape(&tc.ty);
                Ok(IrExpr::TypeCast(Box::new(IrTypeCast {
                    expr: inner,
                    pg_type,
                    tuple_shape,
                })))
            }

            // The same coalesce with no shape after it — `(… ?? …)` standing
            // for the ids of the set it reaches. SQL's own COALESCE, which an
            // ordinary binary operator compiles to, takes one value per side,
            // so a walk reaching many rows has to be read as a set instead.
            Expr::BinOp(b)
                if b.op == ast::BinOpKind::Coalesce
                    && ctx.is_some()
                    && Self::coalesce_of_relative_paths(expr).is_some_and(|operands| {
                        let td = ctx.expect("checked").0;
                        self.relative_paths_reach_many(td, &operands)
                            && operands.iter().all(|path| self.path_lands_on_objects(td, path))
                    }) =>
            {
                let (td, alias) = ctx.expect("checked by the guard");
                let operands = Self::coalesce_of_relative_paths(expr).expect("checked by the guard");
                let branches = self.coalesce_path_branches(td, alias, &operands, &[])?;
                Ok(IrExpr::ObjectPathUnion {
                    branches,
                    limit: None,
                    multi: true,
                })
            }

            Expr::BinOp(b) => {
                // Only a condition can become an EXISTS — `.<pins.updated_at ??
                // .<pins.created_at` is a set of values, not a test on each pin.
                let yields_values = matches!(
                    b.op,
                    ast::BinOpKind::Add
                        | ast::BinOpKind::Sub
                        | ast::BinOpKind::Mul
                        | ast::BinOpKind::Div
                        | ast::BinOpKind::FloorDiv
                        | ast::BinOpKind::Mod
                        | ast::BinOpKind::Pow
                        | ast::BinOpKind::Coalesce
                        | ast::BinOpKind::Concat
                );
                if let Some((td, alias)) = ctx
                    && !yields_values
                {
                    if let Some(exists) = self.try_backlink_exists(b, td, alias)? {
                        return Ok(exists);
                    }
                    if let Some(exists) = self.try_multilink_exists(b, td, alias)? {
                        return Ok(exists);
                    }
                }
                // `x in {a, b, c}` / `x not in {a, b, c}`: a set *literal*
                // specifically on the right of in/not-in compiles to a
                // Postgres array, not through the generic Set-literal path
                // below (which hard-errors on any bare set literal in
                // expression position) — In/NotIn's own SQL emission
                // (`= ANY(...)`/`<> ALL(...)`, sql/mod.rs) already expects
                // an array-typed right operand, so this is the one
                // expression position a set literal is actually meaningful
                // in, in either schema-bound or free context.
                if matches!(b.op, ast::BinOpKind::In | ast::BinOpKind::NotIn)
                    && let Expr::Set(elems) = &b.right
                {
                    let left = self.compile_expr_ctx(&b.left, ctx)?;
                    let items = elems
                        .iter()
                        .map(|e| self.compile_expr_ctx(e, ctx))
                        .collect::<Result<Vec<_>, _>>()?;
                    let right = IrExpr::Array(items);
                    return Ok(IrExpr::BinOp(Box::new(IrBinOp {
                        left,
                        op: b.op.clone(),
                        right,
                    })));
                }
                // `.account = account_of_transaction()` — comparing objects
                // compares identity, so an object-returning function on either
                // side stands for the id of the row it returns. Left whole it
                // is a function call with nowhere to go but the subject of a
                // select.
                if matches!(b.op, ast::BinOpKind::Eq | ast::BinOpKind::Ne) {
                    let id = ["id".to_string()];
                    let left_id = match &b.left {
                        Expr::FunctionCall(fc) => self.try_compile_fn_scalar_subquery(fc, &id, None, ctx)?,
                        _ => None,
                    };
                    let right_id = match &b.right {
                        Expr::FunctionCall(fc) => self.try_compile_fn_scalar_subquery(fc, &id, None, ctx)?,
                        _ => None,
                    };
                    if left_id.is_some() || right_id.is_some() {
                        let left = match left_id {
                            Some(e) => e,
                            None => self.compile_expr_ctx(&b.left, ctx)?,
                        };
                        let right = match right_id {
                            Some(e) => e,
                            None => self.compile_expr_ctx(&b.right, ctx)?,
                        };
                        return Ok(IrExpr::BinOp(Box::new(IrBinOp {
                            left,
                            op: b.op.clone(),
                            right,
                        })));
                    }
                }
                let mut left = self.compile_expr_ctx(&b.left, ctx)?;
                let mut right = self.compile_expr_ctx(&b.right, ctx)?;
                // An ordering comparison takes one value a side, so a walk
                // gathered as an array is read back as a scalar subquery — see
                // `set_walk_as_scalar`.
                if matches!(
                    b.op,
                    ast::BinOpKind::Lt | ast::BinOpKind::Le | ast::BinOpKind::Gt | ast::BinOpKind::Ge
                ) && yields_array(&left) != yields_array(&right)
                {
                    left = set_walk_as_scalar(left);
                    right = set_walk_as_scalar(right);
                }
                // `A ?? B` over sets is A unless A is empty. An empty set
                // gathered as an array is `{}`, not NULL, so `COALESCE` would
                // never fall through to B.
                if b.op == ast::BinOpKind::Coalesce && (yields_array(&left) || yields_array(&right)) {
                    let as_set = |value: IrExpr| {
                        if yields_array(&value) {
                            value
                        } else {
                            IrExpr::FunctionCall(IrFunctionCall {
                                return_pg_type: None,
                                schema: None,
                                name: "array_remove".to_string(),
                                args: vec![value],
                                sql_template: Some("array_remove(ARRAY[$1], NULL)".to_string()),
                            })
                        }
                    };
                    let left = as_set(left);
                    let condition = IrExpr::FunctionCall(IrFunctionCall {
                        return_pg_type: None,
                        schema: None,
                        name: "cardinality".to_string(),
                        args: vec![left.clone()],
                        sql_template: Some("(cardinality($1) > 0)".to_string()),
                    });
                    return Ok(IrExpr::IfElse(Box::new(IrIfElse {
                        condition,
                        if_: left,
                        else_: as_set(right),
                    })));
                }
                // Comparing a value against a *set* — a path that crosses a
                // multi-link or a backlink, which arrives here as an array of
                // its elements — holds when any element matches, which is what
                // the equality means in PyQL and what `= ANY` says in SQL.
                if matches!(b.op, ast::BinOpKind::Eq | ast::BinOpKind::Ne) {
                    // A `with` binding of more than one row is the same kind
                    // of set, reached through its CTE rather than an array.
                    let is_set = |e: &IrExpr| match e {
                        IrExpr::ArrayFromSelect(_) => true,
                        IrExpr::CteRef { name, .. } => self.multi_row_ctes.contains(name),
                        _ => false,
                    };
                    let flipped = is_set(&left) && !is_set(&right) && !is_array_expr(&right);
                    let straight = is_set(&right) && !is_set(&left) && !is_array_expr(&left);
                    if flipped || straight {
                        let (value, set) = if straight { (left, right) } else { (right, left) };
                        let membership = IrExpr::BinOp(Box::new(IrBinOp {
                            left: value,
                            op: ast::BinOpKind::In,
                            right: set,
                        }));
                        return Ok(if matches!(b.op, ast::BinOpKind::Ne) {
                            IrExpr::UnaryOp(Box::new(IrUnaryOp {
                                op: ast::UnaryOpKind::Not,
                                operand: membership,
                            }))
                        } else {
                            membership
                        });
                    }
                }
                if let (Some(lt), Some(rt)) = (infer_ir_type(&left), infer_ir_type(&right))
                    && !types_compatible(lt, rt)
                    && !datetime_arithmetic_compatible(&b.op, lt, rt)
                {
                    return Err(PyQLError::Type(PyQLTypeError {
                        message: format!(
                            "operator '{op}' cannot be applied to operands of type \
                                 '{lq}' and '{rq}'",
                            op = b.op,
                            lq = pg_type_to_pyql(lt),
                            rq = pg_type_to_pyql(rt),
                        ),
                        position: Position { line: 0, col: 0 },
                    }));
                }
                Ok(IrExpr::BinOp(Box::new(IrBinOp {
                    left: true_division_operand(&b.op, left, &right),
                    op: b.op.clone(),
                    right,
                })))
            }

            Expr::FunctionCall(f) => {
                // notify(Channel, payload) / notify_raw(name, payload) → pg_notify(...).
                // Works in both free and schema-bound context (unlike sequence_next
                // below) since a trigger handler's payload needs __new__/__old__,
                // which only ever resolves schema-bound.
                if (f.module.is_none() || f.module.as_deref() == Some("std")) && f.name == "notify" {
                    return self.compile_notify(f, ctx);
                }
                if (f.module.is_none() || f.module.as_deref() == Some("std")) && f.name == "notify_raw" {
                    return self.compile_notify_raw(f, ctx);
                }

                // sequence_next / sequence_reset: type-ref arg → nextval/setval SQL
                // (free-only: schema-bound context never special-cased this).
                if ctx.is_none()
                    && (f.module.is_none() || f.module.as_deref() == Some("std"))
                    && (f.name == "sequence_next" || f.name == "sequence_reset")
                {
                    return self.compile_sequence_fn(f);
                }

                // assert_single(subquery) [free-only] / assert_single|assert_exists|
                // assert_distinct(subquery) [schema-bound] → _pylon.<fn>(ARRAY(subquery)).
                // Preserves the existing asymmetry: free context only ever recognized
                // "assert_single" here, not the other two.
                let assert_names: &[&str] = if ctx.is_some() {
                    &["assert_single", "assert_exists", "assert_distinct"]
                } else {
                    &["assert_single"]
                };
                if (f.module.is_none() || f.module.as_deref() == Some("std"))
                    && assert_names.contains(&f.name.as_str())
                    && !f.args.is_empty()
                    && let Expr::SubQuery(inner_stmt) = &f.args[0]
                {
                    let inner = match self.relative_subselect(inner_stmt, ctx)? {
                        Some(ps) => IrArraySource::PathSelect(Box::new(ps)),
                        None => self.compile_subquery_to_array_source(inner_stmt)?,
                    };
                    let fn_pg = match f.name.as_str() {
                        "assert_single" => "assert_single",
                        "assert_exists" => "assert_exists",
                        _ => "assert_distinct",
                    };
                    let mut args = vec![IrExpr::ArrayFromSelect(Box::new(inner))];
                    args.extend(self.assert_message(f, ctx)?);
                    return Ok(IrExpr::FunctionCall(IrFunctionCall {
                        return_pg_type: None,
                        schema: Some("_pylon".to_string()),
                        name: fn_pg.to_string(),
                        args,
                        sql_template: None,
                    }));
                }

                // contains(.multilink.scalar, value) → EXISTS (set-membership
                // semantics; schema-bound only, needs td/alias to resolve the
                // multilink).
                if let Some((td, alias)) = ctx
                    && (f.module.is_none() || f.module.as_deref() == Some("std"))
                    && f.name == "contains"
                    && f.args.len() == 2
                    && let Expr::Path(p) = &f.args[0]
                    && p.partial
                    && p.steps.len() >= 2
                    && let ast::PathStep::Name(ln) = &p.steps[0]
                    && Self::resolve_multilink(td, ln).is_some()
                {
                    let synthetic = ast::BinOp {
                        left: f.args[0].clone(),
                        op: ast::BinOpKind::Eq,
                        right: f.args[1].clone(),
                    };
                    if let Some(exists) = self.try_multilink_exists(&synthetic, td, alias)? {
                        return Ok(exists);
                    }
                }

                // Single-arg aggregate over a schema-shaped source →
                // AggOverQuery. Schema-bound: count(.multilink) correlates via
                // the junction/FK table (`.multilink` isn't an ordinary scalar
                // path). Free: count(TypeName) / count((select TypeName ...))
                // resolves the arg as a schema type reference or subquery.
                if f.args.len() == 1
                    && f.kwargs.is_empty()
                    && let Some(mut ps) = self.compile_shape_field_select(&f.args[0], ctx)?
                {
                    let IrPathResult::Scalar(column, _) = ps.result else {
                        return Err(self.type_err("a shape's pointer read off a walk is a value"));
                    };
                    let ns = f.module.as_deref().unwrap_or("std");
                    let aggregate =
                        crate::stdlib::lookup(ns, &f.name)
                            .into_iter()
                            .find_map(|d| match &d.impl_strategy {
                                crate::stdlib::ImplStrategy::SqlBuiltin(sql_name) if d.is_aggregate() => {
                                    Some(sql_name.to_string())
                                }
                                _ => None,
                            });
                    let Some(sql_name) = aggregate else {
                        return Err(self.type_err(&format!(
                            "'{}' over a shape's pointer read off a walk needs an aggregate",
                            f.name
                        )));
                    };
                    // Over no rows SQL's aggregates give NULL where Gel's give
                    // the empty set's own value.
                    let over_nothing = aggregate_over_nothing_sql(&f.name);
                    // An unnested set cannot sit inside the aggregate call;
                    // the walk's rows are aggregated from outside instead.
                    let subquery = if matches!(&column, IrExpr::FunctionCall(f) if f.name == "unnest" && f.sql_template.is_none())
                    {
                        ps.result = IrPathResult::Scalar(column, None);
                        IrExpr::FunctionCall(IrFunctionCall {
                            return_pg_type: None,
                            schema: None,
                            name: sql_name.clone(),
                            args: vec![IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(
                                ps,
                            ))))],
                            sql_template: Some(format!(
                                "(SELECT {sql_name}(\"_s\".\"v\") FROM unnest($1) AS \"_s\"(\"v\"))"
                            )),
                        })
                    } else {
                        let aggregate = IrExpr::FunctionCall(IrFunctionCall {
                            return_pg_type: None,
                            schema: None,
                            name: sql_name,
                            args: vec![column],
                            sql_template: None,
                        });
                        ps.result = IrPathResult::Scalar(aggregate, None);
                        IrExpr::PathSubquery(Box::new(ps))
                    };
                    return Ok(match over_nothing {
                        Some(value) => IrExpr::FunctionCall(IrFunctionCall {
                            return_pg_type: None,
                            schema: None,
                            name: "coalesce".to_string(),
                            args: vec![subquery, IrExpr::RawSql(value.to_string())],
                            sql_template: None,
                        }),
                        None => subquery,
                    });
                }
                if f.args.len() == 1 {
                    let arg = &f.args[0];
                    // `count(a intersect b)` counts what the operation yields.
                    // Read as an array it would count the array: always one.
                    if matches!(arg, Expr::Intersect(_, _) | Expr::Except(_, _)) {
                        use crate::stdlib::{ImplStrategy, lookup};
                        let ns = f.module.as_deref().unwrap_or("std");
                        let best = lookup(ns, &f.name)
                            .iter()
                            .find(|d| d.params.len() == 1)
                            .map(|d| d.impl_strategy.clone());
                        if let Some(ImplStrategy::SqlBuiltin(sql_name)) = best
                            && let IrExpr::SetOp { op, left, right, .. } = self.compile_expr_ctx(arg, ctx)?
                        {
                            return Ok(IrExpr::SetOp {
                                op,
                                left,
                                right,
                                mode: super::SetOpMode::Aggregate(sql_name.to_string()),
                            });
                        }
                    }
                    // `array_agg(array_unpack(.permissions))` — the elements
                    // of one row's array. PostgreSQL rejects a set-returning
                    // call inside an aggregate, so the unpacking becomes the
                    // row source the aggregate reads.
                    if let Expr::FunctionCall(unpack) = arg
                        && unpack.module.as_deref().unwrap_or("std") == "std"
                        && unpack.name == "array_unpack"
                        && unpack.kwargs.is_empty()
                        && let [array] = unpack.args.as_slice()
                        && let Some(sql_name) = crate::stdlib::lookup(f.module.as_deref().unwrap_or("std"), &f.name)
                            .into_iter()
                            .find_map(|d| match &d.impl_strategy {
                                crate::stdlib::ImplStrategy::SqlBuiltin(sql_name) if d.is_aggregate() => {
                                    Some(sql_name.to_string())
                                }
                                _ => None,
                            })
                    {
                        let values = self.compile_expr_ctx(array, ctx)?;
                        // A walk gathered as an array holds one array per row,
                        // which `unnest` would only flatten one level; that
                        // shape is aggregated where the walk is built instead.
                        if !yields_array(&values) {
                            let over_nothing = aggregate_over_nothing_sql(&f.name).unwrap_or("NULL");
                            return Ok(IrExpr::FunctionCall(IrFunctionCall {
                                return_pg_type: None,
                                schema: None,
                                name: sql_name.clone(),
                                args: vec![values],
                                sql_template: Some(format!(
                                    "(SELECT coalesce({sql_name}(\"_s\".\"v\"), {over_nothing}) FROM unnest($1) AS \"_s\"(\"v\"))"
                                )),
                            }));
                        }
                    }
                    // `sum((select T filter …).amount)` — the sub-select's
                    // values arrive gathered as an array; the aggregate
                    // takes its elements.
                    if matches!(arg, Expr::FieldAccess { .. })
                        && matches!(Self::peel_field_access_chain(arg).0, Expr::SubQuery(_))
                    {
                        let ns = f.module.as_deref().unwrap_or("std");
                        let aggregate =
                            crate::stdlib::lookup(ns, &f.name)
                                .into_iter()
                                .find_map(|d| match &d.impl_strategy {
                                    crate::stdlib::ImplStrategy::SqlBuiltin(sql_name) if d.is_aggregate() => {
                                        Some(sql_name.to_string())
                                    }
                                    _ => None,
                                });
                        if let Some(sql_name) = aggregate {
                            let values = self.compile_expr_ctx(arg, ctx)?;
                            if matches!(values, IrExpr::ArrayFromSelect(_)) {
                                let over_nothing = aggregate_over_nothing_sql(&f.name).unwrap_or("NULL");
                                return Ok(IrExpr::FunctionCall(IrFunctionCall {
                                    return_pg_type: None,
                                    schema: None,
                                    name: sql_name.clone(),
                                    args: vec![values],
                                    sql_template: Some(format!(
                                        "(SELECT coalesce({sql_name}(\"_s\".\"v\"), {over_nothing}) FROM unnest($1) AS \"_s\"(\"v\"))"
                                    )),
                                }));
                            }
                            return Ok(IrExpr::FunctionCall(IrFunctionCall {
                                return_pg_type: None,
                                schema: None,
                                name: sql_name,
                                args: vec![values],
                                sql_template: None,
                            }));
                        }
                    }
                    // `max(.<pins.updated_at ?? .<pins.created_at)` — the
                    // coalesce picks one whole set, gathered as an array, and
                    // the aggregate takes its elements.
                    if let Expr::BinOp(b) = arg
                        && b.op == ast::BinOpKind::Coalesce
                    {
                        let values = self.compile_expr_ctx(arg, ctx)?;
                        let ns = f.module.as_deref().unwrap_or("std");
                        let aggregate =
                            crate::stdlib::lookup(ns, &f.name)
                                .into_iter()
                                .find_map(|d| match &d.impl_strategy {
                                    crate::stdlib::ImplStrategy::SqlBuiltin(sql_name) if d.is_aggregate() => {
                                        Some(sql_name.to_string())
                                    }
                                    _ => None,
                                });
                        if let Some(sql_name) = aggregate
                            && yields_array(&values)
                        {
                            let over_nothing = aggregate_over_nothing_sql(&f.name).unwrap_or("NULL");
                            return Ok(IrExpr::FunctionCall(IrFunctionCall {
                                return_pg_type: None,
                                schema: None,
                                name: sql_name.clone(),
                                args: vec![values],
                                sql_template: Some(format!(
                                    "(SELECT coalesce({sql_name}(\"_s\".\"v\"), {over_nothing}) FROM unnest($1) AS \"_s\"(\"v\"))"
                                )),
                            }));
                        }
                        return self.resolve_fn_call(f.module.as_deref(), &f.name, vec![values]);
                    }
                    // `count(memberships)` — a binding names a set, so the
                    // aggregate runs over its rows. Compiled as an ordinary
                    // expression it becomes a scalar subquery over the CTE,
                    // which any binding of more than one row aborts on.
                    if let Some(name) = self.resolve_cte_name(arg) {
                        use crate::stdlib::{ImplStrategy, lookup};
                        let ns = f.module.as_deref().unwrap_or("std");
                        let overloads = lookup(ns, &f.name);
                        let best = overloads
                            .iter()
                            .find(|d| d.params.len() == 1)
                            .or_else(|| overloads.first());
                        if let Some(ImplStrategy::SqlBuiltin(sql_name)) = best.map(|d| &d.impl_strategy)
                            && best.is_some_and(|d| d.params.first().is_some_and(|p| p.ty.is_set()))
                        {
                            let object = self.cte_types.get(name).is_some_and(|bound| bound.contains("::"));
                            return Ok(IrExpr::AggOverCte {
                                fn_name: sql_name.to_string(),
                                cte: name.to_string(),
                                column: (!object).then(|| "v".to_string()),
                            });
                        }
                    }
                    if let Some((td, alias)) = ctx {
                        // `count((select .<promotion filter …))` — compiled as an
                        // expression the sub-select is a scalar subquery, and a
                        // bare aggregate around it aggregates the enclosing select.
                        if let Expr::SubQuery(stmt) = arg
                            && f.name != "array_agg"
                            && let Some(sql_name) = crate::stdlib::lookup(f.module.as_deref().unwrap_or("std"), &f.name)
                                .into_iter()
                                .find_map(|d| match &d.impl_strategy {
                                    crate::stdlib::ImplStrategy::SqlBuiltin(sql_name) if d.is_aggregate() => {
                                        Some(sql_name.to_string())
                                    }
                                    _ => None,
                                })
                            && let Some(mut ps) = self.relative_subselect(stmt, ctx)?
                        {
                            // An object row is an anonymous record, which `unnest` cannot expand.
                            if let IrPathResult::Object { alias, .. } = &ps.result {
                                let id = IrExpr::ColumnRef {
                                    alias: alias.clone(),
                                    column: "id".to_string(),
                                    pg_type: "uuid".to_string(),
                                };
                                ps.result = IrPathResult::Scalar(id, None);
                            }
                            let aggregate = IrExpr::FunctionCall(IrFunctionCall {
                                return_pg_type: None,
                                schema: None,
                                name: sql_name.clone(),
                                args: vec![IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(
                                    ps,
                                ))))],
                                sql_template: Some(format!(
                                    "(SELECT {sql_name}(\"_s\".\"v\") FROM unnest($1) AS \"_s\"(\"v\"))"
                                )),
                            });
                            return Ok(aggregate_over_nothing(&f.name, aggregate));
                        }
                        // `max(items.created_at)` inside a FILTER: the
                        // aggregate takes the whole set the path names, so it
                        // belongs inside a subquery over that set — a bare
                        // `max(...)` here is an aggregate in a WHERE clause,
                        // which Postgres rejects outright.
                        if let Expr::Path(p) = arg
                            && !p.partial
                            && p.steps.len() > 1
                            && let Some(root) = self.find_path_root_in_expr(arg)
                        {
                            let synthetic = ast::SelectStmt {
                                result: Expr::FunctionCall(f.clone()),
                                filter: None,
                                order_by: vec![],
                                offset: None,
                                limit: None,
                                lock: None,
                            };
                            let ps = self.compile_expr_as_path_select(&synthetic, &synthetic.result, &root, false)?;
                            return Ok(aggregate_over_nothing(&f.name, IrExpr::PathSubquery(Box::new(ps))));
                        }
                        // `sum(.applied_promotions.amount)` — the aggregate
                        // takes the set the walk lands on, so the walk becomes
                        // the row source of a correlated subquery the aggregate
                        // sits inside. Compiled as an expression the walk stands
                        // for the array of its elements, leaving the aggregate
                        // with an array argument and no overload to match.
                        // A backlink is as many-valued: `count(.<revisions)`.
                        // So is a computed selecting a set
                        // (`Computed[MultiLink[Member], '.staff']`) — one step,
                        // but the junction-only count below cannot see through
                        // it to a junction table, so it walks the path the
                        // computed splices into instead.
                        if let Expr::Path(p) = arg
                            && p.partial
                            && (p.steps.len() > 1 && self.path_crosses_multi(td, &p.steps)
                                || matches!(p.steps.first(), Some(ast::PathStep::Backlink(_)))
                                || matches!(p.steps.as_slice(), [ast::PathStep::Name(name)]
                                    if Self::resolve_multilink(td, name).is_none()
                                        && self.path_crosses_multi(td, &p.steps)))
                        {
                            let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
                            steps.extend(p.steps.iter().cloned());
                            let rooted = ast::Path { steps, partial: false };
                            let mut call = f.clone();
                            call.args[0] = Expr::Path(rooted);
                            let synthetic = ast::SelectStmt {
                                result: Expr::FunctionCall(call),
                                filter: None,
                                order_by: vec![],
                                offset: None,
                                limit: None,
                                lock: None,
                            };
                            let root = format!("{}::{}", td.module, td.name);
                            let mut ps =
                                self.compile_expr_as_path_select(&synthetic, &synthetic.result, &root, false)?;
                            Self::correlate_path_select(&mut ps, alias);
                            return Ok(aggregate_over_nothing(&f.name, IrExpr::PathSubquery(Box::new(ps))));
                        }
                        if let Expr::Path(p) = arg
                            && p.partial
                            && p.steps.len() == 1
                            && let ast::PathStep::Name(ml_name) = &p.steps[0]
                            && Self::resolve_multilink(td, ml_name).is_some()
                        {
                            use crate::stdlib::{ImplStrategy, lookup};
                            let ns = f.module.as_deref().unwrap_or("std");
                            let overloads = lookup(ns, &f.name);
                            let best = overloads
                                .iter()
                                .find(|d| d.params.len() == 1)
                                .or_else(|| overloads.first());
                            if let Some(ImplStrategy::SqlBuiltin(sql_name)) = best.map(|d| &d.impl_strategy) {
                                let fn_name = sql_name.to_string();
                                let inner = self.multilink_correlation_select(ml_name, td, alias)?;
                                return Ok(IrExpr::AggOverQuery {
                                    fn_name,
                                    inner: Box::new(inner),
                                });
                            }
                        }
                    } else {
                        // `array_agg(a.sessions.id)` with no type in scope: the
                        // aggregate takes the whole set the path names, so it
                        // belongs in a subquery over that traversal. Compiled as
                        // an expression instead, a multi-valued path stands for
                        // the array of its elements, and aggregating *that*
                        // nests it one level deep — the same reason the
                        // schema-bound branch above routes this way.
                        if let Expr::Path(p) = arg
                            && !p.partial
                            && p.steps.len() > 1
                            && let Some(root) = self.find_path_root_in_expr(arg)
                        {
                            let synthetic = ast::SelectStmt {
                                result: Expr::FunctionCall(f.clone()),
                                filter: None,
                                order_by: vec![],
                                offset: None,
                                limit: None,
                                lock: None,
                            };
                            let ps = self.compile_expr_as_path_select(&synthetic, &synthetic.result, &root, false)?;
                            return Ok(aggregate_over_nothing(&f.name, IrExpr::PathSubquery(Box::new(ps))));
                        }
                        // `count((delete AuthLink filter .expired))` — the rows
                        // a mutation touched are countable like any other set.
                        // The mutation becomes its own data-modifying CTE, which
                        // Postgres runs regardless, and the aggregate reads it.
                        if let Expr::SubQuery(stmt) = arg
                            && matches!(stmt.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_))
                        {
                            use crate::stdlib::{ImplStrategy, lookup};
                            let ns = f.module.as_deref().unwrap_or("std");
                            let overloads = lookup(ns, &f.name);
                            let best = overloads
                                .iter()
                                .find(|d| d.params.len() == 1)
                                .or_else(|| overloads.first())
                                .cloned();
                            if let Some(d) = best
                                && let ImplStrategy::SqlBuiltin(sql_name) = &d.impl_strategy
                            {
                                let fn_name = sql_name.to_string();
                                let (cte_name, type_name) = self.hoist_dml_as_cte(stmt.as_ref())?;
                                let td = self.resolve_type(&type_name)?;
                                let source = IrSource {
                                    poly: None,
                                    type_name: format!("{}::{}", td.module, td.name),
                                    table: format!("@cte:{cte_name}"),
                                    alias: self.fresh_alias(),
                                };
                                let inner = IrSelect::schema_bound(source, Self::pk_returning(td), None);
                                return Ok(IrExpr::AggOverQuery {
                                    fn_name,
                                    inner: Box::new(inner),
                                });
                            }
                        }
                        let inner_sel: Option<ast::SelectStmt> = match arg {
                            Expr::Path(p) if !p.partial => {
                                // Resolve as a schema type if it matches a known type (not enum).
                                let qname = p
                                    .steps
                                    .iter()
                                    .filter_map(|s| {
                                        if let ast::PathStep::Name(n) = s {
                                            Some(n.as_str())
                                        } else {
                                            None
                                        }
                                    })
                                    .collect::<Vec<_>>()
                                    .join("::");
                                let is_schema_type = self
                                    .schema
                                    .types
                                    .iter()
                                    .any(|t| format!("{}::{}", t.module, t.name) == qname || t.name == qname);
                                if is_schema_type {
                                    Some(ast::SelectStmt {
                                        result: arg.clone(),
                                        filter: None,
                                        order_by: vec![],
                                        offset: None,
                                        limit: None,
                                        lock: None,
                                    })
                                } else {
                                    None
                                }
                            }
                            Expr::SubQuery(stmt) => {
                                if let ast::Stmt::Select(inner) = stmt.as_ref() {
                                    Some(inner.clone())
                                } else {
                                    None
                                }
                            }
                            _ => None,
                        };
                        if let Some(sel) = inner_sel {
                            use crate::stdlib::{ImplStrategy, lookup};
                            let ns = f.module.as_deref().unwrap_or("std");
                            let overloads = lookup(ns, &f.name);
                            let best = overloads
                                .iter()
                                .find(|d| d.params.len() == 1)
                                .or_else(|| overloads.first());
                            // `array_agg((select Type.prop))` — the sub-select
                            // walks to a scalar, which has no type name to be a
                            // schema select's subject. It is the same thing as
                            // `array_agg(Type.prop)` with the select's own
                            // modifiers on the walk, which is what
                            // `compile_expr_as_path_select` already builds.
                            // A `distinct` inside the sub-select means the
                            // same as one on the argument, and that is where the
                            // aggregate can act on it.
                            let (inner_result, inner_distinct) = match &sel.result {
                                Expr::UnaryOp(u) if matches!(u.op, ast::UnaryOpKind::Distinct) => (&u.operand, true),
                                other => (other, false),
                            };
                            if let Expr::Path(inner_path) = inner_result
                                && !inner_path.partial
                                && inner_path.steps.len() > 1
                                && let Some(ast::PathStep::Name(root)) = inner_path.steps.first()
                                && let Ok(root_td) = self.resolve_path_root(root)
                                && self
                                    .walk_path_types(root_td, &inner_path.steps[1..], MAX_COMPUTED_SPLICES)
                                    .1
                                    .is_none()
                            {
                                let root = root.clone();
                                let mut inner_call = f.clone();
                                inner_call.args = vec![if inner_distinct {
                                    Expr::UnaryOp(Box::new(ast::UnaryOp {
                                        op: ast::UnaryOpKind::Distinct,
                                        operand: inner_result.clone(),
                                    }))
                                } else {
                                    inner_result.clone()
                                }];
                                let call = ast::SelectStmt {
                                    result: Expr::FunctionCall(inner_call),
                                    ..sel.clone()
                                };
                                let ps = self.compile_expr_as_path_select(&call, &call.result, &root, false)?;
                                return Ok(IrExpr::PathSubquery(Box::new(ps)));
                            }
                            if let Some(d) = best
                                && let ImplStrategy::SqlBuiltin(sql_name) = &d.impl_strategy
                            {
                                let fn_name = sql_name.to_string();
                                let inner_ir = self.compile_select(&sel, &sel.result, false)?;
                                // `array_agg((select brands { * } filter …))` —
                                // an array of the objects, rows and shape
                                // whole; `array_agg(*)` is not an aggregate
                                // Postgres has.
                                if fn_name == "array_agg"
                                    && matches!(inner_ir.rows.as_slice(), [IrRowSource::Bound { .. }])
                                {
                                    return Ok(IrExpr::ArrayFromSelect(Box::new(IrArraySource::ObjectSelect(
                                        Box::new(inner_ir),
                                    ))));
                                }
                                return Ok(IrExpr::AggOverQuery {
                                    fn_name,
                                    inner: Box::new(inner_ir),
                                });
                            }
                        }
                    }
                }

                // Set-literal argument → AggOverSet (free-only; a schema-bound
                // Set argument would already hard-error via the Set/Shape arm
                // when compiled below, matching today's behavior — this
                // special case never existed on the schema side).
                if ctx.is_none() {
                    let set_arg_idx = f.args.iter().position(|a| matches!(a, Expr::Set(_)));
                    if let Some(idx) = set_arg_idx
                        && let Expr::Set(set_elems) = &f.args[idx]
                    {
                        use crate::stdlib::{ImplStrategy, lookup};
                        let ns = f.module.as_deref().unwrap_or("std");
                        let overloads = lookup(ns, &f.name);
                        let best = overloads
                            .iter()
                            .find(|d| d.params.len() == f.args.len())
                            .or_else(|| overloads.first());
                        let (schema, fn_name) = match best.map(|d| &d.impl_strategy) {
                            Some(ImplStrategy::SqlBuiltin(sql_name)) => (None, sql_name.to_string()),
                            Some(_) => {
                                return Err(self.type_err(&format!(
                                    "function '{}::{}' cannot be called with a set literal in this context",
                                    ns, f.name
                                )));
                            }
                            None => return Err(self.type_err(&format!("function '{}::{}' does not exist", ns, f.name))),
                        };
                        let elems = set_elems
                            .iter()
                            .map(|e| self.compile_expr_ctx(e, ctx))
                            .collect::<Result<Vec<_>, _>>()?;
                        return Ok(IrExpr::AggOverSet { fn_name, schema, elems });
                    }
                }

                // `any(...)`/`all(...)` say outright that the argument is a
                // set, so the comparison inside must not also be warned about.
                // The argument is compiled before `resolve_fn_call` ever sees
                // which function this is, which is why the guard goes here.
                // `any(.grants.account = a and not .grants.deleted)` — every
                // `.grants` in it is the same grant, so the condition holds
                // per grant; compiled term by term, each walked the link on
                // its own.
                if let Some((td, _)) = ctx
                    && f.module.as_deref().unwrap_or("std") == "std"
                    && matches!(f.name.as_str(), "any" | "all")
                    && f.kwargs.is_empty()
                    && let [condition] = f.args.as_slice()
                    && let Some(per_element) = per_element_of_one_multilink(condition, td)
                {
                    let (link, element_condition) = per_element;
                    let condition = if f.name == "all" {
                        Expr::UnaryOp(Box::new(ast::UnaryOp {
                            op: ast::UnaryOpKind::Not,
                            operand: element_condition,
                        }))
                    } else {
                        element_condition
                    };
                    let exists = Expr::UnaryOp(Box::new(ast::UnaryOp {
                        op: ast::UnaryOpKind::Exists,
                        operand: Expr::SubQuery(Box::new(Stmt::Select(ast::SelectStmt {
                            result: Expr::Path(ast::Path {
                                steps: link,
                                partial: true,
                            }),
                            filter: Some(condition),
                            order_by: vec![],
                            offset: None,
                            limit: None,
                            lock: None,
                        }))),
                    }));
                    let exists = if f.name == "all" {
                        Expr::UnaryOp(Box::new(ast::UnaryOp {
                            op: ast::UnaryOpKind::Not,
                            operand: exists,
                        }))
                    } else {
                        exists
                    };
                    return self.compile_expr_ctx(&exists, ctx);
                }
                // `any(.<company.posts is Post)` — one answer per object the
                // path reaches, gathered as an array, so aggregate its elements.
                if f.module.as_deref().unwrap_or("std") == "std"
                    && matches!(f.name.as_str(), "any" | "all")
                    && f.kwargs.is_empty()
                    && let [arg @ Expr::TypeIs { .. }] = f.args.as_slice()
                    && let answers @ IrExpr::ArrayFromSelect(_) = self.compile_expr_ctx(arg, ctx)?
                {
                    let (aggregate, over_nothing) = if f.name == "all" {
                        ("bool_and", "true")
                    } else {
                        ("bool_or", "false")
                    };
                    return Ok(IrExpr::FunctionCall(IrFunctionCall {
                        return_pg_type: None,
                        schema: None,
                        name: aggregate.to_string(),
                        args: vec![answers],
                        sql_template: Some(format!(
                            "(SELECT coalesce({aggregate}(\"_unnested\".\"v\"), {over_nothing}) FROM unnest($1) AS \"_unnested\"(\"v\"))"
                        )),
                    }));
                }
                // `all(array_unpack($tags) in .tags.label)` — the comparison is
                // made once per element, then aggregated. Inlined as `unnest()`
                // the array is a set-returning call, which Postgres refuses in a
                // WHERE; over no elements `all` is true and `any` false.
                if f.module.as_deref().unwrap_or("std") == "std"
                    && matches!(f.name.as_str(), "any" | "all")
                    && f.kwargs.is_empty()
                    && let [Expr::BinOp(comparison)] = f.args.as_slice()
                    && let Expr::FunctionCall(unpack) = &comparison.left
                    && unpack.module.as_deref().unwrap_or("std") == "std"
                    && unpack.name == "array_unpack"
                    && let [array] = unpack.args.as_slice()
                {
                    let array = self.compile_expr_ctx(array, ctx)?;
                    let element = "<unnested element>".to_string();
                    self.inline_bindings
                        .insert(element.clone(), IrExpr::RawSql("\"_unnested\".\"v\"".to_string()));
                    let per_element = self.compile_expr_ctx(
                        &Expr::BinOp(Box::new(ast::BinOp {
                            left: Expr::Path(ast::Path::absolute(element.clone())),
                            op: comparison.op.clone(),
                            right: comparison.right.clone(),
                        })),
                        ctx,
                    );
                    self.inline_bindings.remove(&element);
                    let (aggregate, over_nothing) = if f.name == "all" {
                        ("bool_and", "true")
                    } else {
                        ("bool_or", "false")
                    };
                    return Ok(IrExpr::FunctionCall(IrFunctionCall {
                        return_pg_type: None,
                        schema: None,
                        name: aggregate.to_string(),
                        args: vec![per_element?, array],
                        sql_template: Some(format!(
                            "(SELECT coalesce({aggregate}($1), {over_nothing}) FROM unnest($2) AS \"_unnested\"(\"v\"))"
                        )),
                    }));
                }
                if let Some(args) = self.compile_named_call_args(f, ctx)? {
                    return self.resolve_fn_call(f.module.as_deref(), &f.name, args);
                }
                let is_explicit_set = f.module.as_deref().unwrap_or("std") == "std"
                    && matches!(f.name.as_str(), "any" | "all")
                    && f.args.len() == 1;
                if is_explicit_set {
                    self.explicit_set_depth += 1;
                }
                let args = f
                    .args
                    .iter()
                    .map(|a| self.compile_expr_ctx(a, ctx))
                    .collect::<Result<Vec<_>, _>>();
                if is_explicit_set {
                    self.explicit_set_depth -= 1;
                }
                self.resolve_fn_call(f.module.as_deref(), &f.name, args?)
            }

            Expr::UnaryOp(u) if u.op == ast::UnaryOpKind::Exists => self.compile_exists_ctx(&u.operand, ctx),

            // `distinct` in expression position: a set-producing operand
            // dedupes its own rows, and a single value — an array, a global, a
            // column — is already distinct, so it stands for itself. (A
            // statement-level `select distinct …` never reaches here; it is
            // unwrapped into the select's own `distinct` flag.)
            Expr::UnaryOp(u) if u.op == ast::UnaryOpKind::Distinct => {
                let operand = self.compile_expr_ctx(&u.operand, ctx)?;
                Ok(match operand {
                    IrExpr::PathSubquery(mut ps) => {
                        ps.distinct = true;
                        IrExpr::PathSubquery(ps)
                    }
                    IrExpr::ArrayFromSelect(src) => IrExpr::ArrayFromSelect(Box::new(match *src {
                        IrArraySource::Select(mut sel) => {
                            sel.distinct = true;
                            IrArraySource::Select(sel)
                        }
                        IrArraySource::PathSelect(mut ps) => {
                            ps.distinct = true;
                            IrArraySource::PathSelect(ps)
                        }
                        other => other,
                    })),
                    other => other,
                })
            }

            Expr::UnaryOp(u) => {
                let operand = self.compile_expr_ctx(&u.operand, ctx)?;
                Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
                    op: u.op.clone(),
                    operand,
                })))
            }

            Expr::IfElse(ie) => {
                let condition = self.compile_expr_ctx(&ie.condition, ctx)?;
                let if_ = self.compile_expr_ctx(&ie.if_expr, ctx)?;
                let else_ = self.compile_expr_ctx(&ie.else_expr, ctx)?;
                Ok(IrExpr::IfElse(Box::new(IrIfElse { condition, if_, else_ })))
            }

            Expr::Array(elems) => {
                let items = elems
                    .iter()
                    .map(|e| self.compile_expr_ctx(e, ctx))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(IrExpr::Array(items))
            }

            Expr::NamedTuple(fields) => {
                let ir = fields
                    .iter()
                    .map(|(name, e)| Ok((name.clone(), self.compile_expr_ctx(e, ctx)?)))
                    .collect::<Result<Vec<_>, PyQLError>>()?;
                Ok(IrExpr::NamedTuple {
                    fields: ir,
                    is_free_object: false,
                })
            }

            Expr::Tuple(elems) => {
                let ir = elems
                    .iter()
                    .map(|e| self.compile_expr_ctx(e, ctx))
                    .collect::<Result<Vec<_>, PyQLError>>()?;
                Ok(IrExpr::Tuple(ir))
            }

            Expr::FieldAccess { expr: inner, field } => {
                // `(select …).provider[is Individual].staff` arrives here, not
                // at the `PathStepOn` arm: the trailing `.staff` is outermost.
                if let Some(ir) = self.try_compile_walk_off_subquery(expr, ctx)? {
                    return Ok(ir);
                }
                if let Expr::NamedTuple(fields) = inner.as_ref() {
                    let (_, val) = fields.iter().find(|(k, _)| k == field).ok_or_else(|| {
                        self.type_err(&format!("{field} is not a member of {}", named_tuple_type_str(fields)))
                    })?;
                    return self.compile_expr_ctx(val, ctx);
                }
                if let Some(ps) = self.compile_shape_field_select(expr, ctx)? {
                    return Ok(IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(
                        ps,
                    )))));
                }
                // `(select .emails filter .primary limit 1).address` — the
                // field chain is spliced onto the sub-select's own path so
                // the subquery projects that column, rather than being read
                // as jsonb extraction off an object id.
                let (base, fields) = Self::peel_field_access_chain(expr);
                if let Expr::SubQuery(stmt) = base {
                    let stmt = stmt.as_ref().clone();
                    return self.compile_subquery_expr(&stmt, &fields, ctx, &[]);
                }
                // `account::owner(.id).name` — an object-returning function
                // projected to one of its columns.
                if let Expr::FunctionCall(fc) = base {
                    let fc = fc.clone();
                    if let Some(ir) = self.try_compile_fn_scalar_subquery(&fc, &fields, None, ctx)? {
                        return Ok(ir);
                    }
                }
                let ir = self.compile_expr_ctx(inner, ctx)?;
                Ok(Self::project_free_object_field(ir, field))
            }

            Expr::TupleIndex { expr: inner, index } => {
                match inner.as_ref() {
                    Expr::Tuple(elems) => {
                        let elem = elems.get(*index).ok_or_else(|| {
                            self.type_err(&format!(
                                "{index} is not a member of {}",
                                positional_tuple_type_str(elems)
                            ))
                        })?;
                        self.compile_expr_ctx(elem, ctx)
                    }
                    Expr::NamedTuple(fields) => {
                        let (_, val) = fields.get(*index).ok_or_else(|| {
                            self.type_err(&format!("{index} is not a member of {}", named_tuple_type_str(fields)))
                        })?;
                        self.compile_expr_ctx(val, ctx)
                    }
                    // Not a literal to constant-fold — emit a generic runtime
                    // jsonb positional access (`$param.1`, `(<tuple<...>>expr).1`, …).
                    // When the source is a cast to a statically-known tuple type,
                    // bounds-check the index against its arity at compile time
                    // (e.g. `2 is not a member of tuple<std::int64, std::str>`).
                    _ => {
                        if let Expr::TypeCast(tc) = inner.as_ref()
                            && let Some(shape) = self.resolve_tuple_cast_shape(&tc.ty)
                            && *index >= shape.members.len()
                        {
                            return Err(self.type_err(&format!(
                                "{index} is not a member of {}",
                                self.type_expr_to_display_str(&tc.ty)
                            )));
                        }
                        let ir = self.compile_expr_ctx(inner, ctx)?;
                        Ok(IrExpr::JsonbIndex {
                            expr: Box::new(ir),
                            index: *index,
                        })
                    }
                }
            }

            // `detached` bypasses the implicit root-matches-td correlation
            // rewrite. Schema-bound: if `inner` contains a type-rooted path,
            // compile it as an independent PathSubquery; otherwise (or when
            // already free) fall back to compiling `inner` with NO schema
            // binding — note this fallback is deliberately `None`, not
            // `ctx`, since `detached` means "evaluate independently of the
            // enclosing scope" and free context has no rooted path to find
            // in the first place (`find_path_root_in_expr` only ever matches
            // against a resolvable schema type name).
            Expr::Detached(inner) => {
                if ctx.is_some()
                    && let Some(root) = self.find_path_root_in_expr(inner)
                {
                    let synthetic = ast::SelectStmt {
                        result: (**inner).clone(),
                        filter: None,
                        order_by: vec![],
                        offset: None,
                        limit: None,
                        lock: None,
                    };
                    let ps = self.compile_expr_as_path_select(&synthetic, inner, &root, false)?;
                    return Ok(IrExpr::PathSubquery(Box::new(ps)));
                }
                self.compile_expr_ctx(inner, None)
            }

            // Free context tolerates an empty set (-> Null) or a singleton
            // set (-> its one element) as a convenience; a schema-bound
            // expression position hard-errors on ANY set literal instead
            // (see the generic Shape|Set arm below) — a plausibly
            // intentional semantic difference, preserved exactly as-is.
            Expr::Set(elems) if ctx.is_none() && elems.is_empty() => Ok(IrExpr::Null),

            Expr::Set(elems) if ctx.is_none() => {
                let compiled: Result<Vec<_>, _> = elems.iter().map(|e| self.compile_expr_ctx(e, ctx)).collect();
                let mut compiled = compiled?;
                if compiled.len() == 1 {
                    Ok(compiled.remove(0))
                } else {
                    Err(self.type_err("multi-element set literal is not supported in free SELECT context"))
                }
            }

            // A free object literal (`{ foo := 'bar' }`, no subject type) is
            // valid anywhere an expression is, not just as a whole SELECT's
            // result — e.g. nested inside a computed shape element. Compiled
            // the same way `compile_free_select` treats it at the top level
            // (each field compiled independently, ctx propagated so a
            // schema-bound nested free object can still reference `.name`
            // etc.), just wrapped as `IrExpr::NamedTuple` (jsonb) instead of
            // a whole result row, since here it's a value, not a row source.
            // is_free_object: true — this came from curly-brace shape syntax,
            // not a paren tuple literal, so the value-shape-tag tree
            // (pylon/query.py's shape_value_tags) can tell the frontend to
            // render it as an expandable "Object {...}", not a `(...)`
            // tuple literal (see ShapeNode::NamedTuple's own doc comment).
            Expr::Shape(s) if s.expr.is_none() => {
                let fields = s
                    .elements
                    .iter()
                    .map(|el| -> Result<(String, IrExpr), PyQLError> {
                        let name = path_leaf(&el.path)?.to_string();
                        let expr = el.compexpr.as_ref().ok_or_else(|| {
                            self.type_err("free object field must have a value expression (':= expr')")
                        })?;
                        let compiled = match expr {
                            Expr::SubQuery(stmt)
                                if matches!(stmt.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_)) =>
                            {
                                self.dml_as_value(stmt.as_ref())?
                            }
                            other => match self.free_object_link_field(other)? {
                                Some(object) => object,
                                None => self.compile_expr_ctx(other, ctx)?,
                            },
                        };
                        Ok((name, compiled))
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(IrExpr::NamedTuple {
                    fields,
                    is_free_object: true,
                })
            }

            // A shape applied to a WITH-bound free object (`test := test {
            // test2 }` where `test` isn't a schema object, just a free
            // binding) projects the named fields out of it — each element
            // either reads the underlying field (by name, via the same
            // per-field CTE column `.field` access uses) or, with a `:=`
            // override, compiles a brand new value in the current context,
            // exactly like a fresh free-object-literal field would.
            Expr::Shape(s) if matches!(&s.expr, Some(inner) if self.is_free_cte_ref(inner)) => {
                let Some(Expr::Path(root_path)) = &s.expr else {
                    unreachable!()
                };
                let ast::PathStep::Name(root) = &root_path.steps[0] else {
                    unreachable!()
                };
                let fields = s
                    .elements
                    .iter()
                    .map(|el| -> Result<(String, IrExpr), PyQLError> {
                        let name = path_leaf(&el.path)?.to_string();
                        let expr = match &el.compexpr {
                            Some(over) => self.compile_expr_ctx(over, ctx)?,
                            None => match self.resolve_cte_field_chain(root, &[name.as_str()]) {
                                Some(result) => result?,
                                None => {
                                    return Err(self.type_err(&format!("free object '{root}' has no field '{name}'")));
                                }
                            },
                        };
                        Ok((name, expr))
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(IrExpr::NamedTuple {
                    fields,
                    is_free_object: true,
                })
            }

            // `(.<prices[is Listing] union .<sale_prices[is Listing]) { id }`
            // — each operand hangs off the enclosing row, so none can be
            // hoisted into a CTE the way a standalone union's operands are.
            Expr::Shape(sh)
                if ctx.is_some()
                    && matches!(sh.expr.as_ref(), Some(Expr::Union(_, _)))
                    && Self::union_of_relative_paths(sh.expr.as_ref().expect("checked")).is_some() =>
            {
                let (td, alias) = ctx.expect("checked by the guard");
                let operands =
                    Self::union_of_relative_paths(sh.expr.as_ref().expect("checked")).expect("checked by the guard");
                let elements = sh.elements.clone();
                let multi = self.relative_paths_reach_many(td, &operands);
                let mut branches = Vec::with_capacity(operands.len());
                for path in operands {
                    let mut steps = vec![ast::PathStep::Name(format!("{}::{}", td.module, td.name))];
                    steps.extend(path.steps.iter().cloned());
                    let rooted = ast::Path { steps, partial: false };
                    let synthetic = ast::SelectStmt {
                        result: Expr::Path(rooted.clone()),
                        filter: None,
                        order_by: vec![],
                        offset: None,
                        limit: None,
                        lock: None,
                    };
                    let mut ps = self.compile_path_select(&synthetic, &rooted, &elements, false)?;
                    Self::correlate_path_select(&mut ps, alias);
                    branches.push(ps);
                }
                Ok(IrExpr::ObjectPathUnion {
                    branches,
                    limit: None,
                    multi,
                })
            }

            // `([is Conditional].configs ?? [is Loop].configs) { … }` — the
            // same correlated walks a union of them gives, except each operand
            // after the first only stands in when the ones before it are empty.
            Expr::Shape(sh)
                if ctx.is_some() && sh.expr.as_ref().and_then(Self::coalesce_of_relative_paths).is_some() =>
            {
                let (td, alias) = ctx.expect("checked by the guard");
                let operands =
                    Self::coalesce_of_relative_paths(sh.expr.as_ref().expect("checked")).expect("checked by the guard");
                let multi = self.relative_paths_reach_many(td, &operands);
                let branches = self.coalesce_path_branches(td, alias, &operands, &sh.elements)?;
                Ok(IrExpr::ObjectPathUnion {
                    branches,
                    limit: None,
                    multi,
                })
            }

            Expr::Shape(sh) if matches!(sh.expr.as_ref(), Some(Expr::SubQuery(_))) => {
                let sh = sh.clone();
                match self.shape_over_subquery(&sh)? {
                    Some(ir) => Ok(ir),
                    None => Err(PyQLError::Type(PyQLTypeError {
                        message: "shapes and set literals are not valid in expression context".into(),
                        position: Position { line: 0, col: 0 },
                    })),
                }
            }

            Expr::Shape(sh) if Self::shape_over_subquery_projection(sh).is_some() => {
                let (stmt, fields) = Self::shape_over_subquery_projection(sh).expect("checked by the guard");
                let stmt = stmt.clone();
                let elements = sh.elements.clone();
                self.compile_subquery_expr(&stmt, &fields, ctx, &elements)
            }

            // `account := account if cond else {}` — the empty set is a legal
            // expression in EdgeQL and means "no value", which is what the
            // assignment paths already spell `IrExpr::Null`. Only a *non-empty*
            // set literal has no expression-position meaning.
            Expr::Set(items) if items.is_empty() => Ok(IrExpr::Null),

            Expr::Shape(sh)
                if matches!(sh.expr.as_ref(), Some(Expr::Path(p))
                    if !p.partial
                        && matches!(p.steps.first(), Some(ast::PathStep::Name(n))
                            if self.cte_object_type(n).is_some() || self.for_var_types.contains_key(n))) =>
            {
                let expr = expr.clone();
                match self.shape_over_binding(&expr)? {
                    Some(ir) => Ok(ir),
                    None => Err(PyQLError::Type(PyQLTypeError {
                        message: "shapes and set literals are not valid in expression context".into(),
                        position: Position { line: 0, col: 0 },
                    })),
                }
            }

            // A bare shape or set literal is never valid in expression
            // position, in either context — preserved exactly as the
            // schema-bound side always enforced (the free side's more
            // permissive empty/singleton-set handling above is the one
            // deliberate exception, handled before this arm).
            Expr::Shape(_) | Expr::Set(_) => Err(PyQLError::Type(PyQLTypeError {
                message: "shapes and set literals are not valid in expression context".into(),
                position: Position { line: 0, col: 0 },
            })),

            // A `select` over a path compiles to a correlated subquery; DML
            // and everything else still has no expression-position meaning.
            // Union/Except previously fell through free's generic "not valid
            // in free SELECT context" catch-all — these explicit,
            // purpose-written messages (already used schema-bound) apply
            // equally well with no schema in scope, so they're unconditional
            // here rather than ctx-gated.
            Expr::SubQuery(stmt) => {
                let stmt = stmt.as_ref().clone();
                self.compile_subquery_expr(&stmt, &[], ctx, &[])
            }

            Expr::Union(_, _) => Err(PyQLError::Type(PyQLTypeError {
                message: "union is not valid in expression context".into(),
                position: Position { line: 0, col: 0 },
            })),

            // `array_unpack(a) intersect array_unpack(b)` — a set operation
            // between two set-valued expressions is itself a set, which in
            // expression position is the array of what it yields.
            Expr::Except(left, right) | Expr::Intersect(left, right) => {
                let op = if matches!(expr, Expr::Intersect(_, _)) {
                    super::SetOpKind::Intersect
                } else {
                    super::SetOpKind::Except
                };
                let left = self.compile_expr_ctx(left, ctx)?;
                let right = self.compile_expr_ctx(right, ctx)?;
                Ok(IrExpr::SetOp {
                    op,
                    left: Box::new(left),
                    right: Box::new(right),
                    mode: super::SetOpMode::Array,
                })
            }

            // TypeIs (`expr is Type`) is schema-exclusive — compile_type_is
            // deeply needs td/alias throughout (interface checks, __type__
            // column, alias-scoped bool expr). No free-context equivalent
            // existed before the merge (fell to the generic catch-all); this
            // is a new, clearer explicit error for that case.
            Expr::TypeIs { expr, ty } => match ctx {
                Some((td, alias)) => self.compile_type_is(expr, ty, td, alias),
                None => match expr.as_ref() {
                    Expr::Path(p) => self.compile_path_type_is(p, ty, None),
                    _ => Err(self.type_err("'is' type check is not valid in free SELECT context")),
                },
            },
        }
    }

    fn compile_expr(&mut self, expr: &Expr, td: &TypeDescriptor, alias: &str) -> Result<IrExpr, PyQLError> {
        self.compile_expr_ctx(expr, Some((td, alias)))
    }

    fn compile_free_expr(&mut self, expr: &Expr) -> Result<IrExpr, PyQLError> {
        self.compile_expr_ctx(expr, None)
    }

    /// `path is T`: whether the objects `path` reaches are of `T` or one of
    /// its subtypes, read off their own `__type__`.
    fn compile_path_type_is(
        &mut self,
        path: &ast::Path,
        ty: &ast::TypeExpr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<IrExpr, PyQLError> {
        let (ty_module, ty_name) = ty
            .as_named()
            .ok_or_else(|| self.type_err("cannot use IS with a tuple or array type"))?;
        let check_qname = match (ty_module, ctx) {
            (Some(module), _) => format!("{module}::{ty_name}"),
            (None, Some((td, _))) => format!("{}::{}", td.module, ty_name),
            (None, None) => ty_name.to_string(),
        };
        let check_td = self.resolve_type(&check_qname)?;
        let check_qname = format!("{}::{}", check_td.module, check_td.name);
        let mut type_path = path.clone();
        type_path.steps.push(ast::PathStep::Name("__type__".to_string()));
        let own_type = self.compile_expr_ctx(&Expr::Path(type_path), ctx)?;
        let implementors: Vec<String> = self
            .find_poly_implementors(&check_qname)
            .into_iter()
            .map(|implementor| implementor.type_name)
            .collect();
        let is_one_of = |own_type: IrExpr| {
            implementors
                .iter()
                .map(|implementor| {
                    IrExpr::BinOp(Box::new(IrBinOp {
                        left: own_type.clone(),
                        op: ast::BinOpKind::Eq,
                        right: IrExpr::Literal(IrLiteral::Str(implementor.clone())),
                    }))
                })
                .reduce(|left, right| {
                    IrExpr::BinOp(Box::new(IrBinOp {
                        left,
                        op: ast::BinOpKind::Or,
                        right,
                    }))
                })
                .unwrap_or(IrExpr::Literal(IrLiteral::Bool(false)))
        };
        // A path that reaches many objects yields one answer per object.
        Ok(match own_type {
            IrExpr::ArrayFromSelect(source) => match *source {
                IrArraySource::PathSelect(mut path_select) => {
                    let IrPathResult::Scalar(element, cast) = path_select.result else {
                        return Err(self.type_err("'__type__' is read as a value"));
                    };
                    path_select.result = IrPathResult::Scalar(is_one_of(element), cast);
                    IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(path_select)))
                }
                other => is_one_of(IrExpr::ArrayFromSelect(Box::new(other))),
            },
            single => is_one_of(single),
        })
    }

    fn compile_type_is(
        &mut self,
        expr: &Expr,
        ty: &ast::TypeExpr,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        let self_qname = format!("{}::{}", td.module, td.name);

        // `.listing is T`, `x is T`: the objects the path reaches are tested,
        // not the current row — through their own `__type__`.
        let reaches_other_objects = match expr {
            Expr::Path(p) if p.partial || p.steps.len() > 1 => {
                !matches!(p.steps.last(), Some(ast::PathStep::Name(n)) if n == "__type__")
            }
            Expr::Path(p) => matches!(
                p.steps.as_slice(),
                [ast::PathStep::Name(n)] if n != &td.name && n != &self_qname && self.resolve_type(n).is_err()
                    && self.resolve_name_ref(n, true).is_some()
            ),
            _ => false,
        };
        if reaches_other_objects && let Expr::Path(p) = expr {
            return self.compile_path_type_is(p, ty, Some((td, alias)));
        }

        // Determine whether `expr` refers to the current scope or a different type.
        // A 1-step absolute path matching the current td → same scope.
        let (source_qname, cross_scope) = match expr {
            Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
                if let ast::PathStep::Name(n) = &p.steps[0] {
                    if n == &td.name || n == &self_qname || self.scope_answers_to(n, &self_qname) {
                        (self_qname.clone(), false)
                    } else {
                        // Attempt to resolve as another type.
                        match self.resolve_type(n) {
                            Ok(other) => (format!("{}::{}", other.module, other.name), true),
                            Err(_) => (self_qname.clone(), false),
                        }
                    }
                } else {
                    (self_qname.clone(), false)
                }
            }
            _ => (self_qname.clone(), false),
        };

        let (ty_module, ty_name) = ty
            .as_named()
            .ok_or_else(|| self.type_err("cannot use IS with a tuple or array type"))?;
        let check_module = ty_module.unwrap_or(td.module.as_str());
        let check_qname = format!("{}::{}", check_module, ty_name);
        self.resolve_type(&check_qname)?;

        if !cross_scope {
            // Scalar bool using the current alias.
            return Ok(self.type_check_bool_expr(&source_qname, &check_qname, td, alias));
        }

        // Cross-scope: ARRAY(SELECT bool_expr FROM source_table).
        // Collect everything needed before calling fresh_alias (which needs &mut self).
        let src_alias = self.fresh_alias();
        let src_td = self.resolve_type(&source_qname)?;
        let source_table = src_td.table.clone();
        let (poly_implementors, poly_columns) = if self.is_polymorphic(src_td) {
            (
                self.find_poly_implementors(&source_qname),
                Self::poly_dml_columns(src_td),
            )
        } else {
            (vec![], vec![])
        };
        let bool_expr = self.type_check_bool_expr(&source_qname, &check_qname, src_td, &src_alias);

        let source = IrSource {
            poly: None,
            type_name: source_qname,
            table: source_table,
            alias: src_alias,
        };

        Ok(IrExpr::ArrayFromSelect(Box::new(IrArraySource::RawExpr {
            source,
            poly_implementors,
            poly_columns,
            expr: bool_expr,
        })))
    }

    /// Build the boolean `IrExpr` for `source_qname is check_qname` in the current row's scope.
    fn type_check_bool_expr(&self, source_qname: &str, check_qname: &str, td: &TypeDescriptor, alias: &str) -> IrExpr {
        if check_qname == source_qname || Self::is_or_implements(td, check_qname) {
            return IrExpr::Literal(IrLiteral::Bool(true));
        }
        if !self.is_polymorphic(td) {
            return IrExpr::Literal(IrLiteral::Bool(false));
        }
        // A row is of the checked type when its own type is that type or one
        // of its subtypes.
        self.find_poly_implementors(check_qname)
            .into_iter()
            .map(|implementor| {
                IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: alias.to_string(),
                        column: "__type__".into(),
                        pg_type: "text".into(),
                    },
                    op: crate::parse::ast::BinOpKind::Eq,
                    right: IrExpr::Literal(IrLiteral::Str(implementor.type_name)),
                }))
            })
            .reduce(|left, right| {
                IrExpr::BinOp(Box::new(IrBinOp {
                    left,
                    op: crate::parse::ast::BinOpKind::Or,
                    right,
                }))
            })
            .unwrap_or(IrExpr::Literal(IrLiteral::Bool(false)))
    }

    /// Shared lookup for a bare 1-step name: for-loop variable, CTE binding,
    /// or function parameter. Used by both `compile_path`'s schema-bound
    /// prefix and `compile_free_path`.
    ///
    /// `allow_fn_param` used to be `false` from `compile_path`, so a parameter
    /// resolved only in free context. An object-returning body like
    /// `select Item filter .rank = v` compiles its filter against a schema
    /// anchor, so it never consulted `fn_params` and rejected the bare `v` as
    /// "absolute paths are not valid in expression context" — while the same
    /// parameter in a scalar-returning body worked, which is why the gap went
    /// unnoticed. A bare one-step name can only be a variable, CTE binding or
    /// parameter in either context (a property is always written `.name`), so
    /// there is nothing here for a parameter to shadow.
    fn resolve_name_ref(&mut self, name: &str, allow_fn_param: bool) -> Option<IrExpr> {
        if self.for_vars.contains_key(name) {
            return Some(self.for_var_ref(name));
        }
        // A free-object-bound CTE (`with x := { a := 1 } select ... x ...`),
        // referenced bare with no shape to project through, has nothing to
        // expose — a free *object* needs an explicit shape to know what to
        // return (unlike a tuple/named tuple, it has no "default"
        // projection), so this collapses to an empty free object, the same
        // as `Expr::Shape`'s `is_free_cte_ref` case for `x { ... }`.
        // It also sidesteps a real problem: this CTE has no "v" column
        // (only `IrFreeExpr::Scalar` CTEs get one), so falling through to
        // the generic `IrExpr::CteRef` below would reference a column that
        // doesn't exist.
        if let Some(IrFreeExpr::FreeObject(_)) = self.cte_free_items.get(name) {
            return Some(IrExpr::NamedTuple {
                fields: vec![],
                is_free_object: true,
            });
        }
        if let Some(ir) = self.inline_bindings.get(name) {
            return Some(ir.clone());
        }
        if let Some(t) = self.cte_types.get(name) {
            // A scalar binding records its pg type here (see `cte_stmt_type`);
            // an object binding records a `module::Type` name, which is not a
            // pg type and must not be handed to type inference.
            let scalar = !t.contains("::");
            return Some(IrExpr::CteRef {
                name: self.cte_sql_name(name),
                scalar,
                pg_type: (scalar && !t.is_empty()).then(|| literal_sentinel_to_pg(t).to_string()),
            });
        }
        if allow_fn_param && let Some(pg_type) = self.fn_params.get(name) {
            return Some(IrExpr::FnParam {
                name: name.to_string(),
                pg_type: pg_type.clone(),
            });
        }
        None
    }

    /// The `(qualified type, alias)` an absolute `root.prop` should resolve
    /// against when the innermost select is `detached`.
    ///
    /// `None` in the ordinary case — the innermost select is not detached, or
    /// nothing outside it binds that type, in which case naming the type still
    /// means the current row.
    fn enclosing_anchor(&self, root: &str) -> Option<(String, String)> {
        let innermost = self.anchors.last()?;
        if !innermost.detached || !innermost.answers_to(root) {
            return None;
        }
        self.anchors
            .iter()
            .rev()
            .skip(1)
            .find(|a| a.answers_to(root))
            .map(|a| (a.qualified.clone(), a.alias.clone()))
    }

    /// Whether `root` names the scope `self_qname` stands for, beyond its own
    /// two spellings — an inherited computed names its declaring type, which
    /// is the subject there too. See `SelectAnchor::declared_on`.
    fn scope_answers_to(&self, root: &str, self_qname: &str) -> bool {
        self.anchors
            .last()
            .is_some_and(|anchor| anchor.qualified == self_qname && anchor.answers_to(root))
    }

    /// The innermost enclosing select binding `root` as its subject.
    fn outer_anchor(&self, root: &str) -> Option<(String, String)> {
        self.anchors
            .iter()
            .rev()
            .find(|a| a.answers_to(root))
            .map(|a| (a.qualified.clone(), a.alias.clone()))
    }

    fn compile_path(&mut self, p: &ast::Path, td: &TypeDescriptor, alias: &str) -> Result<IrExpr, PyQLError> {
        if !p.partial {
            if p.steps.len() == 1
                && let ast::PathStep::Name(n) = &p.steps[0]
            {
                if let Some(ir) = self.resolve_name_ref(n, true) {
                    return Ok(ir);
                }
                // __type__ without a leading dot still means the current object's type.
                if n == "__type__" {
                    return Ok(if self.is_polymorphic(td) {
                        IrExpr::ColumnRef {
                            alias: alias.to_string(),
                            column: "__type__".to_string(),
                            pg_type: "text".to_string(),
                        }
                    } else {
                        IrExpr::Literal(IrLiteral::Str(format!("{}::{}", td.module, td.name)))
                    });
                }
            }
            // Enum member access: `default::Gender.Female`
            if p.steps.len() == 2
                && let [ast::PathStep::Name(type_ref), ast::PathStep::Name(variant)] = p.steps.as_slice()
                && self.resolve_enum(type_ref).is_some()
            {
                return self.compile_enum_access(type_ref, variant);
            }
            // `root.field1.field2...` where `root` is a WITH-bound free object.
            if let Some(resolved) = self.resolve_cte_path(p) {
                return resolved;
            }
            // `root.field1.field2...` where `root` is a WITH-bound *schema
            // object* (`with person := (select detached Person filter ...)
            // select ... person.company.name ...`). `compile_path_select`
            // already treats a CTE-bound root exactly like a real type name
            // (it checks `cte_types` before falling back to `resolve_type`,
            // via the `@cte:` source-table sentinel — see its own doc
            // comment and `compile_expr_as_path_select`'s sibling case for
            // `Detached`), so it already implements the *entire* general
            // path-traversal feature set here — forward links, multilinks,
            // backlinks, junction-backed links, nested tuple field access,
            // "did you mean" on a typo'd name — not just a one-property
            // special case. Wrapping its result as `IrExpr::PathSubquery`
            // (the same vehicle `Detached` uses for a type-rooted path in
            // expression position) turns the whole traversal into one
            // correlated scalar/id expression.
            if p.steps.len() > 1
                && let ast::PathStep::Name(root) = &p.steps[0]
                && self
                    .cte_types
                    .get(root.as_str())
                    .map(|t| t.contains("::"))
                    .unwrap_or(false)
            {
                let full_path = ast::Path {
                    steps: p.steps.clone(),
                    partial: false,
                };
                let synthetic = ast::SelectStmt {
                    result: Expr::Path(full_path.clone()),
                    filter: None,
                    order_by: vec![],
                    offset: None,
                    limit: None,
                    lock: None,
                };
                let ps = self.compile_path_select(&synthetic, &full_path, &[], false)?;
                return Ok(IrExpr::PathSubquery(Box::new(ps)));
            }
            // `__new__.prop` / `__old__.prop` — the inserted/updated/deleted
            // row a trigger handler is compiled against (see
            // `compile_trigger_handler`, which populates `special_anchors`
            // per the trigger's declared `on` events). Same rewrite-and-
            // recurse trick as the `TypeName.prop` case below, just handing
            // `compile_path` the anchor's own alias ("NEW"/"OLD") instead
            // of `td`'s. Outside trigger-handler compilation (or for the
            // anchor the current trigger's events don't legally bind —
            // e.g. `__old__` in an Insert-only trigger) `special_anchors`
            // is empty/missing that entry, so this falls through to the
            // explicit error below rather than the generic "absolute
            // paths" message: `__old__`/`__new__` cannot be used in
            // this expression.
            if p.steps.len() > 1
                && let ast::PathStep::Name(root) = &p.steps[0]
                && (root == "__new__" || root == "__old__")
            {
                if let Some((anchor_td, anchor_alias)) = self.special_anchors.get(root).cloned() {
                    let relative = ast::Path {
                        steps: p.steps[1..].to_vec(),
                        partial: true,
                    };
                    return self.compile_path(&relative, anchor_td, &anchor_alias);
                }
                return Err(PyQLError::Resolution(PyQLResolutionError::UnknownField(
                    PyQLUnknownFieldError {
                        message: format!("{root} cannot be used in this expression"),
                        position: Position { line: 0, col: 0 },
                    },
                )));
            }
            // `__subject__` is the row a constraint is checked against, which
            // is the same row a relative path reads.
            if p.steps.len() > 1 && matches!(&p.steps[0], ast::PathStep::Name(root) if root == "__subject__") {
                let relative = ast::Path {
                    steps: p.steps[1..].to_vec(),
                    partial: true,
                };
                return self.compile_path(&relative, td, alias);
            }
            // Absolute path rooted at the current td: `TypeName.prop` inside a schema-bound
            // expression (e.g. the value side of a BinOp in compile_expr_as_path_select).
            // Rewrite to a relative path and compile normally.
            if p.steps.len() > 1
                && let ast::PathStep::Name(root) = &p.steps[0]
            {
                let qualified = format!("{}::{}", td.module, td.name);
                if *root == td.name || *root == qualified {
                    let relative = ast::Path {
                        steps: p.steps[1..].to_vec(),
                        partial: true,
                    };
                    // Inside a `detached` select, naming its own type means the
                    // enclosing select's row — that is what makes an anti-join
                    // compare two different rows.
                    if let Some((outer_qualified, outer_alias)) = self.enclosing_anchor(root) {
                        let outer_td = self.resolve_type(&outer_qualified)?.clone();
                        return self.compile_path(&relative, &outer_td, &outer_alias);
                    }
                    return self.compile_path(&relative, td, alias);
                }
                // A prefix naming a type an *enclosing* select already binds —
                // `select Font { styles: { font := Font.id } }`. EdgeQL factors
                // such a prefix out to the scope that binds it, so it reads that
                // row rather than every row of the type.
                if let Some((outer_qualified, outer_alias)) = self.outer_anchor(root) {
                    let relative = ast::Path {
                        steps: p.steps[1..].to_vec(),
                        partial: true,
                    };
                    let outer_td = self.resolve_type(&outer_qualified)?.clone();
                    return self.compile_path(&relative, &outer_td, &outer_alias);
                }
            }
            // `membership.account.id` — a walk off a for-loop variable in
            // expression position. `compile_path_select` already knows to
            // start such a walk from the row the variable holds, so this is
            // that walk read as one subquery.
            if let Some(ast::PathStep::Name(var)) = p.steps.first()
                && p.steps.len() > 1
                && self.for_var_types.contains_key(var)
                && !matches!(p.steps[1], ast::PathStep::TypeIntersection(_))
            {
                let synthetic = ast::SelectStmt {
                    result: Expr::Path(p.clone()),
                    filter: None,
                    order_by: vec![],
                    offset: None,
                    limit: None,
                    lock: None,
                };
                let ps = self.compile_path_select(&synthetic, p, &[], false)?;
                return Ok(IrExpr::PathSubquery(Box::new(ps)));
            }
            // `o[is Organization]` on a for-loop variable — the narrowing is
            // a filter, not a traversal: the row is read from the narrowed
            // type's own table by the key the variable holds, so a variable
            // bound to something else yields nothing, as it should.
            // `line[is BrandOrderLineItem].brand` — the narrowing picks the row
            // out of the narrowed type's own table, and the walk continues from
            // there. Without the tail this is the row itself, handled below.
            if let [
                ast::PathStep::Name(var),
                ast::PathStep::TypeIntersection(type_ref),
                rest @ ..,
            ] = p.steps.as_slice()
                && !rest.is_empty()
                && self.for_var_types.contains_key(var)
            {
                let type_name = match &type_ref.module {
                    Some(m) => format!("{}::{}", m, type_ref.name),
                    None => type_ref.name.clone(),
                };
                let narrowed = self.resolve_type(&type_name)?;
                let mut steps = vec![ast::PathStep::Name(format!("{}::{}", narrowed.module, narrowed.name))];
                steps.extend(rest.iter().cloned());
                let rooted = ast::Path { steps, partial: false };
                let synthetic = ast::SelectStmt {
                    result: Expr::Path(rooted.clone()),
                    filter: None,
                    order_by: vec![],
                    offset: None,
                    limit: None,
                    lock: None,
                };
                let mut ps = self.compile_path_select(&synthetic, &rooted, &[], false)?;
                let correlation = IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: ps.root.alias.clone(),
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    },
                    op: ast::BinOpKind::Eq,
                    right: self.for_var_ref(var),
                }));
                ps.filter = and_conditions(ps.filter, vec![correlation]);
                return Ok(IrExpr::PathSubquery(Box::new(ps)));
            }
            if let [ast::PathStep::Name(var), ast::PathStep::TypeIntersection(type_ref)] = p.steps.as_slice()
                && self.for_var_types.contains_key(var)
            {
                let type_name = match &type_ref.module {
                    Some(m) => format!("{}::{}", m, type_ref.name),
                    None => type_ref.name.clone(),
                };
                let narrowed = self.resolve_type(&type_name)?;
                let narrowed_alias = self.fresh_alias();
                let source = IrSource {
                    poly: self.poly_fanout_for(&format!("{}::{}", narrowed.module, narrowed.name)),
                    type_name: format!("{}::{}", narrowed.module, narrowed.name),
                    table: narrowed.table.clone(),
                    alias: narrowed_alias.clone(),
                };
                let filter = IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: narrowed_alias,
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    },
                    op: ast::BinOpKind::Eq,
                    right: self.for_var_ref(var),
                }));
                return Ok(IrExpr::Subquery(Box::new(IrSelect::schema_bound(
                    source,
                    Self::pk_returning(narrowed),
                    Some(filter),
                ))));
            }
            return Err(PyQLError::Type(PyQLTypeError {
                message: "absolute paths are not valid in expression context; use .name".into(),
                position: Position { line: 0, col: 0 },
            }));
        }

        // A bare `@prop` — the junction row of the multi-link whose own
        // modifiers are being compiled. Read from the junction alias the
        // emitter puts in scope there ("jt"), the same one a `@prop` in the
        // nested shape reads.
        if p.partial
            && let [ast::PathStep::LinkProp(prop_name)] = p.steps.as_slice()
        {
            return self.compile_link_prop_ref(prop_name);
        }

        // Type intersection in expression: [is Type].name — scalar subquery
        if p.partial && matches!(p.steps.first(), Some(ast::PathStep::TypeIntersection(_))) {
            return self.compile_type_intersection_expr(&p.steps, td, alias);
        }

        // `.<assessment[is brand::AssessmentRespondent]` — a backlink read as a
        // value, with or without a narrowing. No column holds it, so it is the
        // traversal as a correlated subquery; the builders below only know
        // forward links and reject the intersection outright.
        if p.partial && matches!(p.steps.first(), Some(ast::PathStep::Backlink(_))) {
            return self.compile_partial_path_as_subquery(p, td, alias);
        }
        // `.ca.name` where `ca := a if cond else b` — the condition does not
        // depend on which branch is taken, so the field access distributes
        // over both and the walk happens inside each. Left whole, the walk
        // builder has no column to traverse through.
        if p.partial
            && p.steps.len() > 1
            && let Some(ast::PathStep::Name(first)) = p.steps.first()
            && let Some(Expr::IfElse(ie)) = self
                .active_declared_pointers
                .iter()
                .find(|d| path_leaf(&d.path).is_ok_and(|name| name == first))
                .and_then(|d| d.compexpr.clone())
        {
            let extend = |branch: &Expr| match branch {
                Expr::Path(bp) => {
                    let mut steps = bp.steps.clone();
                    steps.extend(p.steps[1..].iter().cloned());
                    Some(Expr::Path(ast::Path {
                        steps,
                        partial: bp.partial,
                    }))
                }
                // `(select .<brand[is T] … limit 1).priority` — the walk's
                // remaining steps projected off the sub-select.
                Expr::SubQuery(_) => p.steps[1..].iter().try_fold(branch.clone(), |expr, step| match step {
                    ast::PathStep::Name(field) => Some(Expr::FieldAccess {
                        expr: Box::new(expr),
                        field: field.clone(),
                    }),
                    _ => None,
                }),
                // Nothing to walk from, so nothing is reached.
                Expr::Set(items) if items.is_empty() => Some(Expr::Set(vec![])),
                Expr::TypeCast(cast) if matches!(&cast.expr, Expr::Set(items) if items.is_empty()) => {
                    Some(Expr::Set(vec![]))
                }
                _ => None,
            };
            if let (Some(if_expr), Some(else_expr)) = (extend(&ie.if_expr), extend(&ie.else_expr)) {
                let distributed = Expr::IfElse(Box::new(ast::IfElse {
                    condition: ie.condition.clone(),
                    if_expr,
                    else_expr,
                }));
                return self.compile_expr(&distributed, td, alias);
            }
        }

        // A walk that ends in a type intersection (`exists .provider[is
        // account::Individual]`) narrows to objects rather than reading a
        // pointer, so there is no trailing column for the two-step form to
        // read and it goes the way a longer traversal already does.
        let narrows_last = matches!(p.steps.last(), Some(ast::PathStep::TypeIntersection(_)));

        if p.steps.len() == 2 && !narrows_last {
            return self.compile_path_2step(p, td, alias);
        }

        // Three or more steps: no single column to read, so the whole
        // traversal becomes one correlated subquery.
        if p.steps.len() != 1 {
            return self.compile_partial_path_as_subquery(p, td, alias);
        }

        let pointer_name = match &p.steps[0] {
            ast::PathStep::Name(n) => n.as_str(),
            _ => {
                return Err(PyQLError::Type(PyQLTypeError {
                    message: "type intersections are not valid in expression context".into(),
                    position: Position { line: 0, col: 0 },
                }));
            }
        };

        // __type__ as an expression: for polymorphic (interface) types, read from the
        // inline union column; for concrete types, emit the static qualified name.
        if pointer_name == "__type__" {
            return Ok(if self.is_polymorphic(td) {
                IrExpr::ColumnRef {
                    alias: alias.to_string(),
                    column: "__type__".to_string(),
                    pg_type: "text".to_string(),
                }
            } else {
                IrExpr::Literal(IrLiteral::Str(format!("{}::{}", td.module, td.name)))
            });
        }

        if let Some(prop) = Self::resolve_property(td, pointer_name) {
            return Ok(IrExpr::ColumnRef {
                alias: alias.to_string(),
                column: prop.name.clone(),
                pg_type: prop.pg_type.clone(),
            });
        }

        if let Some(link) = Self::resolve_link(td, pointer_name) {
            if link.is_junction_backed() {
                return self.junction_target_id_expr(td, link, alias);
            }
            // FK column reference (uuid) — e.g. `.company` → `t0."company_id"`
            return Ok(IrExpr::ColumnRef {
                alias: alias.to_string(),
                column: format!("{}_id", link.name),
                pg_type: "uuid".to_string(),
            });
        }

        // Schema-defined computed pointer: inline the expression in place.
        if let Some(cd) = self.resolve_computed(td, pointer_name) {
            let expr_ast = crate::parse::parse_pointer_expr(&cd.expression).map_err(PyQLError::Syntax)?;
            return self.compile_expr(&expr_ast, td, alias);
        }

        // `o in .organizations` — a multi-link read as a value is the set of
        // rows on the other side, which no column holds; the same traversal a
        // longer walk already becomes. Only property, link and computed were
        // resolved here, so a bare multi-link reported itself as unknown —
        // while the suggester, which does know them, offered the name back.
        if Self::resolve_multilink(td, pointer_name).is_some() {
            return self.compile_partial_path_as_subquery(p, td, alias);
        }

        // `select (select T { a := … }) filter .a = …` — a pointer the shape
        // in scope declared is on no type, so it is read as the expression it
        // was written as. The shape route already resolves these; a filter or
        // order-by naming one arrives here instead.
        if let Some(expr) = self
            .active_declared_pointers
            .iter()
            .find(|d| path_leaf(&d.path).is_ok_and(|n| n == pointer_name))
            .and_then(|d| d.compexpr.clone())
        {
            return self.compile_expr(&expr, td, alias);
        }

        Err(self.field_err(pointer_name, &format!("{}::{}", td.module, td.name)))
    }

    /// Free-context counterpart of `compile_path` — no schema type/alias in
    /// scope, so only for-loop variables, CTE bindings, function parameters,
    /// and enum member access (`default::Gender.Female`) are resolvable;
    /// anything property/link-shaped is a hard error.
    fn compile_free_path(&mut self, p: &ast::Path) -> Result<IrExpr, PyQLError> {
        if p.partial {
            // A WITH binding inside a computed pointer or a nested SELECT is
            // compiled without a type in scope, but `.name` there still means
            // the innermost enclosing set — the one the anchor stack holds.
            if let Some((qualified, alias)) = self.anchors.last().map(|a| (a.qualified.clone(), a.alias.clone())) {
                let td = self.resolve_type(&qualified)?;
                return self.compile_path(p, td, &alias);
            }
            return Err(self.type_err(
                "property reference (.name) is not valid in free SELECT; \
                 use a schema-bound SELECT instead",
            ));
        }
        if p.steps.len() == 2
            && let [ast::PathStep::Name(type_ref), ast::PathStep::Name(variant)] = p.steps.as_slice()
            && self.resolve_enum(type_ref).is_some()
        {
            return self.compile_enum_access(type_ref, variant);
        }
        // `root.field1.field2...` where `root` is a WITH-bound free object
        // (any length >= 2, including chains through nested free objects).
        if let Some(resolved) = self.resolve_cte_path(p) {
            return resolved;
        }
        if p.steps.len() == 1
            && let ast::PathStep::Name(n) = &p.steps[0]
            && let Some(ir) = self.resolve_name_ref(n, true)
        {
            return Ok(ir);
        }
        // `assessment.current_question` in a free shape's field or filter — a
        // walk off an object binding. It is the same traversal a bound select
        // makes, read back as one subquery; there is no enclosing row to
        // resolve it against, and nothing else here knows a binding can root a
        // path.
        if !p.partial
            && p.steps.len() > 1
            && let Some(ast::PathStep::Name(root)) = p.steps.first()
            && self.cte_object_type(root).is_some()
        {
            let synthetic = ast::SelectStmt {
                result: Expr::Path(p.clone()),
                filter: None,
                order_by: vec![],
                offset: None,
                limit: None,
                lock: None,
            };
            let ps = self.compile_path_select(&synthetic, p, &[], false)?;
            // A walk made only of forward single links does not multiply rows,
            // so its cardinality is the root binding's. Treating every join as
            // widening made `(select T filter .id = $x).link.prop` a
            // one-element set where Gel gives the value itself.
            let widens = ps.joins.iter().any(|join| !matches!(join, IrPathJoin::Single { .. }));
            let root_is_multi = self.multi_row_ctes.contains(root.as_str());
            let multi = matches!(ps.result, IrPathResult::Scalar(..)) && (widens || root_is_multi);
            return Ok(if multi {
                IrExpr::ArrayFromSelect(Box::new(IrArraySource::PathSelect(Box::new(ps))))
            } else {
                IrExpr::PathSubquery(Box::new(ps))
            });
        }
        Err(self.type_err("expression is not valid in free SELECT context"))
    }

    fn compile_path_2step(&mut self, p: &ast::Path, td: &TypeDescriptor, alias: &str) -> Result<IrExpr, PyQLError> {
        let link_name = match &p.steps[0] {
            ast::PathStep::Name(n) => n.as_str(),
            _ => {
                return Err(PyQLError::Type(PyQLTypeError {
                    message: "type intersections are not valid in expression context".into(),
                    position: Position { line: 0, col: 0 },
                }));
            }
        };
        let pointer_name = match &p.steps[1] {
            ast::PathStep::Name(n) => n.as_str(),
            _ => {
                return Err(PyQLError::Type(PyQLTypeError {
                    message: "type intersections are not valid in expression context".into(),
                    position: Position { line: 0, col: 0 },
                }));
            }
        };

        if let Some(link) = Self::resolve_link(td, link_name) {
            if pointer_name == "id" {
                if link.is_junction_backed() {
                    return self.junction_target_id_expr(td, link, alias);
                }
                return Ok(IrExpr::ColumnRef {
                    alias: alias.to_string(),
                    column: format!("{}_id", link_name),
                    pg_type: "uuid".to_string(),
                });
            }
            let target_td = self.resolve_type(&link.target)?;
            if let Some(prop) = Self::resolve_property(target_td, pointer_name) {
                let ft_alias = self.fresh_alias();
                let target_id_expr = if link.is_junction_backed() {
                    self.junction_target_id_expr(td, link, alias)?
                } else {
                    IrExpr::ColumnRef {
                        alias: alias.to_string(),
                        column: format!("{}_id", link_name),
                        pg_type: "uuid".to_string(),
                    }
                };
                return Ok(IrExpr::Subquery(Box::new(IrSelect::schema_bound(
                    IrSource {
                        poly: None,
                        type_name: format!("{}::{}", target_td.module, target_td.name),
                        table: target_td.table.clone(),
                        alias: ft_alias.clone(),
                    },
                    vec![IrShapePointer::Scalar(IrScalarPointer {
                        implicit_id: false,
                        marker_offset: None,
                        alias: prop.name.clone(),
                        column: prop.name.clone(),
                        pg_type: prop.pg_type.clone(),
                        tuple_shape: self.resolve_property_tuple_shape(prop),
                    })],
                    Some(IrExpr::BinOp(Box::new(IrBinOp {
                        left: IrExpr::ColumnRef {
                            alias: ft_alias.clone(),
                            column: "id".to_string(),
                            pg_type: "uuid".to_string(),
                        },
                        op: ast::BinOpKind::Eq,
                        right: target_id_expr,
                    }))),
                ))));
            }
            // Not a stored column on the target — a computed pointer, or a
            // further link. The general traversal builder resolves both.
            return self.compile_partial_path_as_subquery(p, td, alias);
        }

        // A multi-link path stands for a set of values. Inside a comparison
        // it has already been rewritten to an EXISTS (`try_multilink_exists`,
        // which runs first); everywhere else it is an array.
        if Self::resolve_multilink(td, link_name).is_some() {
            return self.compile_partial_path_as_subquery(p, td, alias);
        }

        // Not a stored pointer at all — a computed one, most likely, which
        // the general builder can traverse through by splicing in the path
        // it stands for. It raises the same "no link or property" error this
        // used to when the name really is unknown (which is what made a
        // computed head read as `has no link or property 'x'. Did you mean
        // 'x'?` — the suggester could see it, the resolver couldn't).
        self.compile_partial_path_as_subquery(p, td, alias)
    }

    // ── Backlink compilation ─────────────────────────────────────────────────────

    /// Detect a backlink path on either side of a BinOp and compile as EXISTS.
    fn try_backlink_exists(
        &mut self,
        b: &ast::BinOp,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<Option<IrExpr>, PyQLError> {
        use ast::PathStep;
        fn is_backlink(p: &ast::Path) -> bool {
            p.partial && matches!(p.steps.first(), Some(PathStep::Backlink(_)))
        }
        let (path_steps, value_ast, flip) = if let Expr::Path(p) = &b.left {
            if is_backlink(p) {
                (p.steps.as_slice(), &b.right, false)
            } else {
                return Ok(None);
            }
        } else if let Expr::Path(p) = &b.right {
            if is_backlink(p) {
                (p.steps.as_slice(), &b.left, true)
            } else {
                return Ok(None);
            }
        } else {
            return Ok(None);
        };
        let value_expr = self.compile_expr(value_ast, td, alias)?;
        let current_qname = format!("{}::{}", td.module, td.name);
        let exists = self.compile_backlink_as_exists(
            path_steps,
            Some((b.op.clone(), value_expr, flip)),
            &current_qname,
            alias,
        )?;
        Ok(Some(exists))
    }

    /// Compile a path `[Backlink(name), TypeIntersect(type), ...rest]` into EXISTS.
    /// `comparison` is `Some((op, value_expr, flip))` when used in a comparison filter.
    /// `current_qname` is the fully-qualified name of the object type being filtered.
    fn compile_backlink_as_exists(
        &mut self,
        steps: &[ast::PathStep],
        comparison: Option<(ast::BinOpKind, IrExpr, bool)>,
        current_qname: &str,
        alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        use ast::PathStep;

        let backlink_name = match steps.first() {
            Some(PathStep::Backlink(n)) => n.clone(),
            _ => return Err(self.type_err("internal: expected backlink step")),
        };
        // Without a type intersection the backlink spans every type that
        // declares the link at this target, so the row qualifies if any one of
        // them points at it.
        let Some(PathStep::TypeIntersection(type_ref)) = steps.get(1) else {
            // Without a type intersection the backlink spans every type that
            // declares the link at this target.
            return self.backlink_exists_over_owners(
                None,
                &backlink_name,
                &steps[1..],
                comparison,
                current_qname,
                alias,
            );
        };

        let type_name = match &type_ref.module {
            Some(m) => format!("{}::{}", m, type_ref.name),
            None => type_ref.name.clone(),
        };
        let target_td = self.resolve_type(&type_name)?;
        if self.declares_backlink(target_td, &backlink_name, current_qname) {
            return self.backlink_exists_for_owner(
                target_td,
                &backlink_name,
                &steps[2..],
                comparison,
                current_qname,
                alias,
            );
        }
        // The intersection narrows to an interface or mixin that does not
        // declare the link itself — its implementors do, and a row of one of
        // them satisfies `[is ThatType]` all the same. Qualified, because that
        // is how an implementor names what it implements.
        let narrow_to = format!("{}::{}", target_td.module, target_td.name);
        self.backlink_exists_over_owners(
            Some(&narrow_to),
            &backlink_name,
            &steps[2..],
            comparison,
            current_qname,
            alias,
        )
    }

    /// The type that declares the link a backlink narrowed to `owner_td`
    /// reads through.
    fn backlink_owner(
        &self,
        owner_td: &'a TypeDescriptor,
        backlink_name: &str,
        current_qname: &str,
    ) -> Result<&'a TypeDescriptor, PyQLError> {
        // `.<passkeys[is account::Account]` — the intersection narrows what
        // comes back, and the link itself may be declared further down: here
        // `passkeys` is Individual's, and an Individual is an Account. So the
        // owner is the concrete type that actually declares it, the same way
        // `backlink_exists_over_owners` resolves one.
        Ok(if self.declares_backlink(owner_td, backlink_name, current_qname) {
            owner_td
        } else {
            // Qualified, because that is how a type records the interfaces it
            // implements; the query may well have written the bare name.
            let narrowed = format!("{}::{}", owner_td.module, owner_td.name);
            let declaring: Vec<&'a TypeDescriptor> = self
                .schema
                .types
                .iter()
                .filter(|t| !t.abstract_ && Self::is_or_implements(t, &narrowed))
                .filter(|t| self.declares_backlink(t, backlink_name, current_qname))
                .collect();
            let declaring = Self::without_inherited_owners(declaring);
            match declaring.as_slice() {
                [only] => only,
                [] => owner_td,
                several => {
                    return Err(self.type_err(&format!(
                        "'{backlink_name}' pointing to {current_qname} is declared by {} types under \
                         {narrowed} ({}), so a backlink narrowed to it has no single source to read \
                         — narrow to one of them instead",
                        several.len(),
                        several
                            .iter()
                            .map(|t| format!("{}::{}", t.module, t.name))
                            .collect::<Vec<_>>()
                            .join(", "),
                    )));
                }
            }
        })
    }

    /// Whether a backlink narrowed to `owner_td` reaches at most one object,
    /// which it does through an exclusive link.
    fn backlink_is_single(&self, owner_td: &'a TypeDescriptor, backlink_name: &str, current_qname: &str) -> bool {
        let Ok(owner) = self.backlink_owner(owner_td, backlink_name, current_qname) else {
            return false;
        };
        owner
            .links
            .iter()
            .any(|l| l.name == backlink_name && l.is_exclusive && self.link_target_reaches(&l.target, current_qname))
            || owner.multilinks.iter().any(|ml| {
                ml.name == backlink_name && ml.is_exclusive && self.link_target_reaches(&ml.target, current_qname)
            })
    }

    /// Does `td` declare the link a backlink names, pointing at the type the
    /// traversal is standing on?
    fn declares_backlink(&self, td: &TypeDescriptor, backlink_name: &str, current_qname: &str) -> bool {
        td.links
            .iter()
            .any(|l| l.name == backlink_name && self.link_target_reaches(&l.target, current_qname))
            || td
                .multilinks
                .iter()
                .any(|ml| ml.name == backlink_name && self.link_target_reaches(&ml.target, current_qname))
    }

    /// EXISTS over every type that declares the backlink's link, OR-ed
    /// together: a row qualifies if any one of them points at it. `narrow_to`
    /// keeps only the types that satisfy an `[is …]` the path asked for.
    #[allow(clippy::too_many_arguments)]
    /// Drops the owners that only inherit the link from another owner in the
    /// list: reading the base already reads its subtypes' rows.
    fn without_inherited_owners(owners: Vec<&'a TypeDescriptor>) -> Vec<&'a TypeDescriptor> {
        let qnames: Vec<String> = owners.iter().map(|t| format!("{}::{}", t.module, t.name)).collect();
        owners
            .into_iter()
            .filter(|t| !t.bases.iter().any(|base| qnames.contains(base)))
            .collect()
    }

    fn backlink_exists_over_owners(
        &mut self,
        narrow_to: Option<&str>,
        backlink_name: &str,
        rest: &[ast::PathStep],
        comparison: Option<(ast::BinOpKind, IrExpr, bool)>,
        current_qname: &str,
        alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        let schema = self.schema;
        let owners: Vec<&'a TypeDescriptor> = schema
            .types
            .iter()
            .filter(|t| !t.abstract_)
            .filter(|t| narrow_to.is_none_or(|q| Self::is_or_implements(t, q)))
            .filter(|t| self.declares_backlink(t, backlink_name, current_qname))
            .collect();
        let owners = Self::without_inherited_owners(owners);
        if owners.is_empty() {
            return Err(self.type_err(&match narrow_to {
                Some(q) => format!("type {q} has no link or multi-link '{backlink_name}' pointing to {current_qname}"),
                None => format!("no type has a link or multi-link '{backlink_name}' pointing to {current_qname}"),
            }));
        }
        let mut combined: Option<IrExpr> = None;
        for owner_td in owners {
            let one = self.backlink_exists_for_owner(
                owner_td,
                backlink_name,
                rest,
                comparison.clone(),
                current_qname,
                alias,
            )?;
            combined = Some(match combined {
                None => one,
                Some(previous) => IrExpr::BinOp(Box::new(IrBinOp {
                    left: previous,
                    op: ast::BinOpKind::Or,
                    right: one,
                })),
            });
        }
        Ok(combined.expect("owners is non-empty"))
    }

    /// Is `td` the type `qname` names, or one that implements/extends it?
    fn is_or_implements(td: &TypeDescriptor, qname: &str) -> bool {
        format!("{}::{}", td.module, td.name) == qname
            || td.interfaces.iter().any(|i| i == qname)
            || td.parents.iter().any(|p| p == qname)
            || td.bases.iter().any(|b| b == qname)
    }

    /// A concrete type another concrete type extends (`BrandAddon`, which
    /// `BrandAddonBundle` extends). Its own table holds only its own rows, so
    /// reading the type means reading the subtypes' tables beside it.
    fn has_subtypes(&self, td: &TypeDescriptor) -> bool {
        let qname = format!("{}::{}", td.module, td.name);
        !td.abstract_ && self.schema.types.iter().any(|t| t.bases.contains(&qname))
    }

    /// A plain `@pylon.abstract` mixin, materialised as nothing at all.
    /// Unlike an interface it backs no view, so naming its table reaches a
    /// relation that does not exist.
    fn backs_no_relation(td: &TypeDescriptor) -> bool {
        td.abstract_ && !td.materialized
    }

    /// See `IrOutput::subtype_fanouts`.
    fn subtype_fanouts(&self) -> HashMap<(String, String), IrPolyFanout> {
        self.schema
            .types
            .iter()
            .filter(|t| self.has_subtypes(t) || Self::backs_no_relation(t))
            .filter_map(|t| {
                let fanout = self.poly_fanout_for(&format!("{}::{}", t.module, t.name))?;
                Some(((t.module.clone(), t.table.clone()), fanout))
            })
            .collect()
    }

    /// Whether the type's rows come from more than one table — an interface,
    /// an abstract type (which has no table of its own), or a concrete type
    /// with subtypes — and so are read through the union that carries each
    /// row's own `__type__`.
    fn is_polymorphic(&self, td: &TypeDescriptor) -> bool {
        td.abstract_ || self.has_subtypes(td)
    }

    /// One owner type's half of `compile_backlink_as_exists`: EXISTS over the
    /// rows of `target_td` that link back to `alias`, plus whatever the
    /// remaining path steps and comparison require of them.
    #[allow(clippy::too_many_arguments)]
    fn backlink_exists_for_owner(
        &mut self,
        target_td: &'a TypeDescriptor,
        backlink_name: &str,
        rest: &[ast::PathStep],
        comparison: Option<(ast::BinOpKind, IrExpr, bool)>,
        current_qname: &str,
        alias: &str,
    ) -> Result<IrExpr, PyQLError> {
        let backlink_name = backlink_name.to_string();
        let target_qname = format!("{}::{}", target_td.module, target_td.name);
        let target_table = target_td.table.clone();
        let t_alias = self.fresh_alias();

        // Backlink source is either a single (FK) link or a multi-link
        // (junction table) on the target type — mirrors the equivalent
        // link-vs-multilink resolution the general shape-position backlink
        // code already does (see the `PathStep::Backlink` handling above in
        // `compile_path_expr`/similar), which this filter/exists-specific
        // path previously didn't: it only ever checked `target_td.links`,
        // so a self-referential-multilink backlink like `Person.friends`
        // failed to compile here even though it worked in a shape position.
        let join_cond = if let Some(l) = target_td
            .links
            .iter()
            .find(|l| l.name == backlink_name && self.link_target_reaches(&l.target, current_qname))
        {
            if l.is_junction_backed() {
                // Same junction-table EXISTS shape the multi-link branch
                // below uses — no direct FK column, since this link is
                // itself junction-backed.
                let (jt_table, jt_module, jt_owner_col, jt_current_col, _) = self.link_junction_info(target_td, l)?;
                let jt_alias = self.fresh_alias();
                IrExpr::UnaryOp(Box::new(IrUnaryOp {
                    op: ast::UnaryOpKind::Exists,
                    operand: IrExpr::Subquery(Box::new(IrSelect::schema_bound(
                        IrSource {
                            poly: None,
                            type_name: format!("{}::__jt__", jt_module),
                            table: jt_table,
                            alias: jt_alias.clone(),
                        },
                        vec![],
                        Some(IrExpr::BinOp(Box::new(IrBinOp {
                            left: IrExpr::BinOp(Box::new(IrBinOp {
                                left: IrExpr::ColumnRef {
                                    alias: jt_alias.clone(),
                                    column: jt_owner_col,
                                    pg_type: "uuid".to_string(),
                                },
                                op: ast::BinOpKind::Eq,
                                right: IrExpr::ColumnRef {
                                    alias: t_alias.clone(),
                                    column: "id".to_string(),
                                    pg_type: "uuid".to_string(),
                                },
                            })),
                            op: ast::BinOpKind::And,
                            right: IrExpr::BinOp(Box::new(IrBinOp {
                                left: IrExpr::ColumnRef {
                                    alias: jt_alias,
                                    column: jt_current_col,
                                    pg_type: "uuid".to_string(),
                                },
                                op: ast::BinOpKind::Eq,
                                right: IrExpr::ColumnRef {
                                    alias: alias.to_string(),
                                    column: "id".to_string(),
                                    pg_type: "uuid".to_string(),
                                },
                            })),
                        }))),
                    ))),
                }))
            } else {
                let fk_col = format!("{}_id", backlink_name);
                // Join condition: target.fk_col = current.id
                IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: t_alias.clone(),
                        column: fk_col,
                        pg_type: "uuid".to_string(),
                    },
                    op: ast::BinOpKind::Eq,
                    right: IrExpr::ColumnRef {
                        alias: alias.to_string(),
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    },
                }))
            }
        } else if let Some(ml) = target_td
            .multilinks
            .iter()
            .find(|ml| ml.name == backlink_name && self.link_target_reaches(&ml.target, current_qname))
            .cloned()
        {
            // Junction row connects t_alias (as the multi-link's owner/
            // "source") to the current row (as its "target") — no direct FK
            // column on either table, so this is a nested EXISTS over the
            // junction table rather than a simple column comparison.
            let (jt_table, jt_module, _, _, _) = self.multilink_junction_info(target_td, &ml)?;
            let jt_alias = self.fresh_alias();
            IrExpr::UnaryOp(Box::new(IrUnaryOp {
                op: ast::UnaryOpKind::Exists,
                operand: IrExpr::Subquery(Box::new(IrSelect::schema_bound(
                    IrSource {
                        poly: None,
                        type_name: format!("{}::__jt__", jt_module),
                        table: jt_table,
                        alias: jt_alias.clone(),
                    },
                    vec![],
                    Some(IrExpr::BinOp(Box::new(IrBinOp {
                        left: IrExpr::BinOp(Box::new(IrBinOp {
                            left: IrExpr::ColumnRef {
                                alias: jt_alias.clone(),
                                column: "source".to_string(),
                                pg_type: "uuid".to_string(),
                            },
                            op: ast::BinOpKind::Eq,
                            right: IrExpr::ColumnRef {
                                alias: t_alias.clone(),
                                column: "id".to_string(),
                                pg_type: "uuid".to_string(),
                            },
                        })),
                        op: ast::BinOpKind::And,
                        right: IrExpr::BinOp(Box::new(IrBinOp {
                            left: IrExpr::ColumnRef {
                                alias: jt_alias,
                                column: "target".to_string(),
                                pg_type: "uuid".to_string(),
                            },
                            op: ast::BinOpKind::Eq,
                            right: IrExpr::ColumnRef {
                                alias: alias.to_string(),
                                column: "id".to_string(),
                                pg_type: "uuid".to_string(),
                            },
                        })),
                    }))),
                ))),
            }))
        } else {
            return Err(PyQLError::Type(PyQLTypeError {
                message: format!(
                    "type {} has no link or multi-link '{}' pointing to {}",
                    target_qname, backlink_name, current_qname,
                ),
                position: Position { line: 0, col: 0 },
            }));
        };

        let tail_cond = self.compile_backlink_tail(rest, comparison, &target_qname, &t_alias)?;

        let filter = match tail_cond {
            Some(tc) => IrExpr::BinOp(Box::new(IrBinOp {
                left: join_cond,
                op: ast::BinOpKind::And,
                right: tc,
            })),
            None => join_cond,
        };

        Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
            op: ast::UnaryOpKind::Exists,
            operand: IrExpr::Subquery(Box::new(IrSelect::schema_bound(
                IrSource {
                    poly: None,
                    type_name: target_qname,
                    table: target_table,
                    alias: t_alias,
                },
                vec![],
                Some(filter),
            ))),
        })))
    }

    /// Compile the tail steps after `[Backlink, TypeIntersect]`.
    fn compile_backlink_tail(
        &mut self,
        steps: &[ast::PathStep],
        comparison: Option<(ast::BinOpKind, IrExpr, bool)>,
        target_qname: &str,
        t_alias: &str,
    ) -> Result<Option<IrExpr>, PyQLError> {
        use ast::PathStep;

        // `.<contacts[is Account] = account` — nothing after the backlink, so
        // the objects it reaches are what is compared, by identity. Returning
        // nothing here dropped the comparison, leaving "any account links to
        // this row" in its place.
        if steps.is_empty() {
            return Ok(comparison.map(|(op, value, flip)| {
                let key = IrExpr::ColumnRef {
                    alias: t_alias.to_string(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                };
                let (left, right) = if flip { (value, key) } else { (key, value) };
                IrExpr::BinOp(Box::new(IrBinOp { left, op, right }))
            }));
        }

        // Chained backlink: recurse (current_qname is now target_qname of the outer backlink)
        if matches!(steps.first(), Some(PathStep::Backlink(_))) {
            let inner = self.compile_backlink_as_exists(steps, comparison, target_qname, t_alias)?;
            return Ok(Some(inner));
        }

        let target_td = self.resolve_type(target_qname)?;

        // Single property or link FK
        if let [PathStep::Name(pointer_name)] = steps {
            if let Some(prop) = Self::resolve_property(target_td, pointer_name) {
                let col = IrExpr::ColumnRef {
                    alias: t_alias.to_string(),
                    column: prop.name.clone(),
                    pg_type: prop.pg_type.clone(),
                };
                return Ok(Some(Self::apply_comparison(col, comparison)));
            }
            if let Some(link) = Self::resolve_link(target_td, pointer_name) {
                let col = if link.is_junction_backed() {
                    self.junction_target_id_expr(target_td, link, t_alias)?
                } else {
                    IrExpr::ColumnRef {
                        alias: t_alias.to_string(),
                        column: format!("{}_id", link.name),
                        pg_type: "uuid".to_string(),
                    }
                };
                return Ok(Some(Self::apply_comparison(col, comparison)));
            }
            // Not a property or a link: a multi-link has no single column to
            // read, so it falls through to the general tail walk below, which
            // reports the same error for a name that is none of the three.
        }

        // Two forward steps: link then property (single FK join)
        if let [PathStep::Name(link_name), PathStep::Name(prop_name)] = steps
            && let Some(link) = Self::resolve_link(target_td, link_name)
        {
            let link_target = link.target.clone();
            let target_id_expr = if link.is_junction_backed() {
                self.junction_target_id_expr(target_td, link, t_alias)?
            } else {
                IrExpr::ColumnRef {
                    alias: t_alias.to_string(),
                    column: format!("{}_id", link_name),
                    pg_type: "uuid".to_string(),
                }
            };
            let link_target_td = self.resolve_type(&link_target)?;
            let link_target_qname = format!("{}::{}", link_target_td.module, link_target_td.name);
            let link_target_table = link_target_td.table.clone();
            if let Some(prop) = Self::resolve_property(link_target_td, prop_name) {
                let l_alias = self.fresh_alias();
                let id_cond = IrExpr::BinOp(Box::new(IrBinOp {
                    left: IrExpr::ColumnRef {
                        alias: l_alias.clone(),
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    },
                    op: ast::BinOpKind::Eq,
                    right: target_id_expr,
                }));
                let col = IrExpr::ColumnRef {
                    alias: l_alias.clone(),
                    column: prop.name.clone(),
                    pg_type: prop.pg_type.clone(),
                };
                let prop_cond = Self::apply_comparison(col, comparison);
                let full = IrExpr::BinOp(Box::new(IrBinOp {
                    left: id_cond,
                    op: ast::BinOpKind::And,
                    right: prop_cond,
                }));
                return Ok(Some(IrExpr::UnaryOp(Box::new(IrUnaryOp {
                    op: ast::UnaryOpKind::Exists,
                    operand: IrExpr::Subquery(Box::new(IrSelect::schema_bound(
                        IrSource {
                            poly: None,
                            type_name: link_target_qname,
                            table: link_target_table,
                            alias: l_alias,
                        },
                        vec![],
                        Some(full),
                    ))),
                }))));
            }
        }

        // Anything else is an ordinary path from the backlink's target type, so
        // it is compiled as one rather than enumerated arity by arity. The two
        // cases above stay because each reads a single column; a step that
        // crosses a multi-link has none to read.
        let tail = ast::Path {
            steps: steps.to_vec(),
            partial: true,
        };
        let walked = self.compile_path(&tail, target_td, t_alias)?;
        Ok(Some(Self::apply_comparison(walked, comparison)))
    }

    /// Apply an optional comparison to a column ref, defaulting to IS NOT NULL.
    fn apply_comparison(col: IrExpr, comparison: Option<(ast::BinOpKind, IrExpr, bool)>) -> IrExpr {
        match comparison {
            Some((op, val, flip)) => {
                let (l, r) = if flip { (val, col) } else { (col, val) };
                // A walk that crosses a multi-link stands for a *set*, which
                // an equality holds against when any element matches — the
                // same reading `compile_expr_ctx` gives one anywhere else.
                if matches!(op, ast::BinOpKind::Eq | ast::BinOpKind::Ne)
                    && matches!(l, IrExpr::ArrayFromSelect(_)) != matches!(r, IrExpr::ArrayFromSelect(_))
                {
                    let (value, set) = if matches!(r, IrExpr::ArrayFromSelect(_)) {
                        (l, r)
                    } else {
                        (r, l)
                    };
                    let membership = IrExpr::BinOp(Box::new(IrBinOp {
                        left: value,
                        op: ast::BinOpKind::In,
                        right: set,
                    }));
                    return if matches!(op, ast::BinOpKind::Ne) {
                        IrExpr::UnaryOp(Box::new(IrUnaryOp {
                            op: ast::UnaryOpKind::Not,
                            operand: membership,
                        }))
                    } else {
                        membership
                    };
                }
                IrExpr::BinOp(Box::new(IrBinOp { left: l, op, right: r }))
            }
            None => ir_is_not_null(col),
        }
    }

    /// If `b` has a multi-link path (any depth) on either side, compile as EXISTS over the junction.
    fn try_multilink_exists(
        &mut self,
        b: &ast::BinOp,
        td: &TypeDescriptor,
        alias: &str,
    ) -> Result<Option<IrExpr>, PyQLError> {
        // A bare `.multilink` counts: comparing the link itself to an object
        // (`filter any(.emails = email)`) is the same set-membership question
        // as comparing something reached through it, just with no tail.
        fn ml_first_name(steps: &[ast::PathStep]) -> Option<&str> {
            match steps.first()? {
                ast::PathStep::Name(n) => Some(n.as_str()),
                _ => None,
            }
        }

        let (path_steps, value_ast, flip) = if let Expr::Path(p) = &b.left {
            if p.partial {
                if let Some(ln) = ml_first_name(&p.steps) {
                    if Self::resolve_multilink(td, ln).is_some() {
                        (p.steps.as_slice(), &b.right, false)
                    } else {
                        return Ok(None);
                    }
                } else {
                    return Ok(None);
                }
            } else {
                return Ok(None);
            }
        } else if let Expr::Path(p) = &b.right {
            if p.partial {
                if let Some(ln) = ml_first_name(&p.steps) {
                    if Self::resolve_multilink(td, ln).is_some() {
                        (p.steps.as_slice(), &b.left, true)
                    } else {
                        return Ok(None);
                    }
                } else {
                    return Ok(None);
                }
            } else {
                return Ok(None);
            }
        } else {
            return Ok(None);
        };

        let value_expr = self.compile_expr(value_ast, td, alias)?;
        let ml_name = match &path_steps[0] {
            ast::PathStep::Name(n) => n.clone(),
            _ => return Ok(None),
        };
        let ml = Self::resolve_multilink(td, &ml_name).unwrap();

        // Warn: multi-link traversal in a comparison returns a set, not a single boolean.
        // The query works (compiled as EXISTS), but `any()` makes the intent explicit.
        if self.explicit_set_depth == 0 {
            // Rendered back the way it was written — a path the reader cannot
            // find in their own query is worse than no path at all.
            let mut pointer_path = String::new();
            for step in path_steps {
                match step {
                    ast::PathStep::Name(n) => {
                        pointer_path.push('.');
                        pointer_path.push_str(n);
                    }
                    ast::PathStep::Backlink(n) => {
                        pointer_path.push_str(".<");
                        pointer_path.push_str(n);
                    }
                    ast::PathStep::LinkProp(n) => {
                        pointer_path.push('@');
                        pointer_path.push_str(n);
                    }
                    ast::PathStep::TypeIntersection(t) => {
                        pointer_path.push_str("[is ");
                        pointer_path.push_str(&t.qualified_name());
                        pointer_path.push(']');
                    }
                }
            }
            self.warnings.push(format!(
                "possibly more than one element returned by an expression in a FILTER clause \
                 (multi-link '{pointer_path}'); wrap with any() to make intent explicit",
            ));
        }

        // Clone what we need to avoid borrow conflicts with self below.
        let ml_target = ml.target.clone();
        let ml_through = ml.through.clone();
        let td_module = td.module.clone();
        let td_name = td.name.clone();
        let td_table = td.table.clone();

        // tail steps are everything after the multi-link name (path_steps[1..])
        let tail_steps: Vec<ast::PathStep> = path_steps[1..].to_vec();

        let jt_alias = self.fresh_alias();

        // Resolve junction table columns.
        let (jt_table, jt_module, jt_src_col, jt_tgt_col) = if let Some(through_qname) = &ml_through {
            let through_td = self.resolve_type(through_qname)?;
            if through_td.junction {
                // See `junction_info_for`'s doc comment: owner-derived,
                // never `through_td.table` itself.
                (
                    format!("{}.{}", td_table, ml_name),
                    td_module.clone(),
                    "source".to_string(),
                    "target".to_string(),
                )
            } else {
                let source_qname = format!("{}::{}", td_module, td_name);
                let src_col = through_td
                    .links
                    .iter()
                    .find(|l| l.target == source_qname)
                    .ok_or_else(|| {
                        PyQLError::Type(PyQLTypeError {
                            message: format!("through type {through_qname} has no link to {source_qname}"),
                            position: Position { line: 0, col: 0 },
                        })
                    })?
                    .name
                    .clone();
                let tgt_col = through_td
                    .links
                    .iter()
                    .find(|l| l.target == ml_target && l.name != src_col)
                    .or_else(|| through_td.links.iter().find(|l| l.target == ml_target))
                    .ok_or_else(|| {
                        PyQLError::Type(PyQLTypeError {
                            message: format!("through type {through_qname} has no link to {ml_target}"),
                            position: Position { line: 0, col: 0 },
                        })
                    })?
                    .name
                    .clone();
                (
                    through_td.table.clone(),
                    through_td.module.clone(),
                    format!("{}_id", src_col),
                    format!("{}_id", tgt_col),
                )
            }
        } else {
            (
                format!("{}.{}", td_table, ml_name),
                td_module.clone(),
                "source".to_string(),
                "target".to_string(),
            )
        };

        // source filter: jt.src_col = parent.id
        let src_filter = IrExpr::BinOp(Box::new(IrBinOp {
            left: IrExpr::ColumnRef {
                alias: jt_alias.clone(),
                column: jt_src_col,
                pg_type: "uuid".to_string(),
            },
            op: ast::BinOpKind::Eq,
            right: IrExpr::ColumnRef {
                alias: alias.to_string(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
        }));

        // Build tail filter: what to compare inside the junction/target EXISTS
        let tail_filter = self.compile_path_tail_filter(
            &tail_steps,
            b.op.clone(),
            value_expr,
            flip,
            &ml_target,
            &jt_alias,
            &jt_tgt_col,
        )?;

        let full_filter = IrExpr::BinOp(Box::new(IrBinOp {
            left: src_filter,
            op: ast::BinOpKind::And,
            right: tail_filter,
        }));

        // EXISTS(SELECT 1 FROM junction jt WHERE ...)
        let jt_source = IrSource {
            poly: None,
            type_name: format!("{}::__jt__", jt_module),
            table: jt_table,
            alias: jt_alias,
        };
        let inner = IrExpr::Subquery(Box::new(IrSelect::schema_bound(jt_source, vec![], Some(full_filter))));

        Ok(Some(IrExpr::UnaryOp(Box::new(IrUnaryOp {
            op: ast::UnaryOpKind::Exists,
            operand: inner,
        }))))
    }

    /// Build a filter expression for the tail steps after the multi-link in an EXISTS context.
    ///
    /// `steps` = path steps after the multi-link name (e.g. ["company", "id"] for .friends.company.id)
    /// `jt_alias` = alias of the junction table row
    /// `jt_tgt_col` = column in the junction table holding the target id (e.g. "target" or "friend_id")
    /// `target_type` = qualified name of the multi-link's target type (e.g. "default::Person")
    #[allow(clippy::too_many_arguments)]
    fn compile_path_tail_filter(
        &mut self,
        steps: &[ast::PathStep],
        op: ast::BinOpKind,
        value_expr: IrExpr,
        flip: bool,
        target_type: &str,
        jt_alias: &str,
        jt_tgt_col: &str,
    ) -> Result<IrExpr, PyQLError> {
        // No tail at all — the multi-link itself is what is being compared,
        // so the junction row's target id is the whole answer.
        if steps.is_empty() {
            let col_ref = IrExpr::ColumnRef {
                alias: jt_alias.to_string(),
                column: jt_tgt_col.to_string(),
                pg_type: "uuid".to_string(),
            };
            let (left, right) = if flip {
                (value_expr, col_ref)
            } else {
                (col_ref, value_expr)
            };
            return Ok(IrExpr::BinOp(Box::new(IrBinOp { left, op, right })));
        }

        // `.emails[is account::Email].email` — an intersection narrows what the
        // walk continues from. The remaining steps read against the narrowed
        // type, and because its own table is what they join to, a row of any
        // other type drops out on its own: the narrowing needs no separate
        // check.
        if let Some(ast::PathStep::TypeIntersection(type_ref)) = steps.first() {
            let narrowed = self.resolve_type(&type_ref.qualified_name())?;
            let narrowed_qname = format!("{}::{}", narrowed.module, narrowed.name);
            return self.compile_path_tail_filter(
                &steps[1..],
                op,
                value_expr,
                flip,
                &narrowed_qname,
                jt_alias,
                jt_tgt_col,
            );
        }

        let first_name = match steps.first() {
            Some(ast::PathStep::Name(n)) => n.clone(),
            _ => return Err(self.type_err("expected a property or link name in path")),
        };

        let target_td = self.resolve_type(target_type)?;
        let target_table = target_td.table.clone();

        if steps.len() == 1 {
            // Terminal step: must be a scalar property or "id"
            if first_name == "id" {
                // FK optimisation: compare jt.target directly
                let col_ref = IrExpr::ColumnRef {
                    alias: jt_alias.to_string(),
                    column: jt_tgt_col.to_string(),
                    pg_type: "uuid".to_string(),
                };
                let (l, r) = if flip {
                    (value_expr, col_ref)
                } else {
                    (col_ref, value_expr)
                };
                return Ok(IrExpr::BinOp(Box::new(IrBinOp { left: l, op, right: r })));
            }
            // Check if it's a link (object) rather than a scalar
            // A single link is compared by the foreign key it stores, the
            // same way `.link = obj` is one step higher up
            // (`any(.access_grants.account = account)`). A multi-link has no
            // column to compare and would need a junction of its own.
            let single_link = target_td
                .links
                .iter()
                .find(|l| l.name == first_name && !l.is_junction_backed());
            if single_link.is_none() && target_td.multilinks.iter().any(|l| l.name == first_name) {
                let target_display = target_type.replace("::", ".");
                return Err(PyQLError::Type(PyQLTypeError {
                    message: format!(
                        "operator '{op}' cannot be applied to operands of type '{target_display}' and the value type",
                        op = op,
                    ),
                    position: Position { line: 0, col: 0 },
                }));
            }
            let (prop_name, prop_pg) = match single_link {
                Some(link) => (format!("{}_id", link.name), "uuid".to_string()),
                None => {
                    let prop = target_td
                        .properties
                        .iter()
                        .find(|p| p.name == first_name)
                        .ok_or_else(|| self.field_err(&first_name, target_type))?;
                    (prop.name.clone(), prop.pg_type.clone())
                }
            };
            let tgt_alias = self.fresh_alias();
            // Build EXISTS(SELECT 1 FROM target WHERE target.id = jt.target AND target.prop op value)
            let id_filter = IrExpr::BinOp(Box::new(IrBinOp {
                left: IrExpr::ColumnRef {
                    alias: tgt_alias.clone(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
                op: ast::BinOpKind::Eq,
                right: IrExpr::ColumnRef {
                    alias: jt_alias.to_string(),
                    column: jt_tgt_col.to_string(),
                    pg_type: "uuid".to_string(),
                },
            }));
            let prop_col = IrExpr::ColumnRef {
                alias: tgt_alias.clone(),
                column: prop_name,
                pg_type: prop_pg,
            };
            let (pl, pr) = if flip {
                (value_expr, prop_col)
            } else {
                (prop_col, value_expr)
            };
            let prop_filter = IrExpr::BinOp(Box::new(IrBinOp {
                left: pl,
                op,
                right: pr,
            }));
            let full = IrExpr::BinOp(Box::new(IrBinOp {
                left: id_filter,
                op: ast::BinOpKind::And,
                right: prop_filter,
            }));
            let inner = IrExpr::Subquery(Box::new(IrSelect::schema_bound(
                IrSource {
                    poly: None,
                    type_name: target_type.to_string(),
                    table: target_table,
                    alias: tgt_alias,
                },
                vec![],
                Some(full),
            )));
            return Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
                op: ast::UnaryOpKind::Exists,
                operand: inner,
            })));
        }

        // steps.len() >= 2: first_name must be a single link (not multi)
        if target_td.multilinks.iter().any(|l| l.name == first_name) {
            return Err(self.type_err("nested multi-link traversal in comparison is not yet supported"));
        }
        let link = target_td
            .links
            .iter()
            .find(|l| l.name == first_name)
            .ok_or_else(|| self.field_err(&first_name, target_type))?;
        if link.is_junction_backed() {
            // A junction-backed link's correlation is a subquery, not a
            // plain FK column, and this recursive path-tail resolver is
            // built entirely around passing a (alias, column) pair down to
            // the next level — supporting it here would need a broader
            // signature change. Fail loudly rather than silently reference
            // a `{name}_id` column that doesn't exist for this link.
            return Err(self.type_err(&format!(
                "filtering through a junction-backed single link ('{first_name}') nested inside \
                 a multi-link path comparison is not yet supported — filter on '.{first_name}' \
                 directly instead"
            )));
        }
        let next_target = link.target.clone();
        let fk_col = format!("{}_id", first_name);
        let tgt_alias = self.fresh_alias();

        // FK optimisation for [single_link, "id"]:
        if steps.len() == 2
            && let Some(ast::PathStep::Name(n)) = steps.get(1)
            && n == "id"
        {
            // Compare tgt.{fk_col} (the FK in current target) directly
            // We need an EXISTS over the target to access fk_col
            // Actually: EXISTS(target WHERE target.id = jt.target AND target.{fk_col} op value)
            let id_filter = IrExpr::BinOp(Box::new(IrBinOp {
                left: IrExpr::ColumnRef {
                    alias: tgt_alias.clone(),
                    column: "id".to_string(),
                    pg_type: "uuid".to_string(),
                },
                op: ast::BinOpKind::Eq,
                right: IrExpr::ColumnRef {
                    alias: jt_alias.to_string(),
                    column: jt_tgt_col.to_string(),
                    pg_type: "uuid".to_string(),
                },
            }));
            let fk_ref = IrExpr::ColumnRef {
                alias: tgt_alias.clone(),
                column: fk_col,
                pg_type: "uuid".to_string(),
            };
            let (fl, fr) = if flip {
                (value_expr, fk_ref)
            } else {
                (fk_ref, value_expr)
            };
            let fk_filter = IrExpr::BinOp(Box::new(IrBinOp {
                left: fl,
                op,
                right: fr,
            }));
            let full = IrExpr::BinOp(Box::new(IrBinOp {
                left: id_filter,
                op: ast::BinOpKind::And,
                right: fk_filter,
            }));
            let inner = IrExpr::Subquery(Box::new(IrSelect::schema_bound(
                IrSource {
                    poly: None,
                    type_name: target_type.to_string(),
                    table: target_table,
                    alias: tgt_alias,
                },
                vec![],
                Some(full),
            )));
            return Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
                op: ast::UnaryOpKind::Exists,
                operand: inner,
            })));
        }

        // General case: EXISTS(target WHERE target.id = jt.jt_tgt_col AND <tail_filter for steps[1..]>)
        // Recursive call uses tgt_alias.fk_col as the "pointer to the next type's id"
        let id_filter = IrExpr::BinOp(Box::new(IrBinOp {
            left: IrExpr::ColumnRef {
                alias: tgt_alias.clone(),
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            },
            op: ast::BinOpKind::Eq,
            right: IrExpr::ColumnRef {
                alias: jt_alias.to_string(),
                column: jt_tgt_col.to_string(),
                pg_type: "uuid".to_string(),
            },
        }));
        let nested_filter =
            self.compile_path_tail_filter(&steps[1..], op, value_expr, flip, &next_target, &tgt_alias, &fk_col)?;
        let full = IrExpr::BinOp(Box::new(IrBinOp {
            left: id_filter,
            op: ast::BinOpKind::And,
            right: nested_filter,
        }));
        let inner = IrExpr::Subquery(Box::new(IrSelect::schema_bound(
            IrSource {
                poly: None,
                type_name: target_type.to_string(),
                table: target_table,
                alias: tgt_alias,
            },
            vec![],
            Some(full),
        )));
        Ok(IrExpr::UnaryOp(Box::new(IrUnaryOp {
            op: ast::UnaryOpKind::Exists,
            operand: inner,
        })))
    }
}

/// Where a walk reads a multi-link this statement also wrote: the CTE holding
/// the junction rows, and — when the targets were inserted here too — the CTE
/// holding those.
#[derive(Clone)]
struct JunctionReadOverride {
    junction: String,
    targets: Option<String>,
}

/// What an `UNLESS CONFLICT … ELSE (UPDATE …)` clause contributes: the
/// `DO UPDATE SET` assignments, and the predicate deciding whether the
/// conflicting row is touched at all when the ELSE UPDATE carried a filter.
struct ConflictElse {
    sets: Vec<(String, IrExpr)>,
    predicate: Option<IrExpr>,
}

impl<'a> Compiler<'a> {
    /// Compile `UNLESS CONFLICT [ON expr] [ELSE (UPDATE …)]` into `IrConflict`.
    fn compile_conflict(
        &mut self,
        uc: &ast::UnlessConflict,
        td: &TypeDescriptor,
    ) -> Result<(IrConflict, Vec<IrMultiLinkMutation>), PyQLError> {
        // ON clause: compile with empty alias → bare column name (`"col"` not `"t0"."col"`)
        // so the emitter produces `ON CONFLICT ("name")` not `ON CONFLICT ("t0"."name")`.
        let on = uc.on.as_ref().map(|e| self.compile_expr(e, td, "")).transpose()?;
        let mut appends = vec![];
        let mut do_update_where = None;
        let do_update = match uc.else_.as_ref() {
            Some(e) => {
                let resolved = self.compile_conflict_else(e, &mut appends)?;
                do_update_where = resolved.predicate;
                Some(resolved.sets)
            }
            None => None,
        };
        Ok((
            IrConflict {
                on,
                do_update,
                do_update_where,
            },
            appends,
        ))
    }

    /// Compile the ELSE clause of UNLESS CONFLICT, which must be `(UPDATE Type SET { … })`.
    ///
    /// Assignments are compiled with the target table's own bare name (not
    /// schema-qualified, and not the usual `t0`-style fresh alias) as the
    /// qualifying "alias" so a self-referencing RHS (`.stock` in `stock :=
    /// .stock + 1`) resolves unambiguously to the *existing* conflicting
    /// row. A genuinely bare, unqualified column reference here is
    /// ambiguous in Postgres between the existing row and the `excluded`
    /// pseudo-row (confirmed live: "column reference ... is ambiguous")
    /// even though only one of the two is ever actually reachable this way
    /// (nothing here ever compiles a reference to `excluded`) — Postgres's
    /// own docs describe exactly this qualification: "the existing row
    /// using the table's name (or an alias)," no explicit `AS` needed on
    /// the INSERT target for that self-reference to work.
    fn compile_conflict_else(
        &mut self,
        expr: &Expr,
        appends: &mut Vec<IrMultiLinkMutation>,
    ) -> Result<ConflictElse, PyQLError> {
        let Expr::SubQuery(stmt) = expr else {
            return Err(self.type_err("UNLESS CONFLICT ELSE must be an UPDATE expression, e.g. ELSE (UPDATE …)"));
        };
        // `else (select usage::Allowance)` — yield the conflicting row rather
        // than change it. `DO NOTHING` returns nothing at all, so the row is
        // read back by assigning its own key to itself, which is what makes
        // `RETURNING` see it.
        if let Stmt::Select(sel) = stmt.as_ref()
            && sel.filter.is_none()
            && sel.limit.is_none()
            && sel.offset.is_none()
            && let Ok(type_name) = self.expr_as_type_name(&sel.result)
            && let Ok(sel_td) = self.resolve_type(&type_name)
        {
            let table = sel_td.table.clone();
            let pk = sel_td
                .properties
                .iter()
                .find(|p| p.is_pk)
                .ok_or_else(|| self.type_err(&format!("type '{type_name}' has no primary key to read back")))?;
            return Ok(ConflictElse {
                sets: vec![(
                    pk.name.clone(),
                    IrExpr::ColumnRef {
                        alias: table,
                        column: pk.name.clone(),
                        pg_type: pk.pg_type.clone(),
                    },
                )],
                predicate: None,
            });
        }
        let Stmt::Update(upd) = stmt.as_ref() else {
            return Err(self.type_err(
                "UNLESS CONFLICT ELSE must be an UPDATE that changes the conflicting row, or a \
                 SELECT of its type to read it back unchanged",
            ));
        };
        let type_name = self.expr_as_type_name(&upd.subject)?;
        let upd_td = self.resolve_type(&type_name)?;
        let table = upd_td.table.clone();
        // The ON CONFLICT target says *which* row conflicts; the ELSE UPDATE's
        // own filter says whether to touch it at all, and Gel honours it.
        // Dropping it silently turned `unless conflict on .key else (update T
        // filter .expires_at < now() set { … })` into an unconditional steal of
        // a live advisory lock. Compiled against the table name, which is what
        // refers to the *existing* row inside `DO UPDATE` (`excluded` is the
        // proposed one).
        let do_update_where = upd
            .filter
            .as_ref()
            .map(|f| self.compile_expr(f, upd_td, &table))
            .transpose()?;
        // A multi-link cannot be written by `DO UPDATE SET` — junction rows
        // are separate DML. Appending them to the enclosing insert instead
        // applies them to whichever row comes back, inserted or conflicting,
        // and the junction insert is `ON CONFLICT DO NOTHING`, so the
        // inserted branch (which already wrote the same rows from its own
        // shape) is unaffected.
        let mut scalar_shape = vec![];
        for el in &upd.shape {
            let pointer_name = path_leaf(&el.path)?;
            let Some(ml) = Self::resolve_multilink(upd_td, pointer_name) else {
                scalar_shape.push(el.clone());
                continue;
            };
            if el.op == ShapeOp::Remove {
                return Err(self.type_err(&format!(
                    "cannot use `-=` for multi-link '{pointer_name}' inside an UNLESS CONFLICT \
                     ELSE clause; the rows to remove are not known until the conflict resolves"
                )));
            }
            let Some(value) = &el.compexpr else { continue };
            let (jt, module, src_col, tgt_col, through_td) = self.own_multilink_junction_info(upd_td, ml)?;
            let values = self.compile_multilink_values(value, upd_td, &table, through_td)?;
            appends.push(IrMultiLinkMutation {
                junction_table: jt,
                module,
                source_col: src_col,
                target_col: tgt_col,
                values,
                single: false,
            });
        }
        let sets = self.compile_assignments_for_update(&scalar_shape, upd_td, &table)?;
        Ok(ConflictElse {
            sets,
            predicate: do_update_where,
        })
    }

    /// Compile a nested INSERT/UPDATE/DELETE into its own CTE and return that
    /// CTE's name. Postgres cannot run DML inside another statement's value
    /// list, so it is hoisted into the enclosing statement's `WITH` and read
    /// back from there — see `pending_nested_ctes`.
    /// Compile a DML statement into a CTE of the query's own `WITH`.
    ///
    /// Unlike `hoist_nested_dml`, whose CTE belongs to the enclosing
    /// INSERT/UPDATE it was nested inside, this one has no enclosing statement
    /// to attach to — the select that names it *is* the top level.
    fn hoist_dml_as_cte(&mut self, stmt: &Stmt) -> Result<(String, String), PyQLError> {
        let type_name = self.dml_subject_type(stmt)?;
        let before = std::mem::take(&mut self.for_vars_read);
        let inner = self.compile_stmt(stmt);
        let read = std::mem::replace(&mut self.for_vars_read, before);
        let correlated_to = self
            .for_scope
            .iter()
            .rev()
            .find(|slot| read.contains(*slot))
            .map(|slot| format!("_for_{slot}"));
        self.for_vars_read.extend(read);
        let cte_name = self.fresh_nested_cte_name();
        self.hoisted_ctes.push(IrCteDef {
            name: cte_name.clone(),
            stmt: inner?,
            type_name: type_name.clone(),
            correlated_to,
        });
        Ok((cte_name, type_name))
    }

    fn hoist_nested_dml(&mut self, stmt: &Stmt) -> Result<String, PyQLError> {
        let type_name = self.dml_subject_type(stmt)?;
        let inner = self.compile_stmt(stmt)?;
        let cte_name = self.fresh_nested_cte_name();
        self.pending_nested_ctes.push(IrCteDef {
            name: cte_name.clone(),
            stmt: inner,
            type_name,
            correlated_to: None,
        });
        Ok(cte_name)
    }

    /// Compile `(SELECT TargetType FILTER …)` as a scalar subquery for use in a
    /// link assignment (`company := (SELECT Company FILTER .name = $co)`).
    /// Returns `IrExpr::Subquery` whose shape is the target pk — the SQL emitter
    /// renders this as `(SELECT "alias"."id" FROM … WHERE …)`.
    fn compile_link_subquery(&mut self, stmt: &Stmt) -> Result<IrExpr, PyQLError> {
        // `preferences := (insert Preferences { … })` — the nested DML used
        // directly as the value, which is the same hoist the wrapped
        // `select (insert …) { id }` form below goes through.
        if matches!(stmt, Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_)) {
            let cte_name = self.hoist_nested_dml(stmt)?;
            return Ok(IrExpr::ColumnRef {
                alias: cte_name,
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            });
        }
        let Stmt::Select(sel) = stmt else {
            return Err(self.type_err(
                "only SELECT is valid as a link assignment value; \
                 use SELECT (INSERT …) { id } to assign from a DML result",
            ));
        };

        // `SELECT (INSERT …) { id }` / `SELECT (UPDATE …) { id }` /
        // `SELECT (DELETE …) { id }` — the exact workaround this function's
        // own error message above recommends. Postgres has no way to run a
        // nested INSERT/UPDATE/DELETE inside another statement's value list
        // without hoisting it into a `WITH` CTE first, so that's what this
        // does: compile the inner DML as its own statement, stash it in
        // `self.pending_nested_ctes` under a fresh CTE name (drained by
        // whichever `compile_insert`/`compile_update` is compiling the
        // assignment this value belongs to — see those functions' own doc
        // comments — and prepended as a `WITH` CTE by the emitter, which
        // also switches the outer statement's own row source from
        // `VALUES (...)` / a bare `SET` to something that can actually
        // reference it), and return a plain reference to that CTE's `id`
        // column in place of the subquery.
        //
        // A prior attempt to handle this by delegating to `compile_select`
        // (which does know how to chain a `dml_source`, but only for a
        // *top-level* `SELECT (INSERT …) { ... }` statement) compiled
        // without error but silently emitted a subquery that dropped the
        // nested INSERT and selected an unrelated, arbitrary pre-existing
        // row instead — do not repeat that approach.
        let nested_dml = match &sel.result {
            Expr::SubQuery(inner) if matches!(inner.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_)) => {
                Some(inner.as_ref())
            }
            Expr::Shape(s) => match s.expr.as_ref() {
                Some(Expr::SubQuery(inner))
                    if matches!(inner.as_ref(), Stmt::Insert(_) | Stmt::Update(_) | Stmt::Delete(_)) =>
                {
                    Some(inner.as_ref())
                }
                _ => None,
            },
            _ => None,
        };
        if let Some(inner_stmt) = nested_dml {
            let cte_name = self.hoist_nested_dml(inner_stmt)?;
            return Ok(IrExpr::ColumnRef {
                alias: cte_name,
                column: "id".to_string(),
                pg_type: "uuid".to_string(),
            });
        }

        let type_name = self.expr_as_type_name(&sel.result)?;
        let td = self.resolve_type(&type_name)?;
        let alias = self.fresh_alias();

        // `(select T filter … order by … limit 1)` — every clause decides
        // which row is linked, not just the filter.
        let (filter, order_by, offset, limit) = self.compile_path_modifiers(sel, td, &alias)?;
        let mut select = IrSelect::schema_bound(
            IrSource {
                poly: None,
                type_name: format!("{}::{}", td.module, td.name),
                table: td.table.clone(),
                alias,
            },
            Self::pk_returning(td),
            filter,
        );
        select.order_by = order_by;
        select.offset = offset;
        select.limit = limit;
        Ok(IrExpr::Subquery(Box::new(select)))
    }

    /// Shared `IrSort` builder for both schema-bound (`compile_sort`) and
    /// free (`compile_free_select`'s order-by) contexts — direction/nulls
    /// translation is identical either way, only the expr compiler ctx differs.
    fn compile_sort_ctx(
        &mut self,
        s: &ast::SortExpr,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<IrSort, PyQLError> {
        Ok(IrSort {
            expr: self.compile_expr_ctx(&s.expr, ctx)?,
            direction: match s.direction {
                SortDirection::Asc => IrSortDir::Asc,
                SortDirection::Desc => IrSortDir::Desc,
            },
            nulls: match s.nones {
                NonesOrder::First => IrNulls::First,
                NonesOrder::Last => IrNulls::Last,
            },
        })
    }

    fn compile_sort(&mut self, s: &ast::SortExpr, td: &TypeDescriptor, alias: &str) -> Result<IrSort, PyQLError> {
        self.compile_sort_ctx(s, Some((td, alias)))
    }

    // ── Stdlib function resolution ────────────────────────────────────────────────

    /// Look up `name` in the stdlib (namespace = `module` or `"std"`) and produce
    /// the correct `IrExpr::FunctionCall` based on the matching `ImplStrategy`.
    /// Falls through to a plain call if no overload is found (unknown / PG built-in).
    /// `message := …` of an assert handled outside the generic call route,
    /// which would otherwise drop it and raise the assert's own text.
    fn assert_message(
        &mut self,
        f: &ast::FunctionCall,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<Option<IrExpr>, PyQLError> {
        let mut message = None;
        for (name, value) in &f.kwargs {
            if name != "message" {
                return Err(self.type_err(&format!("function 'std::{}' has no parameter '{name}'", f.name)));
            }
            message = Some(self.compile_expr_ctx(value, ctx)?);
        }
        Ok(message)
    }

    /// A stdlib call against its named-only parameters — `message :=` of the
    /// asserts, every parameter of `cal::to_relative_duration`. The arguments
    /// come back in parameter order, each named-only one left out standing
    /// at its default. `None` for a call that names nothing and needs no
    /// default, which the positional route handles as it always has.
    fn compile_named_call_args(
        &mut self,
        f: &ast::FunctionCall,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<Option<Vec<IrExpr>>, PyQLError> {
        use crate::stdlib::NamedDefault;

        let ns = f.module.as_deref().unwrap_or("std");
        let overloads = crate::stdlib::lookup(ns, &f.name);
        let positional = |d: &crate::stdlib::FnDescriptor| d.params.iter().filter(|p| p.named_only.is_none()).count();
        let named = |d: &crate::stdlib::FnDescriptor| d.params.iter().filter(|p| p.named_only.is_some()).count();
        if f.kwargs.is_empty() {
            if overloads.iter().any(|d| positional(d) == f.args.len() && named(d) == 0) {
                return Ok(None);
            }
            if !overloads.iter().any(|d| positional(d) == f.args.len()) && overloads.iter().any(|d| named(d) > 0) {
                let param = overloads
                    .iter()
                    .flat_map(|d| d.params.iter())
                    .find(|p| p.named_only.is_some())
                    .map_or("", |p| p.keyword());
                return Err(self.type_err(&format!(
                    "function '{ns}::{}' takes '{param}' as a named argument only — e.g. '{param} := …'",
                    f.name
                )));
            }
        }
        let fits = |d: &&&crate::stdlib::FnDescriptor| {
            positional(d) == f.args.len()
                && named(d) > 0
                && f.kwargs
                    .iter()
                    .all(|(name, _)| d.params.iter().any(|p| p.keyword() == name && p.named_only.is_some()))
        };
        let Some(desc) = overloads.iter().find(fits) else {
            if let Some((name, _)) = f.kwargs.first() {
                let message = if overloads.iter().all(|d| named(d) == 0) {
                    format!(
                        "function '{ns}::{}' does not take named arguments, got '{name}'",
                        f.name
                    )
                } else {
                    format!("function '{ns}::{}' has no parameter '{name}'", f.name)
                };
                return Err(self.type_err(&message));
            }
            return Ok(None);
        };
        let mut args = f
            .args
            .iter()
            .map(|a| self.compile_expr_ctx(a, ctx))
            .collect::<Result<Vec<_>, _>>()?;
        for param in desc.params.iter().filter(|p| p.named_only.is_some()) {
            let arg = match (
                f.kwargs.iter().find(|(name, _)| name == param.keyword()),
                param.named_only,
            ) {
                (Some((_, value)), _) => self.compile_expr_ctx(value, ctx)?,
                (None, Some(NamedDefault::Int(n))) => IrExpr::Literal(IrLiteral::Int(n)),
                (None, _) => IrExpr::Null,
            };
            args.push(arg);
        }
        Ok(Some(args))
    }

    fn resolve_fn_call(&mut self, module: Option<&str>, name: &str, args: Vec<IrExpr>) -> Result<IrExpr, PyQLError> {
        use crate::stdlib::{ImplStrategy, lookup};

        let ns = module.unwrap_or("std");
        // `any`/`all` aggregate a *set* of booleans. Everything that reaches
        // here is a single value — a multi-link comparison has already become
        // its own EXISTS — and a single boolean is its own any()/all();
        // `bool_or` over it would be an aggregate where SQL allows none.
        if ns == "std" && matches!(name, "any" | "all") && args.len() == 1 && !is_array_expr(&args[0]) {
            return Ok(args.into_iter().next().expect("checked by the guard"));
        }
        let overloads = lookup(ns, name);

        // Arity is decided first and on its own, so a call no overload could
        // accept is never type-matched against one anyway. Named-only
        // parameters are already materialized into `args` by
        // `compile_named_call_args`, so the comparison is against the full
        // parameter list; a trailing variadic absorbs zero or more, matching
        // `pylon.stdlib._arity_matches`, the same rule the Python surface
        // has always applied to `std.foo(...)`.
        let by_arity: Vec<&crate::stdlib::FnDescriptor> = overloads
            .iter()
            .copied()
            .filter(|d| {
                if d.is_variadic() {
                    args.len() + 1 >= d.params.len()
                } else {
                    d.params.len() == args.len()
                }
            })
            .collect();

        // Pick the overload whose parameter types best match the argument
        // types. An overload whose declared types are exactly what is known
        // of the arguments beats one that merely accepts them:
        // `to_str(<bytes>)` is the bytes overload, not the first one whose
        // parameter type no check rejects.
        let exact = by_arity.iter().copied().find(|d| {
            params_for_args(d, args.len())
                .zip(&args)
                .any(|(p, a)| p.ty.scalar_pg_type().is_some() && infer_ir_type(a).is_some())
                && params_for_args(d, args.len()).zip(&args).all(|(p, a)| {
                    match (p.ty.scalar_pg_type(), infer_ir_type(a)) {
                        (Some(declared), Some(known)) => declared == known,
                        _ => pylon_type_matches(a, &p.ty),
                    }
                })
        });
        let best = exact.or_else(|| {
            by_arity.iter().copied().find(|d| {
                params_for_args(d, args.len())
                    .zip(&args)
                    .all(|(p, a)| pylon_type_matches(a, &p.ty))
            })
        });

        let stdlib_return = best.and_then(|d| d.return_type.scalar_pg_type()).map(str::to_string);
        let (schema, resolved_name, sql_template) = if let Some(desc) = best {
            match &desc.impl_strategy {
                ImplStrategy::SqlBuiltin(sql_name) => (None, sql_name.to_string(), None),
                ImplStrategy::SqlExpression(tmpl) => (None, name.to_string(), Some(tmpl.to_string())),
                ImplStrategy::PylonFunction(def) => (Some("_pylon".to_string()), def.name.to_string(), None),
                // Binary infix operator: emit as a template so sql/mod.rs's
                // generic FunctionCall path (which only ever calls
                // `schema.name(args)`) doesn't swallow the operator symbol —
                // previously unreachable in practice (only `std::overlaps`
                // used this strategy, untested, and would have silently
                // resolved to a nonexistent `"std".overlaps(...)` call).
                ImplStrategy::SqlOperator(op) if args.len() == 2 => {
                    (None, name.to_string(), Some(format!("($1 {op} $2)")))
                }
                ImplStrategy::TranspilerIntrinsic(intrinsic) => {
                    return self.compile_range_intrinsic(intrinsic, name, args);
                }
                // TranspilerIntrinsic: pass through; handled elsewhere
                _ => (module.map(str::to_string), name.to_string(), None),
            }
        } else {
            // Fall back to user-defined scalar functions. Overload
            // resolution is by (module, name, argument count) only — true
            // Postgres-style resolution by argument *type* isn't
            // implemented (a call whose args happen to have the right
            // count for the wrong-typed overload still picks that one,
            // relying on the forced TypeCast below rather than erroring).
            // Candidates are searched for one whose param count actually
            // matches the call — taking just the first (module, name)
            // match regardless of arg count used to silently pick the
            // wrong overload's signature (and then error on arg count)
            // whenever an earlier-declared overload happened to have a
            // different arity than the one actually being called
            // (confirmed live: a 2-arg call to an overload set whose
            // first-declared member takes 1 arg reported "expects 1
            // argument(s), got 2" even though a 2-arg overload existed).
            let candidates: Vec<&FunctionDescriptor> = self
                .schema
                .functions
                .iter()
                .filter(|f| {
                    let module_matches = module.map(|m| m == f.module.as_str()).unwrap_or(true);
                    module_matches && f.name == name && !f.return_is_object
                })
                .collect();
            let user_fn = candidates
                .iter()
                .find(|f| f.params.len() == args.len())
                .copied()
                .or_else(|| candidates.first().copied());
            if let Some(fd) = user_fn {
                if fd.params.len() != args.len() {
                    return Err(self.type_err(&format!(
                        "function '{}::{}' expects {} argument(s), got {}",
                        fd.module,
                        fd.name,
                        fd.params.len(),
                        args.len()
                    )));
                }
                let cast_args = fd
                    .params
                    .iter()
                    .zip(args)
                    .map(|(p, a)| {
                        IrExpr::TypeCast(Box::new(super::IrTypeCast {
                            expr: a,
                            pg_type: p.pg_type.clone(),
                            tuple_shape: None,
                        }))
                    })
                    .collect();
                let qualified = format!("{}::{}", fd.module, fd.name);
                let fn_module = fd.module.clone();
                let fn_name = fd.name.clone();
                let mut call_args: Vec<IrExpr> = cast_args;
                if let Some(globals) = self.globals_arg_for_call(&qualified)? {
                    call_args.insert(0, globals);
                }
                // A set-returning function has no single value to type, and
                // the declared type of an object-returning one names a type,
                // not a column — neither is a scalar `infer_ir_type` may
                // report.
                let return_pg_type = (!fd.return_is_set).then(|| fd.return_pg_type.clone());
                return Ok(IrExpr::FunctionCall(super::IrFunctionCall {
                    return_pg_type,
                    schema: Some(fn_module),
                    name: fn_name,
                    args: call_args,
                    sql_template: None,
                }));
            }
            // An object-returning function is deliberately not a candidate
            // above — it compiles through `try_compile_fn_object_select`, which
            // only runs when the call is a select's subject. Saying "does not
            // exist" for one that plainly does (and naming `default::` for a
            // call the user wrote unqualified) sent people looking for a typo
            // instead of at the restriction.
            if let Some(fd) = self.schema.functions.iter().find(|f| {
                let module_matches = module.map(|m| m == f.module.as_str()).unwrap_or(true);
                module_matches && f.name == name && f.return_is_object
            }) {
                return Err(self.type_err(&format!(
                    "function '{}::{}' returns objects, so it can only be the subject of a \
                     select (`select {}::{}(…) {{ … }}`), not part of a larger expression",
                    fd.module, fd.name, fd.module, fd.name
                )));
            }
            let qualified = match module {
                Some(m) => format!("{m}::{name}"),
                None => name.to_string(),
            };
            // The name is real and only the call is wrong — say which,
            // rather than resolving to whichever overload happened to be
            // registered first and letting PostgreSQL reject the emitted
            // SQL at query time with a signature the author never wrote.
            if !overloads.is_empty() {
                return Err(self.type_err(&if by_arity.is_empty() {
                    format!(
                        "function '{qualified}' takes {}, got {}",
                        describe_arities(&overloads),
                        args.len()
                    )
                } else {
                    format!(
                        "function '{qualified}' has no overload accepting ({}) — it accepts {}",
                        describe_args(&args),
                        describe_signatures(&by_arity),
                    )
                }));
            }
            return Err(self.type_err(&format!(
                "function '{qualified}' does not exist{}",
                self.suggest_function_name(ns, name)
            )));
        };

        Ok(IrExpr::FunctionCall(super::IrFunctionCall {
            return_pg_type: stdlib_return,
            schema,
            name: resolved_name,
            args,
            sql_template,
        }))
    }

    /// Resolve `std::range(...)`/`std::multirange(...)` — `TranspilerIntrinsic`
    /// entries with no real backing function anywhere (no `_pylon` function,
    /// no bare PostgreSQL builtin of that literal name). PostgreSQL has no
    /// single polymorphic range constructor — the concrete constructor
    /// (`int8range`, `numrange`, `tsrange`, `tstzrange`, `daterange`, and
    /// their multirange counterparts) is chosen here from the resolved
    /// element type of the arguments, since there's nothing generic to defer
    /// to at the SQL level the way `to_jsonb(x)` covers "cast to json".
    fn compile_range_intrinsic(&self, intrinsic: &str, name: &str, args: Vec<IrExpr>) -> Result<IrExpr, PyQLError> {
        match intrinsic {
            "range" => {
                let point_ty = args.first().and_then(infer_ir_type).ok_or_else(|| {
                    self.type_err(
                        "range(): cannot infer the element type of the first argument — \
                     use an explicit cast, e.g. range(<int64>$lower, <int64>$upper)",
                    )
                })?;
                let ctor = range_ctor_for_pg_type(point_ty).ok_or_else(|| {
                    self.type_err(&format!(
                        "range(): unsupported element type '{point_ty}' — PostgreSQL only has native \
                     ranges over int64, decimal, datetime, cal::local_datetime, and cal::local_date"
                    ))
                })?;
                let sql_template = match args.len() {
                    1 => {
                        return Err(self.type_err(
                            "range(empty) has no inferable element type in this context — not \
                         currently supported; use range(lower, upper) instead",
                        ));
                    }
                    2 => format!("{ctor}($1, $2)"),
                    4 => format!(
                        "{ctor}($1, $2, \
                         (CASE WHEN $3 THEN '[' ELSE '(' END) || (CASE WHEN $4 THEN ']' ELSE ')' END))"
                    ),
                    n => return Err(self.type_err(&format!("range(): unexpected argument count {n}"))),
                };
                // `.name` carries the *resolved* constructor (not the
                // original `range`) so a wrapping `multirange([range(...)])`
                // call can identify the element family — emission always
                // goes through `sql_template` above, so this doesn't change
                // the SQL text.
                // A PostgreSQL range constructor shares its name with the
                // type it builds (`int8range(…)` is an `int8range`), so the
                // ctor doubles as the return type — which is what lets a
                // range reach a `range<anypoint>` parameter as itself rather
                // than as an untyped expression.
                Ok(IrExpr::FunctionCall(super::IrFunctionCall {
                    return_pg_type: Some(ctor.to_string()),
                    schema: None,
                    name: ctor.to_string(),
                    args,
                    sql_template: Some(sql_template),
                }))
            }
            "multirange" => {
                let Some(IrExpr::Array(elems)) = args.first() else {
                    return Err(self.type_err("multirange(): argument must be an array literal of ranges"));
                };
                let first_ctor = elems
                    .first()
                    .and_then(|e| match e {
                        IrExpr::FunctionCall(fc) => Some(fc.name.as_str()),
                        _ => None,
                    })
                    .ok_or_else(|| {
                        self.type_err(
                            "multirange(): cannot infer the element range type from an empty or non-range \
                     array — pass at least one range(...) call, e.g. multirange([range(1, 3)])",
                        )
                    })?;
                let ctor = multirange_ctor_for_range_ctor(first_ctor).ok_or_else(|| {
                    self.type_err(&format!("multirange(): unrecognized range constructor '{first_ctor}'"))
                })?;
                // PostgreSQL's multirange constructors (int8multirange, etc.)
                // are VARIADIC — they don't accept a plain array argument
                // without the VARIADIC keyword.
                Ok(IrExpr::FunctionCall(super::IrFunctionCall {
                    return_pg_type: Some(ctor.to_string()),
                    schema: None,
                    name: name.to_string(),
                    args,
                    sql_template: Some(format!("{ctor}(VARIADIC $1)")),
                }))
            }
            other => Err(self.type_err(&format!("internal error: unhandled TranspilerIntrinsic '{other}'"))),
        }
    }

    // ── Sequence function helpers ──────────────────────────────────────────────────

    /// Compile `sequence_next(SeqType)` → `nextval('"module"."Name_seq"')`
    /// and `sequence_reset(SeqType[, val])` → `setval(...)`.
    fn compile_sequence_fn(&mut self, fc: &ast::FunctionCall) -> Result<IrExpr, PyQLError> {
        let (module, scalar_name) = self.resolve_sequence_scalar_arg(fc)?;

        if fc.name == "sequence_next" {
            if fc.args.len() != 1 {
                return Err(self.type_err("sequence_next takes exactly 1 argument"));
            }
            let sql = format!("nextval('\"{}\".\"{}_seq\"')", module, scalar_name);
            return Ok(IrExpr::FunctionCall(super::IrFunctionCall {
                return_pg_type: None,
                schema: None,
                name: "nextval".into(),
                args: vec![],
                sql_template: Some(sql),
            }));
        }

        // sequence_reset
        match fc.args.len() {
            1 => {
                let sql = format!("setval('\"{}\".\"{}_seq\"', 1, false)", module, scalar_name);
                Ok(IrExpr::FunctionCall(super::IrFunctionCall {
                    return_pg_type: None,
                    schema: None,
                    name: "setval".into(),
                    args: vec![],
                    sql_template: Some(sql),
                }))
            }
            2 => {
                let val = self.compile_free_expr(&fc.args[1])?;
                let sql = format!("setval('\"{}\".\"{}_seq\"', $1, true)", module, scalar_name);
                Ok(IrExpr::FunctionCall(super::IrFunctionCall {
                    return_pg_type: None,
                    schema: None,
                    name: "setval".into(),
                    args: vec![val],
                    sql_template: Some(sql),
                }))
            }
            _ => Err(self.type_err("sequence_reset takes 1 or 2 arguments")),
        }
    }

    /// Resolve the first argument of a sequence function to `(module, scalar_name)`.
    /// The argument must be an unqualified path that names a sequence scalar in the schema.
    fn resolve_sequence_scalar_arg(&self, fc: &ast::FunctionCall) -> Result<(String, String), PyQLError> {
        use crate::parse::ast::{Expr, Path, PathStep};

        let arg = fc.args.first().ok_or_else(|| {
            self.type_err(&format!(
                "{}() requires a sequence scalar type as its first argument",
                fc.name
            ))
        })?;

        // The parser encodes `module::Name` as a single PathStep::Name("module::Name"),
        // so we split on "::" here to recover the module part.
        let (arg_module, arg_name): (Option<&str>, &str) = match arg {
            Expr::Path(Path { steps, partial: false }) => match steps.as_slice() {
                [PathStep::Name(s)] => {
                    if let Some((m, n)) = s.split_once("::") {
                        (Some(m), n)
                    } else {
                        (None, s.as_str())
                    }
                }
                _ => return Err(self.type_err(&format!(
                    "{}(): first argument must be a sequence scalar type name (e.g. OrderNumber or default::OrderNumber)",
                    fc.name
                ))),
            },
            _ => return Err(self.type_err(&format!(
                "{}(): first argument must be a sequence scalar type name (e.g. OrderNumber or default::OrderNumber)",
                fc.name
            ))),
        };

        let scalar = self.schema.scalars.iter().find(|s| {
            s.is_sequence && s.name == arg_name && arg_module.map(|m| m == s.module.as_str()).unwrap_or(true)
        });

        match scalar {
            Some(s) => Ok((s.module.clone(), s.name.clone())),
            None => Err(self.type_err(&format!(
                "{}(): '{}' is not a known sequence scalar type",
                fc.name, arg_name
            ))),
        }
    }

    // ── Channel notify() helpers ────────────────────────────────────────────────

    /// PostgreSQL's hard per-NOTIFY-payload limit (`NOTIFY_PAYLOAD_MAX_LENGTH`
    /// in the Postgres source) — a payload at or over this is rejected by the
    /// server at runtime, always, for every session. Checked here only when
    /// the payload is a literal string (the one case actually decidable at
    /// compile time — see `static_min_payload_bytes` for how much of an
    /// arbitrary payload expression can be sized without running it.
    const NOTIFY_PAYLOAD_MAX_BYTES: usize = 8000;

    /// The rejection every non-object payload for a Type channel shares.
    fn notify_type_payload_err(&self, channel: &str, qname: &str) -> PyQLError {
        self.type_err(&format!(
            "notify(): payload for Channel '{channel}' (a '{qname}' object channel) must name an object of that \
             type — either a with-block binding, or __new__/__old__ inside a trigger handler"
        ))
    }

    /// Compile `notify(Channel, payload)` → `pg_notify('<wire_name>', (<payload>)::text)`.
    /// The payload's required shape depends on the Channel's declared kind:
    /// - `Type(qname)`: payload must be the bare `__new__`/`__old__` trigger
    ///   anchor for that exact type — sends its `.id`, not the whole row (see
    ///   this function's own restriction: a general object-typed expression
    ///   isn't supported yet, only the trigger-anchor case).
    /// - `Scalar(pg_type)`: payload is any expression, best-effort type-checked.
    /// - `Object(fields)`: payload must be a free object literal (`{ a := .., b := .. }`)
    ///   whose field names exactly match the declared shape.
    fn compile_notify(
        &mut self,
        fc: &ast::FunctionCall,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<IrExpr, PyQLError> {
        use crate::parse::ast::{Expr, Path, PathStep};

        if fc.args.len() != 2 {
            return Err(self.type_err("notify() takes exactly 2 arguments: (Channel, payload)"));
        }

        let (channel_module, channel_name): (Option<&str>, &str) = match &fc.args[0] {
            Expr::Path(Path { steps, partial: false }) => match steps.as_slice() {
                [PathStep::Name(s)] => {
                    if let Some((m, n)) = s.split_once("::") {
                        (Some(m), n)
                    } else {
                        (None, s.as_str())
                    }
                }
                _ => {
                    return Err(self.type_err(
                        "notify(): first argument must be a Channel name (e.g. OrderEvents or orders::OrderEvents)",
                    ));
                }
            },
            _ => {
                return Err(self.type_err(
                    "notify(): first argument must be a Channel name (e.g. OrderEvents or orders::OrderEvents)",
                ));
            }
        };
        let full_channel_name = match channel_module {
            Some(m) => format!("{m}::{channel_name}"),
            None => channel_name.to_string(),
        };
        let channel = self
            .resolve_channel(&full_channel_name)
            .ok_or_else(|| self.type_err(&format!("notify(): '{channel_name}' is not a known Channel")))?;
        let wire_name = channel.wire_name.clone();
        let payload_arg = &fc.args[1];

        // A bare `select notify(...)` trigger handler has no type at its
        // root, so the top-level statement compiles as a *free* select
        // (ctx=None) even though `special_anchors` is populated — `__new__`/
        // `__old__` only resolve through `compile_path`, which is only ever
        // reached when ctx is `Some(..)` (see `Expr::Path`'s arm above).
        // Fall back to any bound anchor's (td, alias) as a stand-in ctx so a
        // Scalar/Object payload like `__new__.name` or `{ a := __new__.x }`
        // still resolves — `compile_path`'s own `__new__`/`__old__` branch
        // ignores whatever td/alias ctx carries for those two names anyway,
        // it only matters for a real property access on some other root.
        // Cloned out of `special_anchors` (rather than borrowed) so it
        // doesn't hold an immutable borrow of `self` across the `&mut self`
        // `compile_expr_ctx` calls below.
        let anchor_fallback: Option<(&'a TypeDescriptor, String)> = self.special_anchors.values().next().cloned();
        let ctx = ctx.or_else(|| anchor_fallback.as_ref().map(|(td, alias)| (*td, alias.as_str())));

        let payload_ir = match &channel.payload {
            crate::schema::ChannelPayload::Type(qname) => {
                // The payload for an object channel is the object's `id`, in
                // either of the two places one can be named: the `__new__`/
                // `__old__` anchor a trigger handler runs against, or a
                // with-block binding in an ordinary query — which is what
                // lets a notify compose with the mutation that caused it:
                //
                //   with updated := (update User filter ... set { ... }),
                //   select (notify(UserUpdates, updated), updated)
                let Expr::Path(Path { steps, partial: false }) = payload_arg else {
                    return Err(self.notify_type_payload_err(&full_channel_name, qname));
                };
                let [PathStep::Name(name)] = steps.as_slice() else {
                    return Err(self.notify_type_payload_err(&full_channel_name, qname));
                };

                if name == "__new__" || name == "__old__" {
                    let (anchor_td, alias) = self.special_anchors.get(name.as_str()).cloned().ok_or_else(|| {
                        self.type_err(&format!(
                            "notify(): '{name}' cannot be used here — it's only bound inside a trigger handler"
                        ))
                    })?;
                    let anchor_qname = format!("{}::{}", anchor_td.module, anchor_td.name);
                    if &anchor_qname != qname {
                        return Err(self.type_err(&format!(
                            "notify(): Channel '{full_channel_name}' expects a payload of type '{qname}', got '{anchor_qname}'"
                        )));
                    }
                    IrExpr::ColumnRef {
                        alias,
                        column: "id".to_string(),
                        pg_type: "uuid".to_string(),
                    }
                } else if let Some(cte_type) = self.cte_types.get(name.as_str()).cloned() {
                    if &cte_type != qname {
                        return Err(self.type_err(&format!(
                            "notify(): Channel '{full_channel_name}' expects a payload of type '{qname}', got '{cte_type}'"
                        )));
                    }
                    // `CteRef { scalar: false }` emits `(SELECT "id" FROM
                    // "<cte>")` — the same id the trigger path sends.
                    IrExpr::CteRef {
                        name: name.clone(),
                        scalar: false,
                        pg_type: None,
                    }
                } else {
                    return Err(self.notify_type_payload_err(&full_channel_name, qname));
                }
            }
            crate::schema::ChannelPayload::Scalar(pg_type) => {
                let ir = self.compile_expr_ctx(payload_arg, ctx)?;
                if let Some(actual) = infer_ir_type(&ir)
                    && !types_compatible(actual, pg_type)
                {
                    return Err(self.type_err(&format!(
                            "notify(): Channel '{full_channel_name}' expects a payload of type '{expected}', got '{actual_pyql}'",
                            expected = pg_type_to_pyql(pg_type),
                            actual_pyql = pg_type_to_pyql(actual),
                        )));
                }
                ir
            }
            crate::schema::ChannelPayload::Object(declared_fields) => {
                let Expr::Shape(sh) = payload_arg else {
                    return Err(self.type_err(&format!(
                        "notify(): payload for Channel '{full_channel_name}' (an Object channel) must be a free \
                         object literal, e.g. {{ {} }}",
                        declared_fields
                            .iter()
                            .map(|(n, _)| format!("{n} := .."))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )));
                };
                if sh.expr.is_some() {
                    return Err(self.type_err(&format!(
                        "notify(): payload for Channel '{full_channel_name}' (an Object channel) must be a free \
                         object literal, not a shape over a type"
                    )));
                }
                let ir = self.compile_expr_ctx(payload_arg, ctx)?;
                let IrExpr::NamedTuple {
                    fields,
                    is_free_object: true,
                } = &ir
                else {
                    return Err(self.type_err(&format!(
                        "notify(): payload for Channel '{full_channel_name}' (an Object channel) must be a free object literal"
                    )));
                };
                let declared_names: std::collections::HashSet<&str> =
                    declared_fields.iter().map(|(n, _)| n.as_str()).collect();
                let actual_names: std::collections::HashSet<&str> = fields.iter().map(|(n, _)| n.as_str()).collect();
                if declared_names != actual_names {
                    let mut expected: Vec<&str> = declared_names.iter().copied().collect();
                    expected.sort();
                    let mut actual: Vec<&str> = actual_names.iter().copied().collect();
                    actual.sort();
                    return Err(self.type_err(&format!(
                        "notify(): payload fields for Channel '{full_channel_name}' don't match — expected {{{}}}, got {{{}}}",
                        expected.join(", "), actual.join(", ")
                    )));
                }
                for (name, expr) in fields {
                    let Some((_, declared_pg_type)) = declared_fields.iter().find(|(n, _)| n == name) else {
                        continue;
                    };
                    if let Some(actual) = infer_ir_type(expr)
                        && !types_compatible(actual, declared_pg_type)
                    {
                        return Err(self.type_err(&format!(
                                "notify(): field '{name}' of Channel '{full_channel_name}' expects type '{expected}', got '{actual_pyql}'",
                                expected = pg_type_to_pyql(declared_pg_type),
                                actual_pyql = pg_type_to_pyql(actual),
                            )));
                    }
                }
                ir
            }
        };

        let floor = static_min_payload_bytes(payload_arg);
        if floor >= Self::NOTIFY_PAYLOAD_MAX_BYTES {
            return Err(self.type_err(&format!(
                "notify(): this payload is at least {floor} bytes, which is at or over PostgreSQL's {}-byte NOTIFY \
                 payload limit — the notification would fail at runtime, aborting the transaction that sent it",
                Self::NOTIFY_PAYLOAD_MAX_BYTES
            )));
        }

        let sql = format!("pg_notify('{}', ($1)::text)", wire_name.replace('\'', "''"));
        Ok(IrExpr::FunctionCall(super::IrFunctionCall {
            return_pg_type: None,
            schema: None,
            name: "pg_notify".to_string(),
            args: vec![payload_ir],
            sql_template: Some(sql),
        }))
    }

    /// Compile `notify_raw(channel_name, payload)` → `pg_notify($1, $2)` — the
    /// escape hatch that bypasses Channel resolution and payload-shape
    /// checking entirely: both arguments are arbitrary text expressions.
    fn compile_notify_raw(
        &mut self,
        fc: &ast::FunctionCall,
        ctx: Option<(&TypeDescriptor, &str)>,
    ) -> Result<IrExpr, PyQLError> {
        if fc.args.len() != 2 {
            return Err(self.type_err("notify_raw() takes exactly 2 arguments: (channel_name, payload)"));
        }
        let channel_ir = self.compile_expr_ctx(&fc.args[0], ctx)?;
        let payload_ir = self.compile_expr_ctx(&fc.args[1], ctx)?;

        let floor = static_min_payload_bytes(&fc.args[1]);
        if floor >= Self::NOTIFY_PAYLOAD_MAX_BYTES {
            return Err(self.type_err(&format!(
                "notify_raw(): this payload is at least {floor} bytes, which is at or over PostgreSQL's {}-byte \
                 NOTIFY payload limit",
                Self::NOTIFY_PAYLOAD_MAX_BYTES
            )));
        }

        Ok(IrExpr::FunctionCall(super::IrFunctionCall {
            return_pg_type: None,
            schema: None,
            name: "pg_notify".to_string(),
            args: vec![channel_ir, payload_ir],
            sql_template: None,
        }))
    }

    /// The `GLOBALS_ARG` value to pass when calling `qualified`, or `None` if
    /// that function does not take one.
    ///
    /// Inside a function body the caller's own argument is forwarded verbatim;
    /// at the top level every session global is packed, rather than just the
    /// ones the callee happens to read. Packing the whole set costs one small
    /// jsonb per call and keeps the caller from having to know anything about
    /// the callee's body.
    fn globals_arg_for_call(&mut self, qualified: &str) -> Result<Option<IrExpr>, PyQLError> {
        if self.fns_needing_globals.is_none() {
            self.fns_needing_globals = Some(functions_needing_globals(self.schema).clone());
        }
        if !self.fns_needing_globals.as_ref().is_some_and(|s| s.contains(qualified)) {
            return Ok(None);
        }
        if self.in_fn_body {
            self.used_globals_arg = true;
            return Ok(Some(IrExpr::RawSql(GLOBALS_ARG.to_string())));
        }
        let session_globals: Vec<String> = self
            .schema
            .globals
            .iter()
            .filter(|g| g.computed_expr.is_none())
            .map(|g| format!("{}::{}", g.module, g.name))
            .collect();
        let mut args = Vec::with_capacity(session_globals.len() * 2);
        for name in session_globals {
            let value = self.compile_global(&name)?;
            args.push(IrExpr::Literal(IrLiteral::Str(name)));
            args.push(value);
        }
        Ok(Some(IrExpr::FunctionCall(super::IrFunctionCall {
            return_pg_type: None,
            schema: None,
            name: "jsonb_build_object".to_string(),
            args,
            sql_template: None,
        })))
    }

    // ── User-defined function helpers ─────────────────────────────────────────────

    /// Try to compile `fn(args) { shape }` as a `FunctionSelect` for an object-returning
    /// user function.  Returns `None` if no matching user function exists (so the caller
    /// can fall through to other dispatch paths).
    fn try_compile_fn_object_select(
        &mut self,
        fc: &ast::FunctionCall,
        elements: &[ast::ShapeElement],
        s: &ast::SelectStmt,
        distinct: bool,
    ) -> Result<Option<IrFunctionSelect>, PyQLError> {
        use crate::schema::FunctionDescriptor;

        let fd: Option<&FunctionDescriptor> = self.schema.functions.iter().find(|f| {
            let module_matches = fc.module.as_deref().map(|m| m == f.module.as_str()).unwrap_or(true);
            module_matches && f.name == fc.name && f.return_is_object
        });
        let fd = match fd {
            Some(f) => f,
            None => return Ok(None),
        };
        if fd.params.len() != fc.args.len() {
            return Err(self.type_err(&format!(
                "function '{}::{}' expects {} argument(s), got {}",
                fd.module,
                fd.name,
                fd.params.len(),
                fc.args.len()
            )));
        }

        let fn_module = fd.module.clone();
        let fn_name = fd.name.clone();
        let return_type_name = fd.return_pg_type.clone(); // qualified type name for object returns
        let polymorphic = fd.return_is_polymorphic;

        let mut fn_args = fc
            .args
            .iter()
            .map(|a| self.compile_free_expr(a))
            .collect::<Result<Vec<_>, _>>()?;
        let qualified = format!("{}::{}", fn_module, fn_name);
        if let Some(globals) = self.globals_arg_for_call(&qualified)? {
            fn_args.insert(0, globals);
        }

        let alias = self.fresh_alias();

        // Resolve the return type to build the shape.
        let td = self.resolve_type(&return_type_name)?;
        let td = td.clone();

        let (poly_implementors, poly_columns) = if polymorphic {
            self.collect_poly_info(&return_type_name)
        } else {
            (vec![], vec![])
        };

        let td_module = td.module.clone();
        // Build shape against the return type (treat alias as the source alias).
        let shape = self.compile_shape(elements, &td, &alias, &td_module)?;
        // The shape's own computeds are in scope for the select's clauses,
        // the same as over a type -- added only now, so one pointer still
        // cannot read another.
        let outer_declared = self.active_declared_pointers.clone();
        self.active_declared_pointers
            .extend(elements.iter().filter(|el| el.compexpr.is_some()).cloned());
        let modifiers = self.compile_path_modifiers(s, &td, &alias);
        self.active_declared_pointers = outer_declared;
        let (filter, order_by, offset, limit) = modifiers?;

        Ok(Some(IrFunctionSelect {
            fn_module,
            fn_name,
            fn_args,
            alias,
            type_name: return_type_name,
            polymorphic,
            poly_implementors,
            poly_columns,
            shape,
            filter,
            order_by,
            offset,
            limit,
            distinct,
        }))
    }

    /// The interface's own physical columns (properties + `{link}_id`) — the
    /// subset every concrete implementor table is guaranteed to share, safe
    /// to RETURNING/SELECT uniformly across a poly_implementors fan-out.
    /// Shared by compile_select (read path) and the IrUpdate/IrDelete
    /// builders (write path) so a DML-as-CTE fan-out (sql/mod.rs) can expose
    /// the same columns a polymorphic select would.
    /// Point a shape's single-link sub-selects at the nested-DML CTE that
    /// supplied their foreign key.
    ///
    /// `insert Account { credentials := (insert Credentials { … }) } { ** }`
    /// runs the nested insert as a data-modifying CTE, and Postgres does not
    /// show one statement's CTE writes to the rest of that statement: reading
    /// `access."Credentials"` back finds nothing, so the link hydrated as
    /// `None` even though the row was there on the next statement (confirmed
    /// live). The CTE itself is in scope, and `RETURNING *` gives it every
    /// column the shape asks for, so the sub-select reads that instead.
    fn read_nested_links_from_their_ctes(dml: &IrStmt, dml_cte: Option<&str>, shape: &mut [IrShapePointer]) {
        let (assignments, nested_ctes, appends) = match dml {
            IrStmt::Insert(ins) => (&ins.assignments, &ins.nested_ctes, &ins.multi_link_appends),
            IrStmt::Update(upd) => (&upd.assignments, &upd.nested_ctes, &upd.multi_link_appends),
            _ => return,
        };
        // A multi-link's junction rows are written by this statement too, in
        // a CTE the emitter names after the DML's own — see
        // `emit_insert_multilink_ctes`. The targets themselves come from the
        // append's value source, which for a nested insert is one of
        // `nested_ctes`.
        if let Some(dml_cte) = dml_cte {
            for pointer in shape.iter_mut() {
                let IrShapePointer::MultiLink(link) = pointer else {
                    continue;
                };
                let IrMultiLinkJoin::Standard { junction_table, .. } = &mut link.join else {
                    continue;
                };
                let Some(index) = appends.iter().position(|a| a.junction_table == *junction_table) else {
                    continue;
                };
                *junction_table = format!("@cte:{dml_cte}__ml_add_{index}");
                if let IrMultiLinkValueSource::CteRef(target_cte) = &appends[index].values.source {
                    for row in &mut link.subquery.rows {
                        if let IrRowSource::Bound { source, .. } = row {
                            source.table = format!("@cte:{target_cte}");
                            source.poly = None;
                        }
                    }
                }
            }
        }
        if nested_ctes.is_empty() {
            return;
        }
        let from_cte: HashMap<&str, &str> = assignments
            .iter()
            .filter_map(|(column, expr)| match expr {
                IrExpr::ColumnRef { alias, column: c, .. }
                    if c == "id" && nested_ctes.iter().any(|cte| cte.name == *alias) =>
                {
                    Some((column.as_str(), alias.as_str()))
                }
                _ => None,
            })
            .collect();
        if from_cte.is_empty() {
            return;
        }
        for pointer in shape {
            let IrShapePointer::SingleLink(link) = pointer else {
                continue;
            };
            let IrSingleLinkCorrelation::Fk { fk_column, .. } = &link.correlation else {
                continue;
            };
            let Some(cte_name) = from_cte.get(fk_column.as_str()) else {
                continue;
            };
            for row in &mut link.subquery.rows {
                if let IrRowSource::Bound { source, .. } = row {
                    source.table = format!("@cte:{cte_name}");
                    source.poly = None;
                }
            }
        }
    }

    fn poly_dml_columns(td: &TypeDescriptor) -> Vec<String> {
        td.properties
            .iter()
            .map(|p| p.name.clone())
            .chain(
                td.links
                    .iter()
                    .filter(|l| !l.is_junction_backed())
                    .map(|l| format!("{}_id", l.name)),
            )
            .collect()
    }

    /// A nested SELECT over a link's target, expanded inline over the
    /// interface's implementors when the target is one.
    ///
    /// An interface is materialised as a view that carries only the
    /// interface's own columns -- no discriminator -- so reading a link
    /// through it tags every row as the interface itself and hydrates the
    /// interface class rather than the concrete one. Expanding the
    /// implementors inline is what the root of a query already does, and each
    /// branch supplies its own `__type__`.
    fn link_target_select(
        &self,
        target_td: &TypeDescriptor,
        mut source: IrSource,
        shape: Vec<IrShapePointer>,
    ) -> IrSelect {
        source.poly = self.link_target_fanout(target_td);
        IrSelect::schema_bound(source, shape, None)
    }

    /// The fan-out a link's target needs, for the builders that assemble their
    /// own source rather than going through `link_target_select`.
    fn link_target_fanout(&self, target_td: &TypeDescriptor) -> Option<IrPolyFanout> {
        self.poly_fanout_for(&format!("{}::{}", target_td.module, target_td.name))
    }

    /// Give every interface-typed join target its fan-out, so a traversal that
    /// lands on one reads the implementors and carries the real type rather
    /// than the interface's view, which has no discriminator to carry.
    ///
    /// The root is left alone: a path select fans its own root out through
    /// `poly_implementors` already, and doing it twice would nest the union.
    fn resolve_join_fanouts(&self, path_select: &mut IrPathSelect) {
        for join in &mut path_select.joins {
            let target = match join {
                IrPathJoin::Single { target, .. }
                | IrPathJoin::Multi { target, .. }
                | IrPathJoin::BacklinkSingle { target, .. }
                | IrPathJoin::BacklinkMulti { target, .. }
                | IrPathJoin::Function { target, .. }
                | IrPathJoin::Lateral { target, .. } => target,
            };
            if target.poly.is_none() && !target.table.starts_with("@cte:") {
                target.poly = self.poly_fanout_for(&target.type_name.clone());
            }
        }
    }

    /// The fan-out a source of `type_name` needs, or `None` when it is not an
    /// interface and so reads from a table of its own. See `IrSource::poly`.
    fn poly_fanout_for(&self, type_name: &str) -> Option<IrPolyFanout> {
        let td = self
            .schema
            .types
            .iter()
            .find(|t| format!("{}::{}", t.module, t.name) == type_name)?;
        // A materialised interface has a view to read; a plain abstract has no
        // relation at all, so reading its table name finds nothing. Both are
        // answered by the union of the types that carry the columns.
        if !td.abstract_ && !self.has_subtypes(td) {
            return None;
        }
        let (implementors, columns) = self.collect_poly_info(type_name);
        Some(IrPolyFanout { implementors, columns })
    }

    /// Collect poly_implementors and poly_columns for a polymorphic return type.
    fn collect_poly_info(&self, type_name: &str) -> (Vec<IrPolyImplementor>, Vec<String>) {
        let implementors = self.find_poly_implementors(type_name);
        let columns = if let Some(td) = self
            .schema
            .types
            .iter()
            .find(|t| format!("{}::{}", t.module, t.name) == type_name)
        {
            // The same set the DML path fans out (`poly_dml_columns`): the
            // interface's single-link FKs belong in it too, or reading
            // `.profile` off an interface-typed source finds no
            // `profile_id` column in the union it was fanned out into.
            Self::poly_dml_columns(td)
        } else {
            vec![]
        };
        (implementors, columns)
    }

    // ── vector::search ────────────────────────────────────────────────────────────

    /// Try to compile `vector::search` from a function-call AST node.
    ///
    /// Two overloads are supported:
    /// - `vector::search(TypeName, $vec [, index_name := '…'])` — pre-computed vector
    /// - `vector::search(TypeName, query := $text [, index_name := '…'])` — text overload;
    ///   the Python layer embeds the text and injects `__deferred_vec__` before execution.
    ///
    /// Returns `None` if the call is not `vector::search`.
    fn try_compile_vector_search(
        &mut self,
        fc: &ast::FunctionCall,
        elements: &[ast::ShapeElement],
        s: &ast::SelectStmt,
    ) -> Result<Option<IrVectorSearch>, PyQLError> {
        if fc.module.as_deref() != Some("vector") || fc.name != "search" {
            return Ok(None);
        }

        // Detect text overload: `query :=` kwarg present (no positional second arg needed).
        let text_query_arg = fc.kwargs.iter().find(|(k, _)| k == "query").map(|(_, v)| v);
        let is_text_overload = text_query_arg.is_some();

        if !is_text_overload && fc.args.len() < 2 {
            return Err(
                self.type_err("vector::search requires either a positional vector argument or `query := $text`")
            );
        }

        // First argument: a type name or a filtered subquery narrowing the candidate set.
        //   - Bare name:     `Product` or `default::Product`
        //   - Subquery:      `(select Product filter .price < 100)`
        //
        // For the subquery form we store the raw inner filter AST and compile it below,
        // after the source alias is generated, so property column refs use the right alias.
        let (type_qname, inner_filter_ast): (String, Option<ast::Expr>) = match &fc.args[0] {
            ast::Expr::Path(p) if !p.partial => {
                let name = p.steps.iter()
                    .filter_map(|s| if let ast::PathStep::Name(n) = s { Some(n.as_str()) } else { None })
                    .collect::<Vec<_>>().join("::");
                let td = self.resolve_type(&name)
                    .map_err(|_| self.type_err(&format!("vector::search: '{}' is not a known type", name)))?;
                (format!("{}::{}", td.module, td.name), None)
            }
            ast::Expr::SubQuery(stmt) => {
                if let ast::Stmt::Select(inner_sel) = stmt.as_ref() {
                    let inner_type_name = match &inner_sel.result {
                        ast::Expr::Path(p) if !p.partial => {
                            p.steps.iter()
                                .filter_map(|s| if let ast::PathStep::Name(n) = s { Some(n.as_str()) } else { None })
                                .collect::<Vec<_>>().join("::")
                        }
                        _ => return Err(self.type_err(
                            "vector::search: subquery first argument must select a single type (e.g. select Product filter …)"
                        )),
                    };
                    let td = self.resolve_type(&inner_type_name)
                        .map_err(|_| self.type_err(&format!("vector::search: '{}' is not a known type", inner_type_name)))?;
                    let qname = format!("{}::{}", td.module, td.name);
                    (qname, inner_sel.filter.clone())
                } else {
                    return Err(self.type_err("vector::search: subquery first argument must be a SELECT"));
                }
            }
            _ => return Err(self.type_err(
                "vector::search: first argument must be a type name or a filtered subquery (e.g. select Product filter …)"
            )),
        };

        // Optional named argument: index_name := '…'
        let index_name: Option<String> = fc.kwargs.iter().find(|(k, _)| k == "index_name").and_then(|(_, v)| {
            if let ast::Expr::Literal(ast::Literal::Str(s)) = v {
                Some(s.clone())
            } else {
                None
            }
        });

        // Resolve the type and find the VectorIndex.
        let td = self.resolve_type(&type_qname)?.clone();
        let vi = td
            .vector_indexes
            .iter()
            .find(|vi| vi.index_name.as_deref() == index_name.as_deref())
            .ok_or_else(|| {
                let key = index_name.as_deref().unwrap_or("<default>");
                self.type_err(&format!("type '{}' has no vector index '{}'", type_qname, key))
            })?;

        let vector_col = vi.column_name();
        let distance_op = match vi.metric.as_str() {
            "euclidean" => "<->",
            "inner_product" => "<#>",
            _ => "<=>", // cosine (default)
        };

        // Build query expression and inference fields.
        let (
            query_expr,
            inference_query_param_name,
            inference_query_literal,
            inference_model,
            inference_type_name,
            inference_index_name,
        );

        if is_text_overload {
            // Text overload: register __deferred_vec__ as the SQL param; Python injects
            // the embedding result into it before executing the query.
            let vec_idx = self.param_index("__deferred_vec__");
            let vec_param = IrExpr::Param { index: vec_idx };
            // Cast float8[] → vector so a Python list[float] encodes natively.
            let inner_cast = IrExpr::TypeCast(Box::new(IrTypeCast {
                expr: vec_param,
                pg_type: "float8[]".to_string(),
                tuple_shape: None,
            }));
            query_expr = IrExpr::TypeCast(Box::new(IrTypeCast {
                expr: inner_cast,
                pg_type: "vector".to_string(),
                tuple_shape: None,
            }));
            let query_arg = text_query_arg.unwrap();
            inference_query_param_name = Some(match query_arg {
                ast::Expr::Parameter(name) => name.clone(),
                _ => String::new(),
            });
            inference_query_literal = match query_arg {
                ast::Expr::Literal(ast::Literal::Str(s)) => Some(s.clone()),
                _ => None,
            };
            inference_model = Some(vi.model.clone());
            inference_type_name = Some(type_qname.clone());
            inference_index_name = Some(index_name.clone());
        } else {
            // Vector overload: second positional arg is the pre-computed vector.
            let raw_query_expr = self.compile_free_expr(&fc.args[1])?;
            query_expr = IrExpr::TypeCast(Box::new(IrTypeCast {
                expr: raw_query_expr,
                pg_type: "vector".to_string(),
                tuple_shape: None,
            }));
            inference_query_param_name = None;
            inference_query_literal = None;
            inference_model = None;
            inference_type_name = None;
            inference_index_name = None;
        }

        let alias = self.fresh_alias();
        let source = IrSource {
            poly: None,
            type_name: type_qname.clone(),
            table: td.table.clone(),
            alias: alias.clone(),
        };

        // Compile inner_filter_ast (from subquery first arg) now that we have the alias,
        // so property column refs (e.g. `.price`) use the correct table alias.
        let pre_filter: Option<IrExpr> = match inner_filter_ast {
            Some(ref f) => Some(self.compile_expr(f, &td, &alias)?),
            None => None,
        };

        // Compile the object shape from `object { … }` inside the shape elements.
        // `elements` is the outer shape (`{ object { … }, distance }`).
        // We find the `object` element and take its sub-shape; everything else is ignored
        // at compile time (distance is always emitted; unknown pointers are an error).
        let mut object_shape: Vec<IrShapePointer> = vec![];
        for el in elements {
            if el.splat.is_some() {
                continue;
            } // ignore splat in outer shape
            let pointer_name = match el.path.steps.first() {
                Some(ast::PathStep::Name(n)) => n.as_str(),
                _ => continue,
            };
            match pointer_name {
                "distance" => { /* always emitted; no sub-shape */ }
                "object" => {
                    let sub_els = el.nested.as_deref().unwrap_or(&[]);
                    object_shape = self.compile_shape(sub_els, &td, &alias, &td.module)?;
                }
                other => {
                    return Err(self.type_err(&format!(
                        "vector::search result has no pointer '{}'; valid pointers are 'object' and 'distance'",
                        other
                    )));
                }
            }
        }

        let (outer_filter, order_by_distance, offset, limit) = self.compile_vs_modifiers(s)?;

        // Merge pre_filter (from subquery first arg) with any outer filter via AND.
        let filter = match (pre_filter, outer_filter) {
            (Some(a), Some(b)) => Some(IrExpr::BinOp(Box::new(IrBinOp {
                left: a,
                op: ast::BinOpKind::And,
                right: b,
            }))),
            (Some(f), None) | (None, Some(f)) => Some(f),
            (None, None) => None,
        };

        Ok(Some(IrVectorSearch {
            source,
            vector_col,
            distance_op,
            query_expr,
            object_shape,
            filter,
            order_by_distance,
            offset,
            limit,
            inference_query_param_name,
            inference_query_literal,
            inference_model,
            inference_type_name,
            inference_index_name,
        }))
    }

    /// Compile `order by`, `filter`, `offset`, `limit` for a VectorSearch source.
    /// Recognises `.distance` (relative path) as the distance expression.
    fn compile_vs_modifiers(&mut self, s: &ast::SelectStmt) -> Result<SearchModifiers, PyQLError> {
        let mut order_by_distance: Option<IrSortDir> = None;
        for sort in &s.order_by {
            let is_distance = matches!(&sort.expr,
                ast::Expr::Path(p) if p.partial && p.steps.len() == 1
                    && matches!(&p.steps[0], ast::PathStep::Name(n) if n == "distance")
            );
            if is_distance {
                let dir = match sort.direction {
                    ast::SortDirection::Desc => IrSortDir::Desc,
                    ast::SortDirection::Asc => IrSortDir::Asc,
                };
                order_by_distance = Some(dir);
            } else {
                return Err(self.type_err("vector::search: only 'order by .distance' is supported as a sort key"));
            }
        }

        let filter = match &s.filter {
            Some(f) => Some(self.compile_free_expr(f)?),
            None => None,
        };
        let offset = match &s.offset {
            Some(o) => Some(self.compile_free_expr(o)?),
            None => None,
        };
        let limit = match &s.limit {
            Some(l) => Some(self.compile_free_expr(l)?),
            None => None,
        };

        Ok((filter, order_by_distance, offset, limit))
    }

    // ── fts::search ──────────────────────────────────────────────────────────────

    /// Try to compile `fts::search(TypeName, $query [, index_name := '…'] [, mode := '…'])`.
    /// Returns `None` if the call is not `fts::search`.
    fn try_compile_fts_search(
        &mut self,
        fc: &ast::FunctionCall,
        elements: &[ast::ShapeElement],
        s: &ast::SelectStmt,
    ) -> Result<Option<IrFtsSearch>, PyQLError> {
        if fc.module.as_deref() != Some("fts") || fc.name != "search" {
            return Ok(None);
        }
        if fc.args.len() < 2 {
            return Err(self.type_err("fts::search requires at least 2 arguments: (TypeName, $query)"));
        }

        // First argument: a bare type name reference.
        let type_qname = match &fc.args[0] {
            ast::Expr::Path(p) if !p.partial && p.steps.len() == 1 => {
                if let ast::PathStep::Name(n) = &p.steps[0] {
                    let td = self
                        .resolve_type(n)
                        .map_err(|_| self.type_err(&format!("fts::search: '{}' is not a known type", n)))?;
                    format!("{}::{}", td.module, td.name)
                } else {
                    return Err(self.type_err("fts::search: first argument must be a type name"));
                }
            }
            _ => return Err(self.type_err("fts::search: first argument must be a bare type name")),
        };

        // Optional named arguments.
        let index_name: Option<String> = fc.kwargs.iter().find(|(k, _)| k == "index_name").and_then(|(_, v)| {
            if let ast::Expr::Literal(ast::Literal::Str(s)) = v {
                Some(s.clone())
            } else {
                None
            }
        });

        let mode_str = fc
            .kwargs
            .iter()
            .find(|(k, _)| k == "mode")
            .and_then(|(_, v)| {
                if let ast::Expr::Literal(ast::Literal::Str(s)) = v {
                    Some(s.as_str())
                } else {
                    None
                }
            })
            .unwrap_or("BestFields");

        let tsquery_fn: &'static str = match mode_str {
            "Phrase" => "phraseto_tsquery",
            _ => "websearch_to_tsquery", // BestFields and PhrasePrefix both use websearch
        };

        // Resolve the type and find the SearchIndex.
        let td = self.resolve_type(&type_qname)?.clone();
        let si = td
            .search_indexes
            .iter()
            .find(|si| si.index_name.as_deref() == index_name.as_deref())
            .ok_or_else(|| {
                let key = index_name.as_deref().unwrap_or("<default>");
                self.type_err(&format!("type '{}' has no search index '{}'", type_qname, key))
            })?;

        let backend = si.backend.clone();
        let search_col = si.column_name();
        let is_deferred = backend != SearchBackend::Postgres;
        let deferred_index_name = if is_deferred {
            Some(si.deferred_index_name(&td.module, &td.name))
        } else {
            None
        };

        // Second argument: the query text expression.
        // For deferred backends, IDs/scores are the only SQL params ($1/$2). The query
        // text is consumed by the Python layer before SQL execution, so we extract its
        // name/literal directly from the AST without registering a SQL param for it.
        let query_expr;
        let deferred_query_param_name;
        let deferred_query_literal;
        let deferred_ids_param;
        let deferred_scores_param;

        if is_deferred {
            let ids_idx = self.param_index("__deferred_ids__");
            let scores_idx = self.param_index("__deferred_scores__");
            deferred_ids_param = Some(ids_idx);
            deferred_scores_param = Some(scores_idx);
            deferred_query_param_name = match &fc.args[1] {
                ast::Expr::Parameter(name) => Some(name.clone()),
                _ => None,
            };
            deferred_query_literal = match &fc.args[1] {
                ast::Expr::Literal(ast::Literal::Str(s)) => Some(s.clone()),
                _ => None,
            };
            // Placeholder — not used in SQL for the deferred backend.
            query_expr = IrExpr::Literal(crate::ir::IrLiteral::Str(String::new()));
        } else {
            query_expr = self.compile_free_expr(&fc.args[1])?;
            deferred_query_param_name = None;
            deferred_query_literal = None;
            deferred_ids_param = None;
            deferred_scores_param = None;
        }

        let alias = self.fresh_alias();
        let source = IrSource {
            poly: None,
            type_name: type_qname.clone(),
            table: td.table.clone(),
            alias: alias.clone(),
        };

        // Compile the object shape from `object { … }` in the outer shape.
        let mut object_shape: Vec<IrShapePointer> = vec![];
        for el in elements {
            if el.splat.is_some() {
                continue;
            }
            let pointer_name = match el.path.steps.first() {
                Some(ast::PathStep::Name(n)) => n.as_str(),
                _ => continue,
            };
            match pointer_name {
                "score" => { /* always emitted */ }
                "object" => {
                    let sub_els = el.nested.as_deref().unwrap_or(&[]);
                    object_shape = self.compile_shape(sub_els, &td, &alias, &td.module)?;
                }
                other => {
                    return Err(self.type_err(&format!(
                        "fts::search result has no pointer '{}'; valid pointers are 'object' and 'score'",
                        other
                    )));
                }
            }
        }

        let (filter, order_by_rank, offset, limit) = self.compile_fts_modifiers(s)?;

        Ok(Some(IrFtsSearch {
            source,
            backend,
            search_col,
            tsquery_fn,
            query_expr,
            object_shape,
            filter,
            order_by_rank,
            offset,
            limit,
            deferred_index_name,
            deferred_query_param_name,
            deferred_query_literal,
            deferred_ids_param,
            deferred_scores_param,
        }))
    }

    /// Compile `order by`, `filter`, `offset`, `limit` for a FtsSearch source.
    /// Recognises `.score` (relative path) as the score expression.
    fn compile_fts_modifiers(&mut self, s: &ast::SelectStmt) -> Result<SearchModifiers, PyQLError> {
        let mut order_by_rank: Option<IrSortDir> = None;
        for sort in &s.order_by {
            let is_rank = matches!(&sort.expr,
                ast::Expr::Path(p) if p.partial && p.steps.len() == 1
                    && matches!(&p.steps[0], ast::PathStep::Name(n) if n == "score")
            );
            if is_rank {
                let dir = match sort.direction {
                    ast::SortDirection::Desc => IrSortDir::Desc,
                    ast::SortDirection::Asc => IrSortDir::Asc,
                };
                order_by_rank = Some(dir);
            } else {
                return Err(self.type_err("fts::search: only 'order by .score' is supported as a sort key"));
            }
        }

        let filter = match &s.filter {
            Some(f) => Some(self.compile_free_expr(f)?),
            None => None,
        };
        let offset = match &s.offset {
            Some(o) => Some(self.compile_free_expr(o)?),
            None => None,
        };
        let limit = match &s.limit {
            Some(l) => Some(self.compile_free_expr(l)?),
            None => None,
        };

        Ok((filter, order_by_rank, offset, limit))
    }

    // ── Error helpers ─────────────────────────────────────────────────────────────

    fn type_err(&self, msg: &str) -> PyQLError {
        PyQLError::Type(PyQLTypeError {
            message: msg.to_string(),
            position: Position { line: 0, col: 0 },
        })
    }

    fn field_err(&self, field: &str, type_name: &str) -> PyQLError {
        if std::env::var("PYLON_DBG_FIELD_ERR").is_ok() {
            eprintln!(
                "DBG field_err {field} on {type_name}
{}",
                std::backtrace::Backtrace::force_capture()
            );
        }
        let suggestion = self
            .schema
            .types
            .iter()
            .find(|t| format!("{}::{}", t.module, t.name) == type_name)
            .and_then(|td| Self::suggest_pointer_name(td, field));
        let message = match suggestion {
            Some(s) => format!("object type '{type_name}' has no link or property '{field}'. Did you mean '{s}'?"),
            None => format!("object type '{type_name}' has no link or property '{field}'"),
        };
        PyQLError::Resolution(PyQLResolutionError::UnknownField(PyQLUnknownFieldError {
            message,
            position: Position { line: 0, col: 0 },
        }))
    }

    /// A ` — did you mean …?` fragment for an unresolvable function name, or
    /// an empty string.
    ///
    /// Mirrors `pylon.stdlib.unknown_function_message`, which has always
    /// offered this for the `std.foo(...)` attribute form; a name written as
    /// PyQL text got nothing, which is how a schema converted from a system
    /// that spelled it `uuid_generate_v7j` stayed broken instead of being
    /// pointed one character back at `uuid_generate_v7`.
    ///
    /// The wrong-namespace check comes first and is worth its own wording:
    /// the namespaces overlap unevenly — `sqrt`/`abs`/`ceil` are in both
    /// `std` and `math`, while `pi`/`ln`/`exp` are only in `math` — so
    /// guessing the wrong one is routine, and naming where the function
    /// actually lives recovers from it in a way a fuzzy match over the
    /// namespace that lacks it cannot.
    fn suggest_function_name(&self, ns: &str, name: &str) -> String {
        const MIN_SIMILARITY: f64 = 0.7;
        if let Some(other) = ["std", "math", "cal", "sys"]
            .into_iter()
            .find(|o| *o != ns && !crate::stdlib::lookup(o, name).is_empty())
        {
            return format!(" — it lives in {other}, use {other}::{name}()");
        }
        crate::stdlib::registry()
            .iter()
            .filter(|d| d.namespace == ns)
            .map(|d| (format!("{ns}::{}", d.name), d.name))
            .chain(
                self.schema
                    .functions
                    .iter()
                    .map(|f| (format!("{}::{}", f.module, f.name), f.name.as_str())),
            )
            .map(|(qualified, candidate)| (qualified, strsim::jaro_winkler(name, candidate)))
            .filter(|(_, score)| *score >= MIN_SIMILARITY)
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(qualified, _)| format!(" — did you mean {qualified}()?"))
            .unwrap_or_default()
    }

    /// Fuzzy-matches `name` against every pointer (property/link/multilink/
    /// computed — Pylon's term for a type's own attributes; "field" is a
    /// Postgres-level term that doesn't apply here) on `td`, returning the
    /// closest candidate when it's plausibly a typo — powers a
    /// "Did you mean X?" suggestion for an unknown property/link.
    /// Jaro-Winkler (favors a shared prefix, which is where most real typos
    /// preserve the most characters, e.g. `nam` -> `name`) with a
    /// conservative similarity floor, so an unrelated pointer never gets
    /// suggested just because it happens to be the "closest" among an
    /// otherwise-dissimilar set of candidates.
    fn suggest_pointer_name(td: &TypeDescriptor, name: &str) -> Option<String> {
        const MIN_SIMILARITY: f64 = 0.7;
        td.properties
            .iter()
            .map(|p| p.name.as_str())
            .chain(td.links.iter().map(|l| l.name.as_str()))
            .chain(td.multilinks.iter().map(|m| m.name.as_str()))
            .chain(td.computed.iter().map(|c| c.name.as_str()))
            .map(|candidate| (candidate, strsim::jaro_winkler(name, candidate)))
            .filter(|(_, score)| *score >= MIN_SIMILARITY)
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(name, _)| name.to_string())
    }

    // ── Default returning (pk only) ────────────────────────────────────────────

    /// For bare DML (not wrapped in SELECT) return only primary-key properties:
    /// `INSERT … ` returns `{ id }`, same for UPDATE/DELETE.
    fn pk_returning(td: &TypeDescriptor) -> Vec<IrShapePointer> {
        td.properties
            .iter()
            .filter(|p| p.is_pk)
            .map(|p| {
                IrShapePointer::Scalar(IrScalarPointer {
                    implicit_id: false,
                    marker_offset: None,
                    alias: p.name.clone(),
                    column: p.name.clone(),
                    pg_type: p.pg_type.clone(),
                    tuple_shape: None,
                })
            })
            .collect()
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────────────

/// True for `<json>` / `<std::json>` — the one cast target that turns its
/// operand into output text rather than another value.
fn casts_to_json(ty: &ast::TypeExpr) -> bool {
    matches!(ty.as_named(), Some((module, "json")) if module.is_none_or(|m| m == "std"))
}

/// True if any node in a multilink value tree (including both sides of any
/// nested `union`) carries a `@prop := value` link-property assignment.
fn has_any_link_props(vals: &IrMultiLinkValues) -> bool {
    if !vals.link_props.is_empty() {
        return true;
    }
    match &vals.source {
        IrMultiLinkValueSource::Union(a, b) => has_any_link_props(a) || has_any_link_props(b),
        _ => false,
    }
}

/// True for a bare `{}` or a `<AnyType>{}` cast of one — the empty-set
/// literal a caller uses to clear an optional pointer, in either form. A
/// frontend generating PyQL typically emits the cast form (e.g.
/// `<Company>{}`, matching `compile_expr`'s own `Expr::TypeCast` handling of
/// this exact case), while hand-written PyQL more often uses the bare form.
fn is_empty_set_expr(expr: &Expr) -> bool {
    match expr {
        Expr::Set(elems) => elems.is_empty(),
        Expr::TypeCast(tc) => matches!(&tc.expr, Expr::Set(elems) if elems.is_empty()),
        _ => false,
    }
}

/// Extract the single pointer name from a relative path used in a shape element.
fn path_leaf(p: &ast::Path) -> Result<&str, PyQLError> {
    match p.steps.as_slice() {
        [ast::PathStep::Name(n)] => Ok(n.as_str()),
        _ => Err(PyQLError::Type(PyQLTypeError {
            message: "expected a simple pointer name in shape element".into(),
            position: Position { line: 0, col: 0 },
        })),
    }
}

/// Map a PyQL type expression to a PostgreSQL type string.
fn type_expr_to_pg(ty: &ast::TypeExpr) -> Result<String, PyQLError> {
    let Some((module, bare_name)) = ty.as_named() else {
        // Callers resolve a structural tuple/array directly before ever
        // reaching this function (see `resolve_cast_pg_type`) — reaching here
        // with one would be an internal bug, not a user-facing scenario.
        return Err(PyQLError::Type(PyQLTypeError {
            message: "internal error: structural tuple/array type reached type_expr_to_pg".into(),
            position: Position { line: 0, col: 0 },
        }));
    };

    // pgvector:: types map directly to PostgreSQL types.
    if module == Some("pgvector") {
        return match bare_name {
            "vector" => Ok("vector".to_string()),
            other => Err(PyQLError::Type(PyQLTypeError {
                message: format!("unknown pgvector type '{other}'; valid types are: vector"),
                position: Position { line: 0, col: 0 },
            })),
        };
    }

    // postgis:: types map directly to PostgreSQL types.
    if module == Some("postgis") {
        return match bare_name {
            "geometry" => Ok("geometry".to_string()),
            "geography" => Ok("geography".to_string()),
            "box2d" => Ok("box2d".to_string()),
            "box3d" => Ok("box3d".to_string()),
            other => Err(PyQLError::Type(PyQLTypeError {
                message: format!("unknown postgis type '{other}'; valid types are: geometry, geography, box2d, box3d"),
                position: Position { line: 0, col: 0 },
            })),
        };
    }

    // cal:: types map directly to PostgreSQL types.
    if module == Some("cal") {
        let pg = match bare_name {
            "local_datetime" => "timestamp",
            "local_date" => "date",
            "local_time" => "time",
            "relative_duration" | "date_duration" => "interval",
            other => {
                return Err(PyQLError::Type(PyQLTypeError {
                    message: format!(
                        "unknown cal type '{other}'; \
                     valid types are: local_datetime, local_date, local_time, \
                     relative_duration, date_duration"
                    ),
                    position: Position { line: 0, col: 0 },
                }));
            }
        };
        return Ok(pg.to_string());
    }

    let name = match module {
        Some("std") | None => bare_name,
        Some(m) => {
            return Err(PyQLError::Type(PyQLTypeError {
                message: format!("unknown type '{}::{}'", m, bare_name),
                position: Position { line: 0, col: 0 },
            }));
        }
    };
    Ok(match name {
        "str" => "text",
        "int16" => "int2",
        "int32" => "int4",
        "int64" => "int8",
        "float32" => "float4",
        "float64" => "float8",
        "bool" => "boolean",
        "uuid" => "uuid",
        "bytes" => "bytea",
        "json" => "jsonb",
        "decimal" => "numeric",
        // bigint and decimal are both PostgreSQL `numeric` — the distinction
        // is a Pylon-level scale/precision convention, not a separate PG type.
        "bigint" => "numeric",
        "datetime" => "timestamptz",
        "date" => "date",
        "time" => "time",
        "duration" => "interval",
        other => {
            return Err(PyQLError::Type(PyQLTypeError {
                message: format!("unknown type '{other}'"),
                position: Position { line: 0, col: 0 },
            }));
        }
    }
    .to_string())
}

/// Check whether a compiled expression is compatible with a PylonType parameter.
/// Used for overload selection when multiple overloads share the same name.
/// Emit `($1 IS NOT NULL)` for a given IR expression.
fn ir_is_not_null(expr: IrExpr) -> IrExpr {
    IrExpr::FunctionCall(IrFunctionCall {
        return_pg_type: None,
        schema: None,
        name: String::new(),
        args: vec![expr],
        sql_template: Some("($1 IS NOT NULL)".to_string()),
    })
}

/// "1 argument(s)" / "2 or 3 argument(s)" / "at least 1 argument(s)" — the
/// arities an overload set accepts, worded as `pylon.stdlib._arity_error`
/// words the same rejection on the Python side.
fn describe_arities(overloads: &[&crate::stdlib::FnDescriptor]) -> String {
    let mut arities: Vec<usize> = overloads.iter().map(|d| d.params.len()).collect();
    arities.sort_unstable();
    arities.dedup();
    if overloads.iter().any(|d| d.is_variadic()) {
        return format!("at least {} argument(s)", arities[0].saturating_sub(1));
    }
    let list = arities.iter().map(usize::to_string).collect::<Vec<_>>().join(" or ");
    format!("{list} argument(s)")
}

/// The argument types as far as they could be inferred, for an error that
/// has to show the caller what it actually passed.
fn describe_args(args: &[IrExpr]) -> String {
    args.iter()
        .map(|a| infer_ir_type(a).map_or("?", literal_sentinel_to_pg))
        .collect::<Vec<_>>()
        .join(", ")
}

/// The parameter lists of the overloads that did match on arity, in PyQL
/// spelling — what the caller should have passed.
fn describe_signatures(overloads: &[&crate::stdlib::FnDescriptor]) -> String {
    overloads
        .iter()
        .map(|d| {
            let params = d.params.iter().map(|p| p.ty.pyql_name()).collect::<Vec<_>>().join(", ");
            format!("({params})")
        })
        .collect::<Vec<_>>()
        .join(" or ")
}

/// The parameter each of `argc` arguments is checked against.
///
/// One per declared parameter, except that a trailing variadic one stands in
/// for every argument past the fixed ones — `json_get(j, 'a', 'b')` checks
/// both path elements against the single variadic `str` parameter rather
/// than leaving the third argument unchecked, which a plain `params.iter()`
/// zipped against the arguments would do.
fn params_for_args(d: &crate::stdlib::FnDescriptor, argc: usize) -> impl Iterator<Item = &crate::stdlib::Param> {
    let last = d.params.len().saturating_sub(1);
    let repeat_from = d.is_variadic().then_some(last);
    (0..argc).filter_map(move |i| match repeat_from {
        Some(v) if i >= v => d.params.get(v),
        _ => d.params.get(i),
    })
}

fn pylon_type_matches(expr: &IrExpr, ty: &crate::stdlib::PylonType) -> bool {
    use crate::stdlib::PylonType as PT;
    match ty {
        // Wildcard params always match.
        PT::Any | PT::AnyOrderable | PT::AnyPoint => true,
        PT::Array(_) => is_array_expr(expr),
        // Matched on the concrete PostgreSQL type name, which for a
        // multirange is `int8multirange`/`tstzmultirange`/… — it carries the
        // element family as a prefix, so "is a multirange" is a `contains`,
        // not a `starts_with`, and "is a plain range" has to exclude it.
        PT::Range(_) => matches!(infer_ir_type(expr), Some(t) if t.ends_with("range") && !t.contains("multirange")),
        PT::Multirange(_) => matches!(infer_ir_type(expr), Some(t) if t.contains("multirange")),
        // Every parameter type that names a concrete PostgreSQL scalar is
        // judged by `types_compatible` — the one implicit-cast graph the
        // rest of the compiler already resolves operators against — rather
        // than by an exact type-name match. Exactness rejected an integer
        // literal reaching a `float64` parameter, which is how
        // `cal::to_relative_duration(seconds := 3)` and every other
        // int-for-float argument reads.
        //
        // An argument whose type cannot be inferred does *not* match a
        // parameter that names one: an overload is chosen only on evidence,
        // and `resolve_fn_call` reports the call rather than guessing.
        // For a parameter type with no scalar spelling (`optional<…>` and
        // friends) there is nothing to judge, so allow.
        _ => match (ty.scalar_pg_type(), infer_ir_type(expr)) {
            (Some(declared), Some(known)) => types_compatible(known, declared),
            (Some(_), None) => false,
            (None, _) => true,
        },
    }
}

/// True for a call like `array_unpack` that yields a set rather than one value.
fn expr_returns_set(expr: &Expr) -> bool {
    let Expr::FunctionCall(call) = expr else {
        return false;
    };
    crate::stdlib::lookup(call.module.as_deref().unwrap_or("std"), &call.name)
        .iter()
        .any(|d| d.returns_set())
}

fn literal_sentinel_to_pg(t: &str) -> &str {
    match t {
        "__int_literal" => "int8",
        "__float_literal" => "float8",
        other => other,
    }
}

fn is_array_expr(expr: &IrExpr) -> bool {
    match through_coalesce(expr) {
        IrExpr::Array(_) | IrExpr::ArrayFromSelect(_) => true,
        // `str_split(…)[-1]` — a stdlib call declared to return an array,
        // which `infer_ir_type` cannot spell because it only names scalars.
        IrExpr::FunctionCall(f) if f.schema.is_none() => {
            let mut overloads = crate::stdlib::registry().iter().filter(|d| d.name == f.name).peekable();
            overloads.peek().is_some() && overloads.all(|d| matches!(d.return_type, crate::stdlib::PylonType::Array(_)))
        }
        // Everything else an array can arrive as — a column, a cast, a
        // global, a `with` binding, a concatenation of any of those — is
        // known by the type it carries.
        other => matches!(infer_ir_type(other), Some(t) if t.ends_with("[]")),
    }
}

/// A lower bound, computable without running the query, on how many bytes a
/// `notify()` payload will serialize to.
///
/// Only the parts that are already known contribute: string literals count
/// their own length, a concatenation sums its sides, a free object counts the
/// JSON envelope it will always emit (`{}`, the quoted field names, and the
/// `:`/`,` separators) plus whatever its field expressions themselves floor
/// at. Anything runtime-valued — a column, a parameter, a function call —
/// contributes 0, so this never over-estimates and never rejects a payload
/// that could actually have fit.
///
/// Exists because Postgres's 8000-byte NOTIFY cap is enforced at *runtime*,
/// and blowing it aborts the transaction that sent the notification — which,
/// for the composed `with update ... select (notify(...), updated)` shape, is
/// the write itself.
fn static_min_payload_bytes(expr: &ast::Expr) -> usize {
    use crate::parse::ast::{BinOpKind, Expr, Literal};
    match expr {
        Expr::Literal(Literal::Str(s)) => s.len(),
        Expr::BinOp(op) if matches!(op.op, BinOpKind::Concat) => {
            static_min_payload_bytes(&op.left) + static_min_payload_bytes(&op.right)
        }
        Expr::Shape(sh) if sh.expr.is_none() => {
            // `{"a":,"b":}` — braces, one quoted name and colon per field,
            // and a comma between them. Every one of those bytes is emitted
            // regardless of what the values turn out to be.
            let mut total = 2;
            for (i, el) in sh.elements.iter().enumerate() {
                if i > 0 {
                    total += 1;
                }
                let name_len = match el.path.steps.last() {
                    Some(crate::parse::ast::PathStep::Name(n)) => n.len(),
                    _ => 0,
                };
                total += name_len + 3;
                if let Some(value) = &el.compexpr {
                    total += static_min_payload_bytes(value);
                }
            }
            total
        }
        _ => 0,
    }
}

fn expr_to_std_type(expr: &ast::Expr) -> &'static str {
    match expr {
        ast::Expr::Literal(ast::Literal::Str(_)) => "std::str",
        ast::Expr::Literal(ast::Literal::Int(_)) => "std::int64",
        ast::Expr::Literal(ast::Literal::Float(_)) => "std::float64",
        ast::Expr::Literal(ast::Literal::Bool(_)) => "std::bool",
        _ => "anytype",
    }
}

fn named_tuple_type_str(fields: &[(String, ast::Expr)]) -> String {
    let inner = fields
        .iter()
        .map(|(k, v)| format!("{}: {}", k, expr_to_std_type(v)))
        .collect::<Vec<_>>()
        .join(", ");
    format!("tuple<{}>", inner)
}

fn positional_tuple_type_str(elems: &[ast::Expr]) -> String {
    let inner = elems.iter().map(expr_to_std_type).collect::<Vec<_>>().join(", ");
    format!("tuple<{}>", inner)
}

pub(crate) fn infer_ir_type(expr: &IrExpr) -> Option<&str> {
    match expr {
        IrExpr::ColumnRef { pg_type, .. } => Some(pg_type.as_str()),
        IrExpr::TypeCast(tc) => Some(tc.pg_type.as_str()),
        IrExpr::FnParam { pg_type, .. } => Some(pg_type.as_str()),
        IrExpr::Literal(lit) => Some(match lit {
            IrLiteral::Str(_) => "text",
            IrLiteral::Int(_) => "__int_literal",
            IrLiteral::Float(_) => "__float_literal",
            IrLiteral::Bool(_) => "boolean",
        }),
        IrExpr::EnumLiteral { pg_type, .. } => Some(pg_type.as_str()),
        IrExpr::NamedTuple { .. } => Some("jsonb"),
        IrExpr::JsonbField { .. } | IrExpr::JsonbIndex { .. } => Some("jsonb"),
        IrExpr::GlobalParam { pg_type, .. } => Some(pg_type.as_str()),
        // A `with`-bound scalar is typed by what it binds, so a call over one
        // resolves to the same overload the bare value would.
        IrExpr::CteRef { pg_type, .. } => pg_type.as_deref(),
        // A correlated path subquery is typed by whatever it projects — the
        // scalar column at the end of the path. An object-valued one yields
        // an id, which no operator should silently compare against.
        IrExpr::PathSubquery(ps) => match &ps.result {
            IrPathResult::Scalar(e, _) => infer_ir_type(e),
            IrPathResult::Object { .. } => None,
        },
        // `a ++ b` and `distinct a` both yield whatever they were given, so
        // an array stays recognisable as one through either.
        IrExpr::BinOp(b) if b.op == crate::parse::ast::BinOpKind::Concat => {
            infer_ir_type(&b.left).or_else(|| infer_ir_type(&b.right))
        }
        IrExpr::UnaryOp(u) if u.op == crate::parse::ast::UnaryOpKind::Distinct => infer_ir_type(&u.operand),
        // `-x` is a number of x's own type; `not x` and `exists x` are always
        // boolean.
        IrExpr::UnaryOp(u) if u.op == crate::parse::ast::UnaryOpKind::Minus => infer_ir_type(&u.operand),
        IrExpr::UnaryOp(u)
            if matches!(
                u.op,
                crate::parse::ast::UnaryOpKind::Not | crate::parse::ast::UnaryOpKind::Exists
            ) =>
        {
            Some("boolean")
        }
        // `a ?? b` and `a if c else b` yield a value of their branches' own
        // type, so a call over either resolves the overload the bare value
        // would. Whichever side carries a type decides: the other is routinely
        // the untypeable one — an empty set, or a path Gel only knows is
        // optional.
        IrExpr::BinOp(b) if b.op == crate::parse::ast::BinOpKind::Coalesce => {
            infer_ir_type(&b.left).or_else(|| infer_ir_type(&b.right))
        }
        IrExpr::IfElse(ie) => infer_ir_type(&ie.if_).or_else(|| infer_ir_type(&ie.else_)),
        // A slice is the same type as the thing sliced — `substr` of text is
        // text, of bytea is bytea, and an array slice is still that array.
        // Without this a `to_bytes(x)[12:16]` reaching a `bytes` parameter
        // reads as untyped, which is the difference between resolving the
        // bytes overload and resolving nothing at all.
        IrExpr::Slice { expr, .. } => infer_ir_type(expr),
        // `xs[0]` is one element of what `xs` holds — the array type with its
        // `[]` taken off. A string or bytes subscript stays the type it
        // indexes, the way the `substr` it emits does.
        IrExpr::CteFieldRef { pg_type, .. } | IrExpr::ForVar { pg_type, .. } => pg_type.as_deref(),
        IrExpr::Subscript { expr, is_array, .. } => {
            // `str_split(s, '::')[0]`: the array a stdlib call returns is not a
            // type `infer_ir_type` can name (it only names scalars), so the
            // element type comes from the overload's own declared return type.
            let Some(base) = infer_ir_type(expr) else {
                return stdlib_array_element_type(expr);
            };
            if *is_array { base.strip_suffix("[]") } else { Some(base) }
        }
        IrExpr::BinOp(b) => arithmetic_result_type(&b.op, infer_ir_type(&b.left)?, infer_ir_type(&b.right)?),
        // The `coalesce` the compiler itself builds — around an aggregate that
        // ran over nothing, or a `??` whose sides name rows — carries no
        // recorded return type, so it is typed from its arguments like the
        // operator it stands in for.
        IrExpr::FunctionCall(f) if f.schema.is_none() && f.name == "coalesce" => f.args.iter().find_map(infer_ir_type),
        IrExpr::FunctionCall(f) if f.schema.is_none() && matches!(f.name.as_str(), "max" | "min" | "sum") => {
            aggregate_result_type(&f.name, infer_ir_type(f.args.first()?)?)
        }
        IrExpr::AggOverSet {
            fn_name, schema: None, ..
        } if fn_name == "count" => Some("int8"),
        IrExpr::AggOverSet {
            fn_name,
            schema: None,
            elems,
        } => aggregate_result_type(fn_name, infer_ir_type(elems.first()?)?),
        // Any call whose resolution recorded a scalar return type — a stdlib
        // overload (`enc::base64_decode(…)` is bytea) or a user-defined
        // function, which is how a computed pointer's declared type gets
        // checked against the function it calls at all.
        IrExpr::FunctionCall(f) => f.return_pg_type.as_deref(),
        _ => None,
    }
}

/// The element type of an array a stdlib call returns, for an expression whose
/// own type `infer_ir_type` cannot name. `None` unless every overload of the
/// name returns an array of the same scalar — the call would be ambiguous
/// otherwise, and guessing is what overload resolution exists to avoid.
fn stdlib_array_element_type(expr: &IrExpr) -> Option<&'static str> {
    let IrExpr::FunctionCall(f) = expr else {
        return None;
    };
    if f.schema.is_some() {
        return None;
    }
    let mut element: Option<&'static str> = None;
    for descriptor in crate::stdlib::registry().iter().filter(|d| d.name == f.name) {
        let crate::stdlib::PylonType::Array(inner) = &descriptor.return_type else {
            return None;
        };
        let scalar = inner.scalar_pg_type()?;
        if element.is_some_and(|seen| seen != scalar) {
            return None;
        }
        element = Some(scalar);
    }
    element
}

/// What `+` and `-` yield over instants and durations — a datetime minus a
/// datetime is a duration, a datetime shifted by one is a datetime. Gel's
/// `duration_to_seconds(datetime_of_transaction() - .started_at)` is the shape
/// this exists for, and it resolves no overload while the subtraction reads as
/// untyped.
fn temporal_result_type(op: &ast::BinOpKind, left: &str, right: &str) -> Option<&'static str> {
    use ast::BinOpKind::*;
    let instant = |t: &str| matches!(t, "timestamptz" | "timestamp" | "date" | "time");
    match (op, left, right) {
        (Sub, l, r) if instant(l) && instant(r) => Some("interval"),
        (Sub | Add, l, "interval") if instant(l) => Some(match l {
            "timestamptz" => "timestamptz",
            "timestamp" => "timestamp",
            "date" => "date",
            _ => "time",
        }),
        (Add, "interval", r) if instant(r) => Some(match r {
            "timestamptz" => "timestamptz",
            "timestamp" => "timestamp",
            "date" => "date",
            _ => "time",
        }),
        (Add | Sub, "interval", "interval") => Some("interval"),
        _ => None,
    }
}

/// The type Gel gives an arithmetic operator's result, from its operands'.
/// `None` for anything but a pair of numbers.
fn arithmetic_result_type(op: &ast::BinOpKind, left: &str, right: &str) -> Option<&'static str> {
    use ast::BinOpKind::*;
    if !matches!(op, Add | Sub | Mul | Div | FloorDiv | Mod | Pow) {
        return None;
    }
    let (left, right) = (literal_sentinel_to_pg(left), literal_sentinel_to_pg(right));
    if let Some(temporal) = temporal_result_type(op, left, right) {
        return Some(temporal);
    }
    let int = |t: &str| INT_TYPES.contains(&t);
    let float = |t: &str| FLOAT_TYPES.contains(&t);
    let numeric = |t: &str| NUMERIC_TYPES.contains(&t);
    if int(left) && int(right) {
        return Some(if matches!(op, Div | Pow) {
            "float8"
        } else if left == "int8" || right == "int8" {
            "int8"
        } else if left == "int4" || right == "int4" {
            "int4"
        } else {
            "int2"
        });
    }
    if (float(left) || int(left)) && (float(right) || int(right)) {
        return Some(if left == "float4" && right == "float4" {
            "float4"
        } else {
            "float8"
        });
    }
    if (numeric(left) || int(left)) && (numeric(right) || int(right)) {
        return Some("numeric");
    }
    None
}

/// What `max`, `min` and `sum` over values of `element` yield in Gel.
fn aggregate_result_type<'a>(name: &str, element: &'a str) -> Option<&'a str> {
    let element = literal_sentinel_to_pg(element);
    match name {
        "max" | "min" => Some(element),
        "sum" if INT_TYPES.contains(&element) => Some("int8"),
        "sum" if FLOAT_TYPES.contains(&element) || NUMERIC_TYPES.contains(&element) => Some(element),
        _ => None,
    }
}

/// The left operand of `left op right`, cast to `float8` when `op` divides
/// two integers: Gel's `/` yields a float64 there, Postgres's truncates.
fn true_division_operand(op: &ast::BinOpKind, left: IrExpr, right: &IrExpr) -> IrExpr {
    let integer = |expr: &IrExpr| infer_ir_type(expr).is_some_and(|t| INT_TYPES.contains(&literal_sentinel_to_pg(t)));
    if *op != ast::BinOpKind::Div || !integer(&left) || !integer(right) {
        return left;
    }
    IrExpr::TypeCast(Box::new(IrTypeCast {
        expr: left,
        pg_type: "float8".to_string(),
        tuple_shape: None,
    }))
}

/// Maps a resolved element `pg_type` (as `infer_ir_type` reports it) to the
/// PostgreSQL native range constructor over that type. PG has no float4/
/// float8/int2/int4-native range type — only int8range, numrange, tsrange,
/// tstzrange, and daterange exist — so untyped int/float literals default
/// to the widest native family (int8/numeric) rather than erroring, matching
/// how those literals already default elsewhere in Pylon.
fn range_ctor_for_pg_type(pg_type: &str) -> Option<&'static str> {
    match pg_type {
        "int2" | "int4" | "int8" | "__int_literal" => Some("int8range"),
        "numeric" | "__float_literal" => Some("numrange"),
        "timestamp" => Some("tsrange"),
        "timestamptz" => Some("tstzrange"),
        "date" => Some("daterange"),
        _ => None,
    }
}

/// The multirange counterpart of a range constructor name resolved by
/// `range_ctor_for_pg_type`.
fn multirange_ctor_for_range_ctor(range_ctor: &str) -> Option<&'static str> {
    match range_ctor {
        "int8range" => Some("int8multirange"),
        "numrange" => Some("nummultirange"),
        "tsrange" => Some("tsmultirange"),
        "tstzrange" => Some("tstzmultirange"),
        "daterange" => Some("datemultirange"),
        _ => None,
    }
}

const INT_TYPES: &[&str] = &["int2", "int4", "int8", "__int_literal"];
const FLOAT_TYPES: &[&str] = &["float4", "float8", "__float_literal"];
/// Postgres `numeric` backs both Pylon's `bigint` and `decimal` (see
/// `pg_type_for_scalar_name`) — Pylon doesn't distinguish them at the
/// pg_type level, so this bucket covers both.
const NUMERIC_TYPES: &[&str] = &["numeric"];

/// Pylon's implicit-cast graph for numeric operands:
/// `int16 → int32 → int64 → float32 → float64` on one branch and
/// `int64 → bigint → decimal` on another — every int width casts to every
/// float width and to numeric/decimal, but float and numeric/decimal don't
/// cast to each other (they're separate branches past `int64`). Postgres's
/// own operator resolution handles the actual mixed-type arithmetic once
/// the compile-time gate lets it through (e.g. `int2 + float4` is a native
/// Postgres operator) — this only needs to match which operand-type
/// combinations are meant to be allowed.
pub(crate) fn types_compatible(a: &str, b: &str) -> bool {
    if a == b {
        return true;
    }
    let a_int = INT_TYPES.contains(&a);
    let b_int = INT_TYPES.contains(&b);
    if a_int && b_int {
        return true;
    }
    let a_float = FLOAT_TYPES.contains(&a);
    let b_float = FLOAT_TYPES.contains(&b);
    if a_float && b_float {
        return true;
    }
    let a_numeric = NUMERIC_TYPES.contains(&a);
    let b_numeric = NUMERIC_TYPES.contains(&b);
    if a_numeric && b_numeric {
        return true;
    }
    (a_int && b_float) || (a_float && b_int) || (a_int && b_numeric) || (a_numeric && b_int)
}

/// Datetime/duration `+`/`-` pairs PostgreSQL supports natively (e.g.
/// `timestamptz + interval`) that `types_compatible`'s bucket-matching
/// (same type, or both-int, or both-float) doesn't cover. Deliberately a
/// separate, narrower check from `types_compatible` (also used for UNION-branch
/// compatibility, where "a datetime and a duration are interchangeable"
/// would be nonsensical) rather than folded into it, so this can't leak
/// into a context where "arithmetic-compatible" isn't the same relation as
/// "interchangeable." Postgres's own operator resolution is the final
/// authority on any (op, operand-order) combination that doesn't actually
/// exist (e.g. `interval - timestamptz`) — this only needs to widen the
/// compile-time gate far enough to let the legitimate combinations through.
fn datetime_arithmetic_compatible(op: &ast::BinOpKind, a: &str, b: &str) -> bool {
    if !matches!(op, ast::BinOpKind::Add | ast::BinOpKind::Sub) {
        return false;
    }
    matches!(
        (a, b),
        ("timestamptz", "interval")
            | ("interval", "timestamptz")
            | ("timestamp", "interval")
            | ("interval", "timestamp")
            | ("date", "interval")
            | ("interval", "date")
            | ("time", "interval")
            | ("interval", "time")
    )
}

/// Collect `SearchEnqueueInfo` for every OpenSearch- or Meilisearch-backed
/// search index on a type — `Postgres`-backed indexes are excluded since
/// they're maintained synchronously by a trigger-updated tsvector column,
/// not an async outbox worker.
fn collect_search_enqueue(td: &TypeDescriptor, type_name: &str, operation: &'static str) -> Vec<SearchEnqueueInfo> {
    td.search_indexes
        .iter()
        .filter(|si| si.backend == SearchBackend::OpenSearch || si.backend == SearchBackend::Meilisearch)
        .map(|si| SearchEnqueueInfo {
            type_name: type_name.to_string(),
            index_name: si.index_name.clone(),
            operation,
            backend: si.backend.clone(),
        })
        .collect()
}

/// Reverse of `type_expr_to_pg`'s plain-scalar branch — renders a base
/// Postgres type back to its canonical PyQL display name. `pub` (not just
/// crate-local): reused by `pylon-server`'s `/api/schema` port
/// (`_scalar_type_name`'s equivalent) so that display-name logic isn't
/// duplicated across crates.
///
/// `"interval"`/`"date"`/`"time"`/`"timestamp"` are inherently ambiguous
/// from the bare pg_type alone: `interval` backs both `std::duration` and
/// `cal::relative_duration` (defaults to the former — the more common
/// case), while `date`/`time`/`timestamp` (no tz) are unambiguous (only
/// `cal::local_date`/`cal::local_time`/`cal::local_datetime` use them, as
/// opposed to `timestamptz` for `std::datetime`).
pub fn pg_type_to_pyql(pg: &str) -> &str {
    match pg {
        "text" | "varchar" => "std::str",
        "uuid" => "std::uuid",
        "int2" => "std::int16",
        "int4" => "std::int32",
        "int8" => "std::int64",
        "float4" => "std::float32",
        "float8" => "std::float64",
        "boolean" => "std::bool",
        "numeric" => "std::decimal",
        "timestamptz" => "std::datetime",
        "timestamp" => "cal::local_datetime",
        "date" => "cal::local_date",
        "time" => "cal::local_time",
        "interval" => "std::duration",
        "bytea" => "std::bytes",
        "jsonb" => "std::json",
        "__int_literal" => "std::int64",
        "__float_literal" => "std::float64",
        other => other,
    }
}