kimberlite-query 0.9.1

SQL query layer for Kimberlite projections
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
//! Query planner: transforms parsed SQL into execution plans.
//!
//! The planner analyzes predicates to select the optimal access path:
//! - `PointLookup`: When all primary key columns have equality predicates
//! - `RangeScan`: When primary key has range predicates
//! - `TableScan`: Fallback for non-indexed predicates

use std::ops::Bound;
use std::sync::Arc;

use crate::error::{QueryError, Result};
use crate::expression::ScalarExpr;
use crate::key_encoder::{encode_key, successor_key};
use crate::parser::{
    CaseWhenArm, ComputedColumn, LimitExpr, OrderByClause, ParsedSelect, Predicate, PredicateValue,
    ScalarCmpOp,
};
use crate::plan::{
    CaseColumnDef, CaseWhenClause, Filter, FilterCondition, FilterOp, QueryPlan, ScanOrder,
    SortSpec,
};
use crate::schema::{ColumnName, Schema, TableDef};
use crate::value::Value;

/// Creates table metadata from a table definition.
#[inline]
fn create_metadata(table_def: &TableDef, table_name: String) -> crate::plan::TableMetadata {
    crate::plan::TableMetadata {
        table_id: table_def.table_id,
        table_name,
        columns: table_def.columns.clone(),
        primary_key: table_def.primary_key.clone(),
    }
}

/// Builds a point lookup plan.
#[inline]
fn build_point_lookup_plan(
    table_def: &TableDef,
    table_name: String,
    key_values: &[Value],
    column_indices: Vec<usize>,
    column_names: Vec<ColumnName>,
) -> QueryPlan {
    let key = encode_key(key_values);
    QueryPlan::PointLookup {
        metadata: create_metadata(table_def, table_name),
        key,
        columns: column_indices,
        column_names,
    }
}

/// Builds a range scan plan.
#[inline]
#[allow(clippy::too_many_arguments)]
fn build_range_scan_plan(
    table_def: &TableDef,
    table_name: String,
    start_key: Bound<kimberlite_store::Key>,
    end_key: Bound<kimberlite_store::Key>,
    remaining_predicates: &[ResolvedPredicate],
    limit: Option<usize>,
    offset: Option<usize>,
    order_by: &[OrderByClause],
    column_indices: Vec<usize>,
    column_names: Vec<ColumnName>,
) -> Result<QueryPlan> {
    let filter = build_filter(table_def, remaining_predicates, &table_name)?;
    let order = determine_scan_order(order_by, table_def);

    // Build sort spec for client-side sorting when ORDER BY doesn't match scan order
    let needs_client_sort = !order_by.is_empty()
        && order_by
            .iter()
            .any(|clause| !table_def.is_primary_key(&clause.column));
    let order_by_spec = if needs_client_sort {
        build_sort_spec(order_by, table_def, &table_name)?
    } else {
        None
    };

    Ok(QueryPlan::RangeScan {
        metadata: create_metadata(table_def, table_name),
        start: start_key,
        end: end_key,
        filter,
        limit,
        offset,
        order,
        order_by: order_by_spec,
        columns: column_indices,
        column_names,
    })
}

/// Builds an index scan plan.
#[inline]
#[allow(clippy::too_many_arguments)]
fn build_index_scan_plan(
    table_def: &TableDef,
    table_name: String,
    index_id: u64,
    index_name: String,
    start_key: Bound<kimberlite_store::Key>,
    end_key: Bound<kimberlite_store::Key>,
    remaining_predicates: &[ResolvedPredicate],
    limit: Option<usize>,
    offset: Option<usize>,
    order_by: &[OrderByClause],
    column_indices: Vec<usize>,
    column_names: Vec<ColumnName>,
) -> Result<QueryPlan> {
    let filter = build_filter(table_def, remaining_predicates, &table_name)?;
    let order = determine_scan_order(order_by, table_def);

    // Build sort spec for client-side sorting when ORDER BY doesn't match scan order
    let needs_client_sort = !order_by.is_empty()
        && order_by
            .iter()
            .any(|clause| !table_def.is_primary_key(&clause.column));
    let order_by_spec = if needs_client_sort {
        build_sort_spec(order_by, table_def, &table_name)?
    } else {
        None
    };

    Ok(QueryPlan::IndexScan {
        metadata: create_metadata(table_def, table_name),
        index_id,
        index_name,
        start: start_key,
        end: end_key,
        filter,
        limit,
        offset,
        order,
        order_by: order_by_spec,
        columns: column_indices,
        column_names,
    })
}

/// Builds a table scan plan.
#[inline]
#[allow(clippy::too_many_arguments)]
fn build_table_scan_plan(
    table_def: &TableDef,
    table_name: String,
    all_predicates: &[ResolvedPredicate],
    limit: Option<usize>,
    offset: Option<usize>,
    order_by: &[OrderByClause],
    column_indices: Vec<usize>,
    column_names: Vec<ColumnName>,
) -> Result<QueryPlan> {
    let filter = build_filter(table_def, all_predicates, &table_name)?;
    let order = build_sort_spec(order_by, table_def, &table_name)?;

    Ok(QueryPlan::TableScan {
        metadata: create_metadata(table_def, table_name),
        filter,
        limit,
        offset,
        order,
        columns: column_indices,
        column_names,
    })
}

/// Resolves a `LimitExpr` against the bound parameter slice into a concrete
/// row count. Mirrors `resolve_value` for the LIMIT/OFFSET position.
///
/// Errors on negative or non-integer bound values so the caller surfaces a
/// clear message instead of letting a bad cast panic at the plan boundary.
fn resolve_limit(expr: Option<LimitExpr>, params: &[Value]) -> Result<Option<usize>> {
    match expr {
        None => Ok(None),
        Some(LimitExpr::Literal(v)) => Ok(Some(v)),
        Some(LimitExpr::Param(idx)) => {
            let zero_idx = idx.checked_sub(1).ok_or(QueryError::ParameterNotFound(0))?;
            let value = params
                .get(zero_idx)
                .cloned()
                .ok_or(QueryError::ParameterNotFound(idx))?;
            match value {
                Value::BigInt(n) if n >= 0 => Ok(Some(n as usize)),
                Value::Integer(n) if n >= 0 => Ok(Some(n as usize)),
                Value::SmallInt(n) if n >= 0 => Ok(Some(n as usize)),
                Value::TinyInt(n) if n >= 0 => Ok(Some(n as usize)),
                Value::BigInt(_) | Value::Integer(_) | Value::SmallInt(_) | Value::TinyInt(_) => {
                    Err(QueryError::ParseError(
                        "LIMIT/OFFSET parameter must be non-negative".to_string(),
                    ))
                }
                other => Err(QueryError::UnsupportedFeature(format!(
                    "LIMIT/OFFSET parameter must bind to an integer; got {other:?}"
                ))),
            }
        }
    }
}

/// Wraps a base plan with an aggregate plan if needed.
#[inline]
fn wrap_with_aggregate(
    base_plan: QueryPlan,
    table_def: &TableDef,
    table_name: String,
    parsed: &ParsedSelect,
    params: &[Value],
) -> Result<QueryPlan> {
    // For DISTINCT without explicit GROUP BY, group by all selected columns
    let group_by_columns = if parsed.distinct && parsed.group_by.is_empty() {
        parsed
            .columns
            .clone()
            .unwrap_or_else(|| table_def.columns.iter().map(|c| c.name.clone()).collect())
    } else {
        parsed.group_by.clone()
    };

    // For DISTINCT, aggregates should be empty (just deduplication)
    let aggregates = if parsed.distinct && parsed.aggregates.is_empty() {
        vec![]
    } else {
        parsed.aggregates.clone()
    };

    // Resolve GROUP BY column indices
    let mut group_by_indices = Vec::new();
    for col_name in &group_by_columns {
        let (idx, _) =
            table_def
                .find_column(col_name)
                .ok_or_else(|| QueryError::ColumnNotFound {
                    table: table_name.clone(),
                    column: col_name.to_string(),
                })?;
        group_by_indices.push(idx);
    }

    // Build result column names: GROUP BY columns + aggregate results
    let mut result_columns = group_by_columns.clone();
    for agg in &aggregates {
        let agg_name = match agg {
            crate::parser::AggregateFunction::CountStar => "COUNT(*)".to_string(),
            crate::parser::AggregateFunction::Count(col) => format!("COUNT({col})"),
            crate::parser::AggregateFunction::Sum(col) => format!("SUM({col})"),
            crate::parser::AggregateFunction::Avg(col) => format!("AVG({col})"),
            crate::parser::AggregateFunction::Min(col) => format!("MIN({col})"),
            crate::parser::AggregateFunction::Max(col) => format!("MAX({col})"),
        };
        result_columns.push(ColumnName::new(agg_name));
    }

    // Resolve per-aggregate FILTER (WHERE ...) predicates against the table.
    // The parser guarantees aggregate_filters is parallel with aggregates, but
    // older planner paths build aggregates without filters — fall back to None
    // when the parsed list is shorter than the resolved aggregates list.
    let mut aggregate_filters: Vec<Option<crate::plan::Filter>> = Vec::new();
    for (i, _agg) in aggregates.iter().enumerate() {
        let filter_predicates = parsed.aggregate_filters.get(i).and_then(|f| f.as_ref());
        let filter = match filter_predicates {
            Some(preds) => {
                let resolved = resolve_predicates(preds, params)?;
                build_filter(table_def, &resolved, &table_name)?
            }
            None => None,
        };
        aggregate_filters.push(filter);
    }

    Ok(QueryPlan::Aggregate {
        metadata: create_metadata(table_def, table_name),
        source: Box::new(base_plan),
        group_by_cols: group_by_indices,
        group_by_names: group_by_columns,
        aggregates,
        aggregate_filters,
        column_names: result_columns,
        having: parsed.having.clone(),
    })
}

/// Plans a parsed SELECT statement. Samples the system clock once and
/// folds `NOW()` / `CURRENT_TIMESTAMP` / `CURRENT_DATE` sentinels into
/// literals before returning, so the executor never sees a raw
/// sentinel and stays pure (PRESSURECRAFT §1 FCIS). Callers that need
/// a deterministic clock (VOPR, replay) should use
/// [`plan_query_with_clock`] and pass their own timestamp.
pub fn plan_query(schema: &Schema, parsed: &ParsedSelect, params: &[Value]) -> Result<QueryPlan> {
    plan_query_with_clock(schema, parsed, params, current_statement_timestamp_ns())
}

/// Plans a parsed SELECT statement with an explicit statement-stable
/// timestamp. Use this from VOPR / replay / any path that requires
/// determinism. AUDIT-2026-05 S3.7.
pub fn plan_query_with_clock(
    schema: &Schema,
    parsed: &ParsedSelect,
    params: &[Value],
    statement_ts_ns: i64,
) -> Result<QueryPlan> {
    let mut plan = if parsed.joins.is_empty() {
        // Single-table query - existing logic
        plan_single_table_query(schema, parsed, params)?
    } else {
        // Multi-table query - new JOIN logic
        plan_join_query(schema, parsed, params)?
    };
    fold_time_constants_in_plan(&mut plan, statement_ts_ns);
    Ok(plan)
}

/// Plans a single-table query (no JOINs).
fn plan_single_table_query(
    schema: &Schema,
    parsed: &ParsedSelect,
    params: &[Value],
) -> Result<QueryPlan> {
    // Look up table
    let table_name = parsed.table.clone();
    let table_def = schema
        .get_table(&table_name.clone().into())
        .ok_or_else(|| QueryError::TableNotFound(table_name.clone()))?;

    // Resolve predicate values (substitute parameters)
    let resolved_predicates = resolve_predicates(&parsed.predicates, params)?;

    // Resolve columns for the query (accounts for aggregate requirements)
    let (column_indices, column_names) = resolve_query_columns(table_def, parsed, &table_name)?;

    // Check if we need aggregates
    let needs_aggregate = !parsed.aggregates.is_empty()
        || !parsed.group_by.is_empty()
        || parsed.distinct
        || !parsed.having.is_empty();

    // Analyze predicates to determine access path
    let access_path = analyze_access_path(table_def, &resolved_predicates);

    // Build the base scan plan
    let base_plan = build_scan_plan(
        access_path,
        table_def,
        table_name.clone(),
        parsed,
        params,
        column_indices,
        column_names,
    )?;

    // Wrap in an aggregate plan if needed
    let plan_after_agg = if needs_aggregate {
        wrap_with_aggregate(base_plan, table_def, table_name.clone(), parsed, params)?
    } else {
        base_plan
    };

    // Wrap in a Materialize plan if CASE WHEN or scalar projections are present.
    if !parsed.case_columns.is_empty() || !parsed.scalar_projections.is_empty() {
        let source_columns = plan_after_agg.column_names().to_vec();
        let case_columns = resolve_case_columns_for_join(&parsed.case_columns, &source_columns)?;
        // Scalar columns see the *post-case* layout so a scalar projection
        // can reference a CASE alias too (rare but consistent with PG).
        let mut post_case_columns = source_columns.clone();
        post_case_columns.extend(case_columns.iter().map(|c| c.alias.clone()));
        let scalar_columns =
            resolve_scalar_columns(&parsed.scalar_projections, &post_case_columns, params)?;

        // Build the declared output column list in SELECT order:
        //   [user-selected bare columns (with aliases)...; CASE aliases...; scalar outputs...]
        // The executor prunes source rows down to this shape by name, so
        // source columns fetched only for scalar-expression evaluation
        // don't leak into the final result.
        let mut output_columns: Vec<ColumnName> = match (&parsed.columns, &parsed.column_aliases) {
            (None, _) => {
                // SELECT * — pass through every source column.
                source_columns.clone()
            }
            (Some(cols), aliases) => {
                let mut out = Vec::with_capacity(cols.len());
                for (i, col) in cols.iter().enumerate() {
                    let alias = aliases
                        .as_ref()
                        .and_then(|v| v.get(i))
                        .and_then(|a| a.as_ref());
                    out.push(match alias {
                        Some(a) => ColumnName::new(a.clone()),
                        None => col.clone(),
                    });
                }
                out
            }
        };
        output_columns.extend(case_columns.iter().map(|c| c.alias.clone()));
        output_columns.extend(scalar_columns.iter().map(|c| c.output_name.clone()));

        Ok(QueryPlan::Materialize {
            source: Box::new(plan_after_agg),
            filter: None,
            case_columns,
            scalar_columns,
            order: None,
            limit: None,
            offset: None,
            column_names: output_columns,
        })
    } else {
        Ok(plan_after_agg)
    }
}

/// Bake a list of parsed scalar projections against a known source
/// column layout. Substitutes bound parameter values into each
/// expression tree so the executor doesn't have to know about `params`.
fn resolve_scalar_columns(
    projections: &[crate::parser::ParsedScalarProjection],
    source_columns: &[ColumnName],
    params: &[Value],
) -> Result<Vec<crate::plan::ScalarColumnDef>> {
    if projections.is_empty() {
        return Ok(Vec::new());
    }
    let columns: Arc<[ColumnName]> = source_columns.to_vec().into();
    projections
        .iter()
        .map(|p| {
            Ok(crate::plan::ScalarColumnDef {
                output_name: p.output_name.clone(),
                expr: substitute_scalar_params(&p.expr, params)?,
                columns: columns.clone(),
            })
        })
        .collect()
}

/// Plans a multi-table query with JOINs.
fn plan_join_query(schema: &Schema, parsed: &ParsedSelect, params: &[Value]) -> Result<QueryPlan> {
    // Build left-deep join tree
    let mut current_plan = plan_table_access(schema, &parsed.table, params)?;

    for join in &parsed.joins {
        // Plan right table access
        let right_plan = plan_table_access(schema, &join.table, params)?;

        // Build join conditions from ON clause
        let on_conditions =
            build_join_conditions(&join.on_condition, schema, &parsed.table, &join.table)?;

        // Merge column names from both tables (left then right)
        let left_columns = current_plan.column_names().to_vec();
        let right_columns = right_plan.column_names().to_vec();
        let mut all_columns = left_columns.clone();
        all_columns.extend(right_columns);

        // Build join node
        current_plan = QueryPlan::Join {
            join_type: join.join_type.clone(),
            left: Box::new(current_plan),
            right: Box::new(right_plan),
            on_conditions,
            columns: vec![], // All columns from both tables
            column_names: all_columns,
        };
    }

    // Collect the full combined column list from the join tree
    let combined_columns = current_plan.column_names().to_vec();

    // Resolve WHERE predicates against the combined column list
    let resolved_predicates = resolve_predicates(&parsed.predicates, params)?;
    let filter = build_filter_for_join(&resolved_predicates, &combined_columns)?;

    // Resolve ORDER BY against the combined column list
    let order = build_sort_spec_for_join(&parsed.order_by, &combined_columns)?;

    // Resolve CASE WHEN computed columns
    let case_columns = resolve_case_columns_for_join(&parsed.case_columns, &combined_columns)?;

    // Compute the post-case column layout — scalar projections see this
    // shape so they can reference a CASE alias if needed.
    let mut post_case_columns = combined_columns.clone();
    post_case_columns.extend(case_columns.iter().map(|c| c.alias.clone()));
    let scalar_columns =
        resolve_scalar_columns(&parsed.scalar_projections, &post_case_columns, params)?;

    // Determine output column names: selected columns from combined list
    // + CASE aliases + scalar output names.
    let output_columns: Vec<ColumnName> = match &parsed.columns {
        None => {
            // SELECT * — all combined columns + computed aliases
            let mut out = combined_columns.clone();
            out.extend(case_columns.iter().map(|c| c.alias.clone()));
            out.extend(scalar_columns.iter().map(|c| c.output_name.clone()));
            out
        }
        Some(selected) => {
            // Validate that each selected column exists in the combined list
            for col in selected {
                if !combined_columns.iter().any(|c| c == col) {
                    return Err(QueryError::ColumnNotFound {
                        table: parsed.table.clone(),
                        column: col.to_string(),
                    });
                }
            }
            let mut out = selected.clone();
            out.extend(case_columns.iter().map(|c| c.alias.clone()));
            out.extend(scalar_columns.iter().map(|c| c.output_name.clone()));
            out
        }
    };

    let limit = resolve_limit(parsed.limit, params)?;
    let offset = resolve_limit(parsed.offset, params)?;
    let needs_materialize = filter.is_some()
        || order.is_some()
        || limit.is_some()
        || offset.is_some()
        || !case_columns.is_empty()
        || !scalar_columns.is_empty();

    if needs_materialize {
        Ok(QueryPlan::Materialize {
            source: Box::new(current_plan),
            filter,
            case_columns,
            scalar_columns,
            order,
            limit,
            offset,
            column_names: output_columns,
        })
    } else {
        Ok(current_plan)
    }
}

/// Builds a filter from resolved predicates against a named column list.
///
/// Used for JOIN queries where we don't have a single `TableDef` — instead we
/// resolve column names against the combined left+right column list.
fn build_filter_for_join(
    predicates: &[ResolvedPredicate],
    columns: &[ColumnName],
) -> Result<Option<Filter>> {
    if predicates.is_empty() {
        return Ok(None);
    }

    let filters: Result<Vec<_>> = predicates
        .iter()
        .map(|p| build_filter_for_join_predicate(p, columns))
        .collect();

    Ok(Some(Filter::and(filters?)))
}

fn build_filter_for_join_predicate(
    pred: &ResolvedPredicate,
    columns: &[ColumnName],
) -> Result<Filter> {
    if let ResolvedOp::Or(left_preds, right_preds) = &pred.op {
        let left_filter = build_filter_for_join(left_preds, columns)?.ok_or_else(|| {
            QueryError::UnsupportedFeature("OR left side has no predicates".to_string())
        })?;
        let right_filter = build_filter_for_join(right_preds, columns)?.ok_or_else(|| {
            QueryError::UnsupportedFeature("OR right side has no predicates".to_string())
        })?;
        Ok(Filter::or(vec![left_filter, right_filter]))
    } else {
        let condition = build_filter_condition_for_join(pred, columns)?;
        Ok(Filter::single(condition))
    }
}

fn build_filter_condition_for_join(
    pred: &ResolvedPredicate,
    columns: &[ColumnName],
) -> Result<FilterCondition> {
    if matches!(pred.op, ResolvedOp::AlwaysTrue) {
        return Ok(FilterCondition {
            column_idx: 0,
            op: FilterOp::AlwaysTrue,
            value: Value::Null,
        });
    }
    if matches!(pred.op, ResolvedOp::AlwaysFalse) {
        return Ok(FilterCondition {
            column_idx: 0,
            op: FilterOp::AlwaysFalse,
            value: Value::Null,
        });
    }
    // ScalarCmp resolves column names against the join-combined column
    // layout passed in. Short-circuit before the keyed column lookup.
    if let ResolvedOp::ScalarCmp { lhs, op, rhs } = &pred.op {
        let cols: Arc<[ColumnName]> = columns.to_vec().into();
        return Ok(FilterCondition {
            column_idx: 0,
            op: FilterOp::ScalarCmp {
                columns: cols,
                lhs: lhs.clone(),
                op: *op,
                rhs: rhs.clone(),
            },
            value: Value::Null,
        });
    }

    let col_idx = columns
        .iter()
        .position(|c| c == &pred.column)
        .ok_or_else(|| QueryError::ColumnNotFound {
            table: "(join)".to_string(),
            column: pred.column.to_string(),
        })?;

    let (op, value) = match &pred.op {
        ResolvedOp::Eq(v) => (FilterOp::Eq, v.clone()),
        ResolvedOp::Lt(v) => (FilterOp::Lt, v.clone()),
        ResolvedOp::Le(v) => (FilterOp::Le, v.clone()),
        ResolvedOp::Gt(v) => (FilterOp::Gt, v.clone()),
        ResolvedOp::Ge(v) => (FilterOp::Ge, v.clone()),
        ResolvedOp::In(vals) => (FilterOp::In(vals.clone()), Value::Null),
        ResolvedOp::NotIn(vals) => (FilterOp::NotIn(vals.clone()), Value::Null),
        ResolvedOp::NotBetween(low, high) => {
            (FilterOp::NotBetween(low.clone(), high.clone()), Value::Null)
        }
        ResolvedOp::Like(pattern) => (FilterOp::Like(pattern.clone()), Value::Null),
        ResolvedOp::NotLike(pattern) => (FilterOp::NotLike(pattern.clone()), Value::Null),
        ResolvedOp::ILike(pattern) => (FilterOp::ILike(pattern.clone()), Value::Null),
        ResolvedOp::NotILike(pattern) => (FilterOp::NotILike(pattern.clone()), Value::Null),
        ResolvedOp::IsNull => (FilterOp::IsNull, Value::Null),
        ResolvedOp::IsNotNull => (FilterOp::IsNotNull, Value::Null),
        ResolvedOp::JsonExtractEq {
            path,
            as_text,
            value: v,
        } => (
            FilterOp::JsonExtractEq {
                path: path.clone(),
                as_text: *as_text,
                value: v.clone(),
            },
            Value::Null,
        ),
        ResolvedOp::JsonContains(v) => (FilterOp::JsonContains(v.clone()), Value::Null),
        ResolvedOp::AlwaysTrue => (FilterOp::AlwaysTrue, Value::Null),
        ResolvedOp::AlwaysFalse => (FilterOp::AlwaysFalse, Value::Null),
        ResolvedOp::Or(_, _) => {
            return Err(QueryError::UnsupportedFeature(
                "OR predicates must be handled at filter level".to_string(),
            ));
        }
        ResolvedOp::ScalarCmp { .. } => {
            unreachable!("ScalarCmp handled by the short-circuit above");
        }
    };

    Ok(FilterCondition {
        column_idx: col_idx,
        op,
        value,
    })
}

/// Builds a sort specification from ORDER BY clauses against a named column list.
fn build_sort_spec_for_join(
    order_by: &[OrderByClause],
    columns: &[ColumnName],
) -> Result<Option<SortSpec>> {
    if order_by.is_empty() {
        return Ok(None);
    }

    let mut sort_cols = Vec::with_capacity(order_by.len());
    for clause in order_by {
        let idx = columns
            .iter()
            .position(|c| c == &clause.column)
            .ok_or_else(|| QueryError::ColumnNotFound {
                table: "(join)".to_string(),
                column: clause.column.to_string(),
            })?;
        let order = if clause.ascending {
            ScanOrder::Ascending
        } else {
            ScanOrder::Descending
        };
        sort_cols.push((idx, order));
    }

    Ok(Some(SortSpec { columns: sort_cols }))
}

/// Resolves CASE WHEN computed columns against a named column list.
fn resolve_case_columns_for_join(
    case_columns: &[ComputedColumn],
    columns: &[ColumnName],
) -> Result<Vec<CaseColumnDef>> {
    case_columns
        .iter()
        .map(|cc| resolve_single_case_column(cc, columns))
        .collect()
}

fn resolve_single_case_column(
    cc: &ComputedColumn,
    columns: &[ColumnName],
) -> Result<CaseColumnDef> {
    let when_clauses: Result<Vec<_>> = cc
        .when_clauses
        .iter()
        .map(|arm| resolve_case_when_arm(arm, columns))
        .collect();

    Ok(CaseColumnDef {
        alias: cc.alias.clone(),
        when_clauses: when_clauses?,
        else_value: cc.else_value.clone(),
    })
}

fn resolve_case_when_arm(arm: &CaseWhenArm, columns: &[ColumnName]) -> Result<CaseWhenClause> {
    // Resolve predicates (no params in CASE conditions)
    let resolved = resolve_predicates(&arm.condition, &[])?;
    let filter = build_filter_for_join(&resolved, columns)?.ok_or_else(|| {
        QueryError::UnsupportedFeature("CASE WHEN condition has no predicates".to_string())
    })?;

    Ok(CaseWhenClause {
        condition: filter,
        result: arm.result.clone(),
    })
}

/// Plans a table access for a single table (used in JOINs).
fn plan_table_access(schema: &Schema, table_name: &str, _params: &[Value]) -> Result<QueryPlan> {
    let table_def = schema
        .get_table(&table_name.into())
        .ok_or_else(|| QueryError::TableNotFound(table_name.to_string()))?;

    // For JOIN table access, just do a full table scan
    // (In the future, we could optimize this based on join predicates)
    let all_column_indices: Vec<usize> = (0..table_def.columns.len()).collect();
    let all_column_names: Vec<ColumnName> =
        table_def.columns.iter().map(|c| c.name.clone()).collect();

    Ok(QueryPlan::TableScan {
        metadata: create_metadata(table_def, table_name.to_string()),
        filter: None,
        limit: None,
        offset: None,
        order: None,
        columns: all_column_indices,
        column_names: all_column_names,
    })
}

/// Builds join conditions from ON clause predicates.
///
/// JOIN predicates can have column references on both sides (e.g., users.id = orders.user_id).
/// These need to be resolved to indices in the concatenated row [left_cols..., right_cols...].
fn build_join_conditions(
    predicates: &[Predicate],
    schema: &Schema,
    left_table: &str,
    right_table: &str,
) -> Result<Vec<crate::plan::JoinCondition>> {
    let left_table_def = schema
        .get_table(&left_table.into())
        .ok_or_else(|| QueryError::TableNotFound(left_table.to_string()))?;
    let right_table_def = schema
        .get_table(&right_table.into())
        .ok_or_else(|| QueryError::TableNotFound(right_table.to_string()))?;

    let left_col_count = left_table_def.columns.len();

    predicates
        .iter()
        .map(|pred| {
            build_single_join_condition(
                pred,
                left_table,
                left_table_def,
                right_table,
                right_table_def,
                left_col_count,
            )
        })
        .collect()
}

/// Builds a single join condition from a JOIN predicate.
///
/// Handles column-to-column comparisons by resolving qualified/unqualified column names
/// to indices in the concatenated row [left_cols..., right_cols...].
fn build_single_join_condition(
    pred: &Predicate,
    left_table: &str,
    left_table_def: &TableDef,
    right_table: &str,
    right_table_def: &TableDef,
    left_col_count: usize,
) -> Result<crate::plan::JoinCondition> {
    use crate::plan::JoinOp;

    // Extract column name, operator, and right side from predicate
    let (left_col_name, op, right_value) = match pred {
        Predicate::Eq(col, val) => (col, JoinOp::Eq, val),
        Predicate::Lt(col, val) => (col, JoinOp::Lt, val),
        Predicate::Le(col, val) => (col, JoinOp::Le, val),
        Predicate::Gt(col, val) => (col, JoinOp::Gt, val),
        Predicate::Ge(col, val) => (col, JoinOp::Ge, val),
        _ => {
            return Err(QueryError::UnsupportedFeature(
                "only equality and comparison operators supported in JOIN ON clause".to_string(),
            ));
        }
    };

    // Resolve left column to index in concatenated row
    let left_col_idx = resolve_join_column(left_col_name, left_table, left_table_def, 0)?;

    // Right side must be a column reference for JOIN conditions
    match right_value {
        PredicateValue::ColumnRef(ref_str) => {
            // Column-to-column comparison
            let right_col_idx = resolve_join_column_ref(
                ref_str,
                left_table,
                left_table_def,
                right_table,
                right_table_def,
                left_col_count,
            )?;

            Ok(crate::plan::JoinCondition {
                left_col_idx,
                right_col_idx,
                op,
            })
        }
        _ => Err(QueryError::UnsupportedFeature(
            "JOIN ON clause requires column-to-column comparisons (e.g., users.id = orders.user_id)".to_string(),
        )),
    }
}

/// Resolves a column name to an index in the concatenated row.
fn resolve_join_column(
    col_name: &ColumnName,
    table_name: &str,
    table_def: &TableDef,
    offset: usize,
) -> Result<usize> {
    let (idx, _) = table_def
        .find_column(col_name)
        .ok_or_else(|| QueryError::ColumnNotFound {
            table: table_name.to_string(),
            column: col_name.to_string(),
        })?;
    Ok(offset + idx)
}

/// Resolves a qualified/unqualified column reference to an index in the concatenated row.
fn resolve_join_column_ref(
    ref_str: &str,
    left_table: &str,
    left_table_def: &TableDef,
    right_table: &str,
    right_table_def: &TableDef,
    left_col_count: usize,
) -> Result<usize> {
    // Parse qualified reference: "table.column" or just "column"
    if let Some((table, column)) = ref_str.split_once('.') {
        // Qualified: table.column
        if table == left_table {
            resolve_join_column(&column.into(), left_table, left_table_def, 0)
        } else if table == right_table {
            resolve_join_column(&column.into(), right_table, right_table_def, left_col_count)
        } else {
            Err(QueryError::TableNotFound(table.to_string()))
        }
    } else {
        // Unqualified: just "column" - try right table first (common pattern)
        if let Ok(idx) = resolve_join_column(
            &ref_str.into(),
            right_table,
            right_table_def,
            left_col_count,
        ) {
            Ok(idx)
        } else {
            resolve_join_column(&ref_str.into(), left_table, left_table_def, 0)
        }
    }
}

/// Builds a scan plan from the analyzed access path.
#[inline]
fn build_scan_plan(
    access_path: AccessPath,
    table_def: &TableDef,
    table_name: String,
    parsed: &ParsedSelect,
    params: &[Value],
    column_indices: Vec<usize>,
    column_names: Vec<ColumnName>,
) -> Result<QueryPlan> {
    let limit = resolve_limit(parsed.limit, params)?;
    let offset = resolve_limit(parsed.offset, params)?;
    match access_path {
        AccessPath::PointLookup { key_values } => Ok(build_point_lookup_plan(
            table_def,
            table_name,
            &key_values,
            column_indices,
            column_names,
        )),
        AccessPath::RangeScan {
            start_key,
            end_key,
            remaining_predicates,
        } => build_range_scan_plan(
            table_def,
            table_name,
            start_key,
            end_key,
            &remaining_predicates,
            limit,
            offset,
            &parsed.order_by,
            column_indices,
            column_names,
        ),
        AccessPath::IndexScan {
            index_id,
            index_name,
            start_key,
            end_key,
            remaining_predicates,
        } => build_index_scan_plan(
            table_def,
            table_name,
            index_id,
            index_name,
            start_key,
            end_key,
            &remaining_predicates,
            limit,
            offset,
            &parsed.order_by,
            column_indices,
            column_names,
        ),
        AccessPath::TableScan {
            predicates: all_predicates,
        } => build_table_scan_plan(
            table_def,
            table_name,
            &all_predicates,
            limit,
            offset,
            &parsed.order_by,
            column_indices,
            column_names,
        ),
    }
}

/// Resolves column selection for queries, accounting for aggregate requirements.
#[inline]
fn resolve_query_columns(
    table_def: &TableDef,
    parsed: &ParsedSelect,
    table_name: &str,
) -> Result<(Vec<usize>, Vec<ColumnName>)> {
    let needs_aggregate = !parsed.aggregates.is_empty()
        || !parsed.group_by.is_empty()
        || parsed.distinct
        || !parsed.having.is_empty();

    // For aggregate or scalar-projection queries, the source plan must
    // fetch ALL columns so the Materialize / Aggregate wrapper can
    // resolve column references by name. Aliases don't apply to the
    // source scan in that case — the wrapper's `column_names` is built
    // separately.
    if needs_aggregate || !parsed.scalar_projections.is_empty() {
        resolve_columns(table_def, None, None, table_name)
    } else {
        resolve_columns(
            table_def,
            parsed.columns.as_ref(),
            parsed.column_aliases.as_ref(),
            table_name,
        )
    }
}

/// Resolves column selection to indices and names.
///
/// ROADMAP v0.5.0 item A — when `aliases` is `Some(vec)` and
/// `aliases[i]` is `Some(alias)`, the output `names[i]` is the alias
/// rather than the source column name. The source column still
/// drives `indices` for projection; the alias affects only what the
/// client sees in `QueryResult.columns`.
fn resolve_columns(
    table_def: &TableDef,
    columns: Option<&Vec<ColumnName>>,
    aliases: Option<&Vec<Option<String>>>,
    table_name: &str,
) -> Result<(Vec<usize>, Vec<ColumnName>)> {
    match columns {
        None => {
            // SELECT * - return all columns
            let indices: Vec<usize> = (0..table_def.columns.len()).collect();
            let names: Vec<ColumnName> = table_def.columns.iter().map(|c| c.name.clone()).collect();
            Ok((indices, names))
        }
        Some(cols) => {
            let mut indices = Vec::with_capacity(cols.len());
            let mut names = Vec::with_capacity(cols.len());

            for (i, col) in cols.iter().enumerate() {
                let (idx, col_def) =
                    table_def
                        .find_column(col)
                        .ok_or_else(|| QueryError::ColumnNotFound {
                            table: table_name.to_string(),
                            column: col.to_string(),
                        })?;
                indices.push(idx);
                // If an alias was supplied for this position, stamp the
                // output name with the alias; otherwise fall back to the
                // column-def canonical name.
                let alias = aliases.and_then(|v| v.get(i)).and_then(|a| a.as_ref());
                let out_name = match alias {
                    Some(a) => ColumnName::new(a.clone()),
                    None => col_def.name.clone(),
                };
                names.push(out_name);
            }

            Ok((indices, names))
        }
    }
}

/// Resolved predicate with concrete values (parameters substituted).
#[derive(Debug, Clone)]
struct ResolvedPredicate {
    column: ColumnName,
    op: ResolvedOp,
}

#[derive(Debug, Clone)]
enum ResolvedOp {
    Eq(Value),
    Lt(Value),
    Le(Value),
    Gt(Value),
    Ge(Value),
    In(Vec<Value>),
    NotIn(Vec<Value>),
    NotBetween(Value, Value),
    Like(String),
    NotLike(String),
    ILike(String),
    NotILike(String),
    IsNull,
    IsNotNull,
    /// JSON path extraction with equality comparison (`->`/`->>`).
    JsonExtractEq {
        path: String,
        as_text: bool,
        value: Value,
    },
    /// JSON containment (`@>`).
    JsonContains(Value),
    Or(Vec<ResolvedPredicate>, Vec<ResolvedPredicate>),
    /// Tautology — matches every row (from `EXISTS` whose subquery had rows).
    AlwaysTrue,
    /// Contradiction — matches no rows (from `EXISTS` whose subquery was empty).
    AlwaysFalse,
    /// Comparison between two scalar expressions, evaluated per row.
    ///
    /// The `column` on the outer `ResolvedPredicate` is empty for this
    /// variant; the filter path evaluates `lhs` and `rhs` via
    /// [`crate::expression::evaluate`] against the full row. Mirrors
    /// the shape of [`super::Predicate::ScalarCmp`].
    ScalarCmp {
        lhs: ScalarExpr,
        op: ScalarCmpOp,
        rhs: ScalarExpr,
    },
}

/// Resolves predicates by substituting parameter values.
fn resolve_predicates(
    predicates: &[Predicate],
    params: &[Value],
) -> Result<Vec<ResolvedPredicate>> {
    predicates
        .iter()
        .map(|p| resolve_predicate(p, params))
        .collect()
}

fn resolve_predicate(predicate: &Predicate, params: &[Value]) -> Result<ResolvedPredicate> {
    match predicate {
        Predicate::Eq(col, val) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::Eq(resolve_value(val, params)?),
        }),
        Predicate::Lt(col, val) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::Lt(resolve_value(val, params)?),
        }),
        Predicate::Le(col, val) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::Le(resolve_value(val, params)?),
        }),
        Predicate::Gt(col, val) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::Gt(resolve_value(val, params)?),
        }),
        Predicate::Ge(col, val) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::Ge(resolve_value(val, params)?),
        }),
        Predicate::In(col, vals) => {
            let resolved: Result<Vec<_>> = vals.iter().map(|v| resolve_value(v, params)).collect();
            Ok(ResolvedPredicate {
                column: col.clone(),
                op: ResolvedOp::In(resolved?),
            })
        }
        Predicate::NotIn(col, vals) => {
            let resolved: Result<Vec<_>> = vals.iter().map(|v| resolve_value(v, params)).collect();
            Ok(ResolvedPredicate {
                column: col.clone(),
                op: ResolvedOp::NotIn(resolved?),
            })
        }
        Predicate::NotBetween(col, low, high) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::NotBetween(resolve_value(low, params)?, resolve_value(high, params)?),
        }),
        Predicate::ScalarCmp { lhs, op, rhs } => Ok(ResolvedPredicate {
            // ScalarCmp spans the whole row — no single column to key
            // off. Mirror Or/Always, which use the empty string and let
            // the filter path dispatch on the op.
            column: ColumnName::new(String::new()),
            op: ResolvedOp::ScalarCmp {
                lhs: substitute_scalar_params(lhs, params)?,
                op: *op,
                rhs: substitute_scalar_params(rhs, params)?,
            },
        }),
        Predicate::Like(col, pattern) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::Like(pattern.clone()),
        }),
        Predicate::NotLike(col, pattern) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::NotLike(pattern.clone()),
        }),
        Predicate::ILike(col, pattern) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::ILike(pattern.clone()),
        }),
        Predicate::NotILike(col, pattern) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::NotILike(pattern.clone()),
        }),
        Predicate::IsNull(col) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::IsNull,
        }),
        Predicate::IsNotNull(col) => Ok(ResolvedPredicate {
            column: col.clone(),
            op: ResolvedOp::IsNotNull,
        }),
        Predicate::JsonExtractEq {
            column,
            path,
            as_text,
            value,
        } => Ok(ResolvedPredicate {
            column: column.clone(),
            op: ResolvedOp::JsonExtractEq {
                path: path.clone(),
                as_text: *as_text,
                value: resolve_value(value, params)?,
            },
        }),
        Predicate::JsonContains { column, value } => Ok(ResolvedPredicate {
            column: column.clone(),
            op: ResolvedOp::JsonContains(resolve_value(value, params)?),
        }),
        // Subquery predicates are pre-executed and substituted in the
        // top-level query() entry point before reaching the planner.
        // If they reach here, that substitution failed.
        Predicate::InSubquery { .. } | Predicate::Exists { .. } => {
            Err(QueryError::UnsupportedFeature(
                "subquery predicate not pre-executed (likely a correlated subquery)".to_string(),
            ))
        }
        // Always(true)  → no-op; substitute with a tautological IS NOT NULL
        //                 against a primary-key column (which is never NULL).
        // Always(false) → impossible; substitute with IS NULL against a
        //                 primary-key column (which is never NULL → always
        //                 false).
        Predicate::Always(b) => {
            // We don't have access to the table here to pick a real column.
            // Use an empty column name; resolve_predicates handles this by
            // returning a non-error tautology/contradiction at filter level.
            // Tag the op so build_filter recognises it.
            Ok(ResolvedPredicate {
                column: ColumnName::new(String::new()),
                op: if *b {
                    ResolvedOp::AlwaysTrue
                } else {
                    ResolvedOp::AlwaysFalse
                },
            })
        }
        Predicate::Or(left_preds, right_preds) => {
            // For OR, we use a dummy column (empty string) since OR can span multiple columns
            let left_resolved = resolve_predicates(left_preds, params)?;
            let right_resolved = resolve_predicates(right_preds, params)?;
            Ok(ResolvedPredicate {
                column: ColumnName::new(String::new()),
                op: ResolvedOp::Or(left_resolved, right_resolved),
            })
        }
    }
}

fn resolve_value(val: &PredicateValue, params: &[Value]) -> Result<Value> {
    match val {
        PredicateValue::Int(v) => Ok(Value::BigInt(*v)),
        PredicateValue::String(s) => Ok(Value::Text(s.clone())),
        PredicateValue::Bool(b) => Ok(Value::Boolean(*b)),
        PredicateValue::Null => Ok(Value::Null),
        PredicateValue::Literal(v) => Ok(v.clone()),
        PredicateValue::Param(idx) => {
            // Parameters are 1-indexed in SQL
            let zero_idx = idx.checked_sub(1).ok_or(QueryError::ParameterNotFound(0))?;
            params
                .get(zero_idx)
                .cloned()
                .ok_or(QueryError::ParameterNotFound(*idx))
        }
        PredicateValue::ColumnRef(_) => Err(QueryError::UnsupportedFeature(
            "column references in WHERE clause not supported (use JOIN ON for column-to-column comparisons)".to_string(),
        )),
    }
}

/// Sample the system clock for a fresh statement-stable timestamp in
/// Unix nanoseconds. Lives at the planner boundary on purpose — the
/// evaluator stays pure (PRESSURECRAFT §1 FCIS), so the clock read is
/// done once per statement, threaded into the plan, and never sampled
/// inside row evaluation.
///
/// Returns `0` if the system clock is somehow before the Unix epoch;
/// callers can override with their own clock for deterministic VOPR
/// runs by calling [`fold_time_constants_in_plan`] directly.
pub fn current_statement_timestamp_ns() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos().min(i64::MAX as u128) as i64)
        .unwrap_or(0)
}

/// Convert a Unix-nanosecond timestamp to "days since Unix epoch"
/// (truncating toward negative infinity for pre-epoch values, though
/// the evaluator guards against negatives).
fn ns_to_days_since_epoch(ts_ns: i64) -> i32 {
    let days = ts_ns.div_euclid(86_400_000_000_000);
    let clamped = days.clamp(i64::from(i32::MIN), i64::from(i32::MAX));
    // Clamp guarantees the value fits in i32; the cast is lossless by
    // construction.
    #[allow(clippy::cast_possible_truncation)]
    {
        clamped as i32
    }
}

/// Walk a `ScalarExpr` tree and replace `ScalarExpr::Now` /
/// `CurrentTimestamp` with a `Literal(Timestamp(statement_ts_ns))` and
/// `CurrentDate` with `Literal(Date(days_since_epoch))`. The same
/// `statement_ts_ns` value MUST be used for every fold call within a
/// single statement so that two `NOW()` references in the same query
/// return identical timestamps (SQL standard: statement-stable).
///
/// Pure function. Called from [`fold_time_constants_in_plan`] and any
/// site that needs to stabilise scalar-expression trees before
/// evaluation. The companion `#[should_panic]` tests in
/// `expression.rs` (`now_panics_at_evaluator_when_unfolded` etc.)
/// remain the contract that the evaluator never sees a raw sentinel.
///
/// AUDIT-2026-05 S3.7 (planner-side completion of the fold contract
/// promised in v0.7.0).
pub fn fold_time_constants(expr: &ScalarExpr, statement_ts_ns: i64) -> ScalarExpr {
    fn f(e: &ScalarExpr, ts: i64) -> ScalarExpr {
        match e {
            ScalarExpr::Now | ScalarExpr::CurrentTimestamp => ScalarExpr::Literal(
                Value::Timestamp(kimberlite_types::Timestamp::from_nanos(ts.max(0) as u64)),
            ),
            ScalarExpr::CurrentDate => ScalarExpr::Literal(Value::Date(ns_to_days_since_epoch(ts))),
            // Recurse into operands so nested time-now references
            // (e.g. `EXTRACT(YEAR FROM NOW())`) are also folded.
            ScalarExpr::Literal(v) => ScalarExpr::Literal(v.clone()),
            ScalarExpr::Column(c) => ScalarExpr::Column(c.clone()),
            ScalarExpr::Upper(x) => ScalarExpr::Upper(Box::new(f(x, ts))),
            ScalarExpr::Lower(x) => ScalarExpr::Lower(Box::new(f(x, ts))),
            ScalarExpr::Length(x) => ScalarExpr::Length(Box::new(f(x, ts))),
            ScalarExpr::Trim(x) => ScalarExpr::Trim(Box::new(f(x, ts))),
            ScalarExpr::Concat(xs) => ScalarExpr::Concat(xs.iter().map(|x| f(x, ts)).collect()),
            ScalarExpr::Abs(x) => ScalarExpr::Abs(Box::new(f(x, ts))),
            ScalarExpr::Round(x) => ScalarExpr::Round(Box::new(f(x, ts))),
            ScalarExpr::RoundScale(x, n) => ScalarExpr::RoundScale(Box::new(f(x, ts)), *n),
            ScalarExpr::Ceil(x) => ScalarExpr::Ceil(Box::new(f(x, ts))),
            ScalarExpr::Floor(x) => ScalarExpr::Floor(Box::new(f(x, ts))),
            ScalarExpr::Coalesce(xs) => ScalarExpr::Coalesce(xs.iter().map(|x| f(x, ts)).collect()),
            ScalarExpr::Nullif(a, b) => ScalarExpr::Nullif(Box::new(f(a, ts)), Box::new(f(b, ts))),
            ScalarExpr::Cast(x, t) => ScalarExpr::Cast(Box::new(f(x, ts)), *t),
            ScalarExpr::Mod(a, b) => ScalarExpr::Mod(Box::new(f(a, ts)), Box::new(f(b, ts))),
            ScalarExpr::Power(a, b) => ScalarExpr::Power(Box::new(f(a, ts)), Box::new(f(b, ts))),
            ScalarExpr::Sqrt(x) => ScalarExpr::Sqrt(Box::new(f(x, ts))),
            ScalarExpr::Substring(x, r) => ScalarExpr::Substring(Box::new(f(x, ts)), *r),
            ScalarExpr::Extract(field, x) => ScalarExpr::Extract(*field, Box::new(f(x, ts))),
            ScalarExpr::DateTrunc(field, x) => ScalarExpr::DateTrunc(*field, Box::new(f(x, ts))),
        }
    }
    f(expr, statement_ts_ns)
}

/// Walk a [`Filter`] tree and fold any embedded [`ScalarExpr::Now`] /
/// `CurrentTimestamp` / `CurrentDate` sentinels. Called from
/// [`fold_time_constants_in_plan`].
fn fold_time_constants_in_filter(filter: &mut crate::plan::Filter, statement_ts_ns: i64) {
    use crate::plan::{Filter, FilterOp};
    match filter {
        Filter::Condition(cond) => {
            if let FilterOp::ScalarCmp { lhs, rhs, .. } = &mut cond.op {
                *lhs = fold_time_constants(lhs, statement_ts_ns);
                *rhs = fold_time_constants(rhs, statement_ts_ns);
            }
        }
        Filter::And(parts) | Filter::Or(parts) => {
            for p in parts {
                fold_time_constants_in_filter(p, statement_ts_ns);
            }
        }
    }
}

/// Walk a [`QueryPlan`] tree and fold every embedded `NOW()` /
/// `CURRENT_TIMESTAMP` / `CURRENT_DATE` sentinel into a literal,
/// using a single statement-stable timestamp. Mutates the plan in
/// place. The evaluator can then run pure (no clock read), and two
/// `NOW()` references in the same statement return identical values
/// per the SQL standard.
///
/// This is the production wiring of the contract that v0.7.0
/// established: the AST carries `ScalarExpr::Now` / `CurrentTimestamp`
/// / `CurrentDate` sentinels, the evaluator panics if it sees them
/// raw, and this function is the planner-side pass that replaces
/// them. AUDIT-2026-05 S3.7.
pub fn fold_time_constants_in_plan(plan: &mut QueryPlan, statement_ts_ns: i64) {
    match plan {
        QueryPlan::PointLookup { .. } => {
            // No scalar expressions in this shape.
        }
        QueryPlan::RangeScan { filter, .. }
        | QueryPlan::IndexScan { filter, .. }
        | QueryPlan::TableScan { filter, .. } => {
            if let Some(f) = filter {
                fold_time_constants_in_filter(f, statement_ts_ns);
            }
        }
        QueryPlan::Aggregate {
            source,
            aggregate_filters,
            ..
        } => {
            fold_time_constants_in_plan(source, statement_ts_ns);
            for af in aggregate_filters.iter_mut().flatten() {
                fold_time_constants_in_filter(af, statement_ts_ns);
            }
        }
        QueryPlan::Join { left, right, .. } => {
            fold_time_constants_in_plan(left, statement_ts_ns);
            fold_time_constants_in_plan(right, statement_ts_ns);
        }
        QueryPlan::Materialize {
            source,
            filter,
            scalar_columns,
            ..
        } => {
            fold_time_constants_in_plan(source, statement_ts_ns);
            if let Some(f) = filter {
                fold_time_constants_in_filter(f, statement_ts_ns);
            }
            for sc in scalar_columns {
                sc.expr = fold_time_constants(&sc.expr, statement_ts_ns);
            }
        }
    }
}

/// Walk a `ScalarExpr` tree and replace any `Literal(Placeholder(n))`
/// with the bound parameter value. Leaves other `Literal` variants
/// and column references untouched. Mirrors `resolve_value` but for
/// scalar-expression trees used by [`Predicate::ScalarCmp`] and
/// `ParsedScalarProjection`.
pub(crate) fn substitute_scalar_params(expr: &ScalarExpr, params: &[Value]) -> Result<ScalarExpr> {
    fn s(e: &ScalarExpr, p: &[Value]) -> Result<ScalarExpr> {
        Ok(match e {
            ScalarExpr::Literal(Value::Placeholder(idx)) => {
                let zero = idx.checked_sub(1).ok_or(QueryError::ParameterNotFound(0))?;
                let v = p
                    .get(zero)
                    .cloned()
                    .ok_or(QueryError::ParameterNotFound(*idx))?;
                ScalarExpr::Literal(v)
            }
            ScalarExpr::Literal(v) => ScalarExpr::Literal(v.clone()),
            ScalarExpr::Column(c) => ScalarExpr::Column(c.clone()),
            ScalarExpr::Upper(x) => ScalarExpr::Upper(Box::new(s(x, p)?)),
            ScalarExpr::Lower(x) => ScalarExpr::Lower(Box::new(s(x, p)?)),
            ScalarExpr::Length(x) => ScalarExpr::Length(Box::new(s(x, p)?)),
            ScalarExpr::Trim(x) => ScalarExpr::Trim(Box::new(s(x, p)?)),
            ScalarExpr::Concat(xs) => {
                ScalarExpr::Concat(xs.iter().map(|x| s(x, p)).collect::<Result<Vec<_>>>()?)
            }
            ScalarExpr::Abs(x) => ScalarExpr::Abs(Box::new(s(x, p)?)),
            ScalarExpr::Round(x) => ScalarExpr::Round(Box::new(s(x, p)?)),
            ScalarExpr::RoundScale(x, n) => ScalarExpr::RoundScale(Box::new(s(x, p)?), *n),
            ScalarExpr::Ceil(x) => ScalarExpr::Ceil(Box::new(s(x, p)?)),
            ScalarExpr::Floor(x) => ScalarExpr::Floor(Box::new(s(x, p)?)),
            ScalarExpr::Coalesce(xs) => {
                ScalarExpr::Coalesce(xs.iter().map(|x| s(x, p)).collect::<Result<Vec<_>>>()?)
            }
            ScalarExpr::Nullif(a, b) => ScalarExpr::Nullif(Box::new(s(a, p)?), Box::new(s(b, p)?)),
            ScalarExpr::Cast(x, t) => ScalarExpr::Cast(Box::new(s(x, p)?), *t),
            // v0.7.0 scalar functions — recurse into operands.
            ScalarExpr::Mod(a, b) => ScalarExpr::Mod(Box::new(s(a, p)?), Box::new(s(b, p)?)),
            ScalarExpr::Power(a, b) => ScalarExpr::Power(Box::new(s(a, p)?), Box::new(s(b, p)?)),
            ScalarExpr::Sqrt(x) => ScalarExpr::Sqrt(Box::new(s(x, p)?)),
            ScalarExpr::Substring(x, r) => ScalarExpr::Substring(Box::new(s(x, p)?), *r),
            ScalarExpr::Extract(f, x) => ScalarExpr::Extract(*f, Box::new(s(x, p)?)),
            ScalarExpr::DateTrunc(f, x) => ScalarExpr::DateTrunc(*f, Box::new(s(x, p)?)),
            // Time-now sentinels carry no operands; identity.
            ScalarExpr::Now => ScalarExpr::Now,
            ScalarExpr::CurrentTimestamp => ScalarExpr::CurrentTimestamp,
            ScalarExpr::CurrentDate => ScalarExpr::CurrentDate,
        })
    }
    s(expr, params)
}

/// Access path determined by predicate analysis.
enum AccessPath {
    /// Point lookup on primary key.
    PointLookup { key_values: Vec<Value> },
    /// Range scan on primary key.
    RangeScan {
        start_key: Bound<kimberlite_store::Key>,
        end_key: Bound<kimberlite_store::Key>,
        remaining_predicates: Vec<ResolvedPredicate>,
    },
    /// Index scan on a secondary index.
    IndexScan {
        index_id: u64,
        index_name: String,
        start_key: Bound<kimberlite_store::Key>,
        end_key: Bound<kimberlite_store::Key>,
        remaining_predicates: Vec<ResolvedPredicate>,
    },
    /// Full table scan.
    TableScan { predicates: Vec<ResolvedPredicate> },
}

/// Analyzes predicates to determine the optimal access path.
fn analyze_access_path(table_def: &TableDef, predicates: &[ResolvedPredicate]) -> AccessPath {
    let pk_columns = &table_def.primary_key;

    if pk_columns.is_empty() {
        // No primary key - must do table scan
        return AccessPath::TableScan {
            predicates: predicates.to_vec(),
        };
    }

    // Check for point lookup: all PK columns have equality predicates
    let mut pk_values: Vec<Option<Value>> = vec![None; pk_columns.len()];
    let mut non_pk_predicates = Vec::new();

    for pred in predicates {
        if let Some(pk_pos) = table_def.primary_key_position(&pred.column) {
            if let ResolvedOp::Eq(val) = &pred.op {
                pk_values[pk_pos] = Some(val.clone());
                continue;
            }
        }
        non_pk_predicates.push(pred.clone());
    }

    // Check if we have all PK columns with equality
    if pk_values.iter().all(Option::is_some) {
        let key_values: Vec<Value> = pk_values.into_iter().flatten().collect();
        return AccessPath::PointLookup { key_values };
    }

    // Check for range scan: first PK column(s) have predicates
    // For simplicity, only handle single-column PK range scans for now
    if pk_columns.len() == 1 {
        let pk_col = &pk_columns[0];
        let pk_predicates: Vec<_> = predicates.iter().filter(|p| &p.column == pk_col).collect();

        if !pk_predicates.is_empty() {
            let bounds_result = compute_range_bounds(&pk_predicates);

            // Unsatisfiable bound set (e.g., `x > 5 AND x < 3`) —
            // short-circuit before the store ever sees an inverted
            // range. AUDIT-2026-05 H-3.
            if bounds_result.is_empty {
                return AccessPath::TableScan {
                    predicates: vec![ResolvedPredicate {
                        column: ColumnName::new(String::new()),
                        op: ResolvedOp::AlwaysFalse,
                    }],
                };
            }

            // If we have useful bounds (not both unbounded), use range scan
            let has_bounds = !matches!(
                (&bounds_result.start, &bounds_result.end),
                (Bound::Unbounded, Bound::Unbounded)
            );

            if has_bounds {
                // Collect remaining predicates: non-PK predicates + unconverted PK predicates
                let mut remaining: Vec<_> = predicates
                    .iter()
                    .filter(|p| &p.column != pk_col)
                    .cloned()
                    .collect();
                remaining.extend(bounds_result.unconverted);

                return AccessPath::RangeScan {
                    start_key: bounds_result.start,
                    end_key: bounds_result.end,
                    remaining_predicates: remaining,
                };
            }
            // If no useful bounds (e.g., only IN predicates), fall through to index scan check
        }
    }

    // Check for index scan: find indexes that can be used
    let index_candidates = find_usable_indexes(table_def, predicates);
    if let Some((best_index, start, end, remaining)) = select_best_index(&index_candidates) {
        return AccessPath::IndexScan {
            index_id: best_index.index_id,
            index_name: best_index.name.clone(),
            start_key: start,
            end_key: end,
            remaining_predicates: remaining,
        };
    }

    // Fall back to table scan
    AccessPath::TableScan {
        predicates: predicates.to_vec(),
    }
}

/// Result of computing range bounds from predicates.
struct RangeBoundsResult {
    start: Bound<kimberlite_store::Key>,
    end: Bound<kimberlite_store::Key>,
    /// Predicates that couldn't be converted to bounds (e.g., IN).
    unconverted: Vec<ResolvedPredicate>,
    /// AUDIT-2026-05 H-3 — set when the lowering produced an
    /// unsatisfiable predicate set (e.g. `x > 5 AND x < 3`). The
    /// caller is responsible for short-circuiting to an empty
    /// result rather than passing inverted bounds down to the
    /// store, which would have to defensively clamp them. Closes
    /// the inverted-range planner output deferred from v0.6.1
    /// (the `cfg(not(fuzzing))` debug-assert escape hatch in
    /// `kimberlite-store::btree::scan`).
    is_empty: bool,
}

/// Computes range bounds from predicates on a single column.
fn compute_range_bounds(predicates: &[&ResolvedPredicate]) -> RangeBoundsResult {
    let mut lower: Option<(Value, bool)> = None; // (value, inclusive)
    let mut upper: Option<(Value, bool)> = None;
    let mut unconverted = Vec::new();

    for pred in predicates {
        match &pred.op {
            ResolvedOp::Eq(val) => {
                // Exact match - both bounds are this value
                lower = Some((val.clone(), true));
                upper = Some((val.clone(), true));
            }
            ResolvedOp::Gt(val) => {
                lower = Some((val.clone(), false));
            }
            ResolvedOp::Ge(val) => {
                lower = Some((val.clone(), true));
            }
            ResolvedOp::Lt(val) => {
                upper = Some((val.clone(), false));
            }
            ResolvedOp::Le(val) => {
                upper = Some((val.clone(), true));
            }
            ResolvedOp::In(_)
            | ResolvedOp::NotIn(_)
            | ResolvedOp::NotBetween(_, _)
            | ResolvedOp::Like(_)
            | ResolvedOp::NotLike(_)
            | ResolvedOp::ILike(_)
            | ResolvedOp::NotILike(_)
            | ResolvedOp::IsNull
            | ResolvedOp::IsNotNull
            | ResolvedOp::JsonExtractEq { .. }
            | ResolvedOp::JsonContains(_)
            | ResolvedOp::AlwaysTrue
            | ResolvedOp::AlwaysFalse
            | ResolvedOp::Or(_, _)
            | ResolvedOp::ScalarCmp { .. } => {
                // These can't be converted to range bounds - add to filter
                unconverted.push((*pred).clone());
            }
        }
    }

    let start = match &lower {
        Some((val, true)) => Bound::Included(encode_key(&[val.clone()])),
        Some((val, false)) => Bound::Excluded(encode_key(&[val.clone()])),
        None => Bound::Unbounded,
    };

    let end = match &upper {
        Some((val, true)) => {
            // For inclusive upper bound, we need the successor key
            Bound::Excluded(successor_key(&encode_key(&[val.clone()])))
        }
        Some((val, false)) => Bound::Excluded(encode_key(&[val.clone()])),
        None => Bound::Unbounded,
    };

    // AUDIT-2026-05 H-3 — detect unsatisfiable bound combinations
    // upstream of the storage scan. A prior version relied on the
    // store's defensive clamp (`if range.start >= range.end { return
    // empty }`) plus a `cfg(not(fuzzing))` debug-assert; the
    // assert had to be muted because the planner legitimately
    // emitted inverted ranges for inputs like `x > 5 AND x < 3`.
    // Detecting at the source means the store can keep its
    // assertion live in fuzz builds too — closing the loop with
    // PRESSURECRAFT §3 (parse-don't-validate: an inverted range
    // is now unrepresentable in `RangeBoundsResult` whose caller
    // honours `is_empty`).
    let is_empty = bounds_are_unsatisfiable(&start, &end);

    RangeBoundsResult {
        start,
        end,
        unconverted,
        is_empty,
    }
}

/// Returns `true` when the (start, end) pair describes the empty
/// range: encoded `start_bytes > end_bytes`, or `start_bytes ==
/// end_bytes` with at least one side excluded.
///
/// `Unbounded` on either side is never empty (one-sided ranges are
/// satisfiable). Bytes-level comparison is the source of truth:
/// post-encoding inversion (e.g. successor-key arithmetic on
/// inclusive-upper bounds) is what the downstream store sees, so
/// that's what we check.
fn bounds_are_unsatisfiable(
    start: &Bound<kimberlite_store::Key>,
    end: &Bound<kimberlite_store::Key>,
) -> bool {
    use std::cmp::Ordering;
    let (start_bytes, start_excluded) = match start {
        Bound::Included(b) => (b.as_ref(), false),
        Bound::Excluded(b) => (b.as_ref(), true),
        Bound::Unbounded => return false,
    };
    let (end_bytes, end_excluded) = match end {
        Bound::Included(b) => (b.as_ref(), false),
        Bound::Excluded(b) => (b.as_ref(), true),
        Bound::Unbounded => return false,
    };

    match start_bytes.cmp(end_bytes) {
        Ordering::Greater => true,
        Ordering::Equal => start_excluded || end_excluded,
        Ordering::Less => false,
    }
}

/// Candidate index with its bounds and remaining predicates.
struct IndexCandidate<'a> {
    index_def: &'a crate::schema::IndexDef,
    start: Bound<kimberlite_store::Key>,
    end: Bound<kimberlite_store::Key>,
    remaining: Vec<ResolvedPredicate>,
    score: usize,
}

/// Finds indexes that can be used for the given predicates.
///
/// Returns a list of index candidates with their computed bounds.
/// Only includes indexes where the first column has predicates.
fn find_usable_indexes<'a>(
    table_def: &'a TableDef,
    predicates: &[ResolvedPredicate],
) -> Vec<IndexCandidate<'a>> {
    let mut candidates = Vec::new();
    let max_iterations = 100; // Bounded iteration limit

    for (iter_count, index_def) in table_def.indexes().iter().enumerate() {
        // Bounded iteration check
        if iter_count >= max_iterations {
            break;
        }

        // Skip empty indexes
        if index_def.columns.is_empty() {
            continue;
        }

        // Check if first column has predicates
        let first_col = &index_def.columns[0];
        let first_col_predicates: Vec<_> = predicates
            .iter()
            .filter(|p| &p.column == first_col)
            .collect();

        if first_col_predicates.is_empty() {
            continue;
        }

        // Compute range bounds for this index
        let bounds_result = compute_range_bounds(&first_col_predicates);

        // Unsatisfiable bounds disqualify the index entirely; the
        // caller's PK-range short-circuit (above) already handles
        // the common case, but a non-PK index reaching here with
        // an inverted predicate set would otherwise emit an
        // inverted-range scan. Skip silently — the table-scan
        // fallback's `AlwaysFalse` predicate will report empty.
        // AUDIT-2026-05 H-3.
        if bounds_result.is_empty {
            continue;
        }

        // Skip if both bounds are unbounded (no useful range)
        if matches!(
            (&bounds_result.start, &bounds_result.end),
            (Bound::Unbounded, Bound::Unbounded)
        ) {
            continue;
        }

        // Collect remaining predicates (non-index predicates + unconverted)
        let mut remaining: Vec<_> = predicates
            .iter()
            .filter(|p| !index_def.columns.contains(&p.column))
            .cloned()
            .collect();
        remaining.extend(bounds_result.unconverted);

        // Score this index
        let score = score_index(index_def, predicates);

        candidates.push(IndexCandidate {
            index_def,
            start: bounds_result.start,
            end: bounds_result.end,
            remaining,
            score,
        });
    }

    candidates
}

/// Scores an index based on predicate coverage.
///
/// Returns higher scores for indexes that cover more predicates with better match types.
fn score_index(index_def: &crate::schema::IndexDef, predicates: &[ResolvedPredicate]) -> usize {
    let mut score = 0;
    let max_columns = 10; // Bounded iteration limit

    for (iter_count, index_col) in index_def.columns.iter().enumerate() {
        // Bounded iteration check
        if iter_count >= max_columns {
            break;
        }

        for pred in predicates {
            if &pred.column == index_col {
                match &pred.op {
                    ResolvedOp::Eq(_) => score += 10, // Equality predicates are best
                    ResolvedOp::Lt(_)
                    | ResolvedOp::Le(_)
                    | ResolvedOp::Gt(_)
                    | ResolvedOp::Ge(_) => {
                        score += 5; // Range predicates are good
                    }
                    _ => score += 1, // Other predicates have minor benefit
                }
            }
        }
    }

    score
}

/// Return type for index selection with index definition, key bounds, and remaining predicates.
type BestIndexResult<'a> = (
    &'a crate::schema::IndexDef,
    Bound<kimberlite_store::Key>,
    Bound<kimberlite_store::Key>,
    Vec<ResolvedPredicate>,
);

/// Selects the best index from candidates.
///
/// Returns the index with the highest score, breaking ties by fewest remaining predicates.
fn select_best_index<'a>(candidates: &'a [IndexCandidate<'a>]) -> Option<BestIndexResult<'a>> {
    if candidates.is_empty() {
        return None;
    }

    // Find the maximum score
    let max_score = candidates.iter().map(|c| c.score).max().unwrap_or(0);

    // Filter to candidates with max score
    let best_candidates: Vec<_> = candidates.iter().filter(|c| c.score == max_score).collect();

    // Among ties, select the one with fewest remaining predicates
    let best = best_candidates
        .iter()
        .min_by_key(|c| (c.remaining.len(), c.index_def.columns.len()))?;

    Some((
        best.index_def,
        best.start.clone(),
        best.end.clone(),
        best.remaining.clone(),
    ))
}

/// Builds a filter from remaining predicates.
fn build_filter(
    table_def: &TableDef,
    predicates: &[ResolvedPredicate],
    table_name: &str,
) -> Result<Option<Filter>> {
    if predicates.is_empty() {
        return Ok(None);
    }

    let filters: Result<Vec<_>> = predicates
        .iter()
        .map(|p| build_filter_from_predicate(table_def, p, table_name))
        .collect();

    Ok(Some(Filter::and(filters?)))
}

/// Builds a filter from a single resolved predicate.
/// Handles OR predicates recursively.
fn build_filter_from_predicate(
    table_def: &TableDef,
    pred: &ResolvedPredicate,
    table_name: &str,
) -> Result<Filter> {
    if let ResolvedOp::Or(left_preds, right_preds) = &pred.op {
        // Recursively build filters for left and right sides
        let left_filter = build_filter(table_def, left_preds, table_name)?.ok_or_else(|| {
            QueryError::UnsupportedFeature("OR left side has no predicates".to_string())
        })?;
        let right_filter = build_filter(table_def, right_preds, table_name)?.ok_or_else(|| {
            QueryError::UnsupportedFeature("OR right side has no predicates".to_string())
        })?;

        Ok(Filter::or(vec![left_filter, right_filter]))
    } else {
        // For non-OR predicates, build a FilterCondition
        let condition = build_filter_condition(table_def, pred, table_name)?;
        Ok(Filter::single(condition))
    }
}

fn build_filter_condition(
    table_def: &TableDef,
    pred: &ResolvedPredicate,
    table_name: &str,
) -> Result<FilterCondition> {
    // AlwaysTrue / AlwaysFalse don't reference a column — short-circuit before
    // the column lookup so the empty column name doesn't surface as an error.
    if matches!(pred.op, ResolvedOp::AlwaysTrue) {
        return Ok(FilterCondition {
            column_idx: 0,
            op: FilterOp::AlwaysTrue,
            value: Value::Null,
        });
    }
    if matches!(pred.op, ResolvedOp::AlwaysFalse) {
        return Ok(FilterCondition {
            column_idx: 0,
            op: FilterOp::AlwaysFalse,
            value: Value::Null,
        });
    }
    // ScalarCmp spans the whole row — carry the table's column layout
    // alongside the expression trees so `ScalarExpr::Column(name)`
    // resolves positionally at evaluation time.
    if let ResolvedOp::ScalarCmp { lhs, op, rhs } = &pred.op {
        let columns: Arc<[ColumnName]> = table_def
            .columns
            .iter()
            .map(|c| c.name.clone())
            .collect::<Vec<_>>()
            .into();
        return Ok(FilterCondition {
            column_idx: 0,
            op: FilterOp::ScalarCmp {
                columns,
                lhs: lhs.clone(),
                op: *op,
                rhs: rhs.clone(),
            },
            value: Value::Null,
        });
    }

    let (col_idx, _) =
        table_def
            .find_column(&pred.column)
            .ok_or_else(|| QueryError::ColumnNotFound {
                table: table_name.to_string(),
                column: pred.column.to_string(),
            })?;

    let (op, value) = match &pred.op {
        ResolvedOp::Eq(v) => (FilterOp::Eq, v.clone()),
        ResolvedOp::Lt(v) => (FilterOp::Lt, v.clone()),
        ResolvedOp::Le(v) => (FilterOp::Le, v.clone()),
        ResolvedOp::Gt(v) => (FilterOp::Gt, v.clone()),
        ResolvedOp::Ge(v) => (FilterOp::Ge, v.clone()),
        ResolvedOp::In(vals) => (FilterOp::In(vals.clone()), Value::Null), // Value unused for In
        ResolvedOp::NotIn(vals) => (FilterOp::NotIn(vals.clone()), Value::Null),
        ResolvedOp::NotBetween(low, high) => {
            (FilterOp::NotBetween(low.clone(), high.clone()), Value::Null)
        }
        ResolvedOp::Like(pattern) => (FilterOp::Like(pattern.clone()), Value::Null),
        ResolvedOp::NotLike(pattern) => (FilterOp::NotLike(pattern.clone()), Value::Null),
        ResolvedOp::ILike(pattern) => (FilterOp::ILike(pattern.clone()), Value::Null),
        ResolvedOp::NotILike(pattern) => (FilterOp::NotILike(pattern.clone()), Value::Null),
        ResolvedOp::IsNull => (FilterOp::IsNull, Value::Null),
        ResolvedOp::IsNotNull => (FilterOp::IsNotNull, Value::Null),
        ResolvedOp::JsonExtractEq {
            path,
            as_text,
            value: v,
        } => (
            FilterOp::JsonExtractEq {
                path: path.clone(),
                as_text: *as_text,
                value: v.clone(),
            },
            Value::Null,
        ),
        ResolvedOp::JsonContains(v) => (FilterOp::JsonContains(v.clone()), Value::Null),
        ResolvedOp::AlwaysTrue => (FilterOp::AlwaysTrue, Value::Null),
        ResolvedOp::AlwaysFalse => (FilterOp::AlwaysFalse, Value::Null),
        ResolvedOp::Or(_, _) => {
            // OR predicates need special handling - they can't be represented as a single FilterCondition
            return Err(QueryError::UnsupportedFeature(
                "OR predicates must be handled at filter level, not as individual conditions"
                    .to_string(),
            ));
        }
        ResolvedOp::ScalarCmp { .. } => {
            // Unreachable — handled by the short-circuit above.
            unreachable!("ScalarCmp must be handled by the short-circuit branch");
        }
    };

    Ok(FilterCondition {
        column_idx: col_idx,
        op,
        value,
    })
}

/// Determines scan order from ORDER BY for range scans.
fn determine_scan_order(order_by: &[OrderByClause], table_def: &TableDef) -> ScanOrder {
    if order_by.is_empty() {
        return ScanOrder::Ascending;
    }

    // Check if first ORDER BY column is in the primary key
    let first = &order_by[0];
    if table_def.is_primary_key(&first.column) {
        if first.ascending {
            ScanOrder::Ascending
        } else {
            ScanOrder::Descending
        }
    } else {
        ScanOrder::Ascending
    }
}

/// Builds a sort specification for table scans.
fn build_sort_spec(
    order_by: &[OrderByClause],
    table_def: &TableDef,
    table_name: &str,
) -> Result<Option<SortSpec>> {
    if order_by.is_empty() {
        return Ok(None);
    }

    let mut columns = Vec::with_capacity(order_by.len());

    for clause in order_by {
        let (col_idx, _) =
            table_def
                .find_column(&clause.column)
                .ok_or_else(|| QueryError::ColumnNotFound {
                    table: table_name.to_string(),
                    column: clause.column.to_string(),
                })?;

        let order = if clause.ascending {
            ScanOrder::Ascending
        } else {
            ScanOrder::Descending
        };

        columns.push((col_idx, order));
    }

    Ok(Some(SortSpec { columns }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::{ParsedStatement, parse_statement};
    use crate::schema::{ColumnDef, DataType, SchemaBuilder};
    use kimberlite_store::TableId;

    fn parse_test_select(sql: &str) -> ParsedSelect {
        match parse_statement(sql).unwrap() {
            ParsedStatement::Select(s) => s,
            _ => panic!("expected SELECT statement"),
        }
    }

    fn test_schema() -> Schema {
        SchemaBuilder::new()
            .table(
                "users",
                TableId::new(1),
                vec![
                    ColumnDef::new("id", DataType::BigInt).not_null(),
                    ColumnDef::new("name", DataType::Text).not_null(),
                    ColumnDef::new("age", DataType::BigInt),
                ],
                vec!["id".into()],
            )
            .build()
    }

    #[test]
    fn test_plan_point_lookup() {
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM users WHERE id = 42");
        let plan = plan_query(&schema, &parsed, &[]).unwrap();

        assert!(matches!(plan, QueryPlan::PointLookup { .. }));
    }

    #[test]
    fn test_plan_range_scan() {
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM users WHERE id > 10");
        let plan = plan_query(&schema, &parsed, &[]).unwrap();

        assert!(matches!(plan, QueryPlan::RangeScan { .. }));
    }

    #[test]
    fn test_plan_table_scan() {
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM users WHERE name = 'alice'");
        let plan = plan_query(&schema, &parsed, &[]).unwrap();

        assert!(matches!(plan, QueryPlan::TableScan { .. }));
    }

    #[test]
    fn test_plan_with_params() {
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM users WHERE id = $1");
        let plan = plan_query(&schema, &parsed, &[Value::BigInt(42)]).unwrap();

        assert!(matches!(plan, QueryPlan::PointLookup { .. }));
    }

    #[test]
    fn test_plan_missing_param() {
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM users WHERE id = $1");
        let result = plan_query(&schema, &parsed, &[]);

        assert!(matches!(result, Err(QueryError::ParameterNotFound(1))));
    }

    #[test]
    fn test_plan_unknown_table() {
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM unknown");
        let result = plan_query(&schema, &parsed, &[]);

        assert!(matches!(result, Err(QueryError::TableNotFound(_))));
    }

    #[test]
    fn test_plan_unknown_column() {
        let schema = test_schema();
        let parsed = parse_test_select("SELECT unknown FROM users");
        let result = plan_query(&schema, &parsed, &[]);

        assert!(matches!(result, Err(QueryError::ColumnNotFound { .. })));
    }

    // AUDIT-2026-05 H-3 — inverted-range planner regression
    // coverage. Every shape that produces an unsatisfiable PK
    // predicate set must short-circuit to a TableScan with an
    // AlwaysFalse filter, never an inverted RangeScan that the
    // store has to defensively clamp.

    #[test]
    fn inverted_range_pk_short_circuits_to_alwaysfalse_table_scan() {
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM users WHERE id > 5 AND id < 3");
        let plan = plan_query(&schema, &parsed, &[]).unwrap();

        match plan {
            QueryPlan::TableScan { filter, .. } => {
                let filter_str = format!("{filter:?}");
                assert!(
                    filter_str.contains("AlwaysFalse"),
                    "expected AlwaysFalse filter for x > 5 AND x < 3, got: {filter_str}"
                );
            }
            other => panic!("expected TableScan with AlwaysFalse filter, got: {other:?}"),
        }
    }

    #[test]
    fn excluded_equal_bounds_pk_short_circuits() {
        // x > 5 AND x < 5 — bounds at the same value but both excluded.
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM users WHERE id > 5 AND id < 5");
        let plan = plan_query(&schema, &parsed, &[]).unwrap();
        assert!(matches!(plan, QueryPlan::TableScan { .. }));
    }

    #[test]
    fn one_sided_lower_bound_still_uses_range_scan() {
        // Sanity: x > 5 (no upper) is satisfiable, must remain a
        // RangeScan. Guards against an over-eager is_empty
        // detector that flags Unbounded-on-one-side as empty.
        let schema = test_schema();
        let parsed = parse_test_select("SELECT * FROM users WHERE id > 5");
        let plan = plan_query(&schema, &parsed, &[]).unwrap();
        assert!(matches!(plan, QueryPlan::RangeScan { .. }));
    }

    #[test]
    fn bounds_are_unsatisfiable_unit() {
        // Direct test of the helper — not via the planner so any
        // refactor of compute_range_bounds keeps the contract
        // intact.
        use std::ops::Bound;

        // Both unbounded → satisfiable.
        assert!(!bounds_are_unsatisfiable(
            &Bound::<kimberlite_store::Key>::Unbounded,
            &Bound::Unbounded,
        ));
        // Inclusive equal → satisfiable (point lookup).
        let k = kimberlite_store::Key::from(vec![1u8, 2, 3]);
        assert!(!bounds_are_unsatisfiable(
            &Bound::Included(k.clone()),
            &Bound::Included(k.clone()),
        ));
        // Excluded equal → empty.
        assert!(bounds_are_unsatisfiable(
            &Bound::Excluded(k.clone()),
            &Bound::Excluded(k.clone()),
        ));
        // start > end → empty.
        let k_high = kimberlite_store::Key::from(vec![9u8]);
        let k_low = kimberlite_store::Key::from(vec![1u8]);
        assert!(bounds_are_unsatisfiable(
            &Bound::Included(k_high),
            &Bound::Included(k_low),
        ));
    }

    // ============================================================================
    // AUDIT-2026-05 S3.7 — fold_time_constants production wiring tests.
    //
    // Companion to the `#[should_panic]` tests in `expression.rs` that
    // pin the contract "evaluator panics on raw NOW/CURRENT_TIMESTAMP/
    // CURRENT_DATE." These tests prove the planner-side fold pass
    // actually replaces the sentinels with literals so the evaluator
    // never sees them.
    // ============================================================================

    #[test]
    fn fold_time_constants_replaces_now_with_timestamp_literal() {
        let ts_ns = 1_746_316_800_i64 * 1_000_000_000; // 2025-05-04T00:00:00Z
        let folded = fold_time_constants(&ScalarExpr::Now, ts_ns);
        match folded {
            ScalarExpr::Literal(Value::Timestamp(t)) => {
                assert_eq!(t.as_nanos() as i64, ts_ns);
            }
            other => panic!("expected Literal(Timestamp), got {other:?}"),
        }
    }

    #[test]
    fn fold_time_constants_replaces_current_timestamp() {
        let ts_ns = 1_746_316_800_i64 * 1_000_000_000;
        let folded = fold_time_constants(&ScalarExpr::CurrentTimestamp, ts_ns);
        match folded {
            ScalarExpr::Literal(Value::Timestamp(t)) => {
                assert_eq!(t.as_nanos() as i64, ts_ns);
            }
            other => panic!("expected Literal(Timestamp), got {other:?}"),
        }
    }

    #[test]
    fn fold_time_constants_replaces_current_date_with_days_since_epoch() {
        // 2025-05-04T00:00:00Z = 20212 days since epoch.
        let ts_ns = 1_746_316_800_i64 * 1_000_000_000;
        let folded = fold_time_constants(&ScalarExpr::CurrentDate, ts_ns);
        match folded {
            ScalarExpr::Literal(Value::Date(days)) => {
                assert_eq!(days, 20_212);
            }
            other => panic!("expected Literal(Date), got {other:?}"),
        }
    }

    #[test]
    fn fold_time_constants_recurses_into_operands() {
        // EXTRACT(YEAR FROM NOW()) — fold must descend into the inner
        // operand so the EXTRACT evaluator sees a Timestamp literal.
        let ts_ns = 1_746_316_800_i64 * 1_000_000_000;
        let expr =
            ScalarExpr::Extract(kimberlite_types::DateField::Year, Box::new(ScalarExpr::Now));
        let folded = fold_time_constants(&expr, ts_ns);
        match folded {
            ScalarExpr::Extract(field, inner) => {
                assert_eq!(field, kimberlite_types::DateField::Year);
                match *inner {
                    ScalarExpr::Literal(Value::Timestamp(_)) => {}
                    other => panic!("expected Literal(Timestamp) inner, got {other:?}"),
                }
            }
            other => panic!("expected Extract, got {other:?}"),
        }
    }

    #[test]
    fn fold_time_constants_is_idempotent_on_non_sentinel_exprs() {
        // Folding a tree without Now/CurrentTimestamp/CurrentDate is
        // a structural no-op (trivially: the fold function is a deep
        // clone that only rewrites three variants).
        let ts_ns = 1_746_316_800_i64 * 1_000_000_000;
        let expr = ScalarExpr::Upper(Box::new(ScalarExpr::Literal(Value::Text("hi".into()))));
        let folded = fold_time_constants(&expr, ts_ns);
        match folded {
            ScalarExpr::Upper(inner) => match *inner {
                ScalarExpr::Literal(Value::Text(s)) => assert_eq!(s, "hi"),
                other => panic!("unexpected inner: {other:?}"),
            },
            other => panic!("expected Upper, got {other:?}"),
        }
    }

    #[test]
    fn fold_time_constants_is_deterministic_with_same_clock() {
        // Two NOW() folds with the same statement_ts_ns must produce
        // identical Timestamp literals — that's the SQL standard's
        // statement-stable contract for NOW().
        let ts_ns = 1_746_316_800_i64 * 1_000_000_000;
        let a = fold_time_constants(&ScalarExpr::Now, ts_ns);
        let b = fold_time_constants(&ScalarExpr::Now, ts_ns);
        match (a, b) {
            (
                ScalarExpr::Literal(Value::Timestamp(ta)),
                ScalarExpr::Literal(Value::Timestamp(tb)),
            ) => assert_eq!(ta.as_nanos(), tb.as_nanos()),
            other => panic!("expected matching Timestamp literals: {other:?}"),
        }
    }

    fn find_scalar_columns(p: &QueryPlan) -> Option<&[crate::plan::ScalarColumnDef]> {
        match p {
            QueryPlan::Materialize { scalar_columns, .. } => Some(scalar_columns),
            QueryPlan::Aggregate { source, .. } => find_scalar_columns(source),
            _ => None,
        }
    }

    fn assert_no_sentinel(e: &ScalarExpr) {
        match e {
            ScalarExpr::Now | ScalarExpr::CurrentTimestamp | ScalarExpr::CurrentDate => {
                panic!("planner left an unfolded time-now sentinel in the plan");
            }
            ScalarExpr::Upper(x)
            | ScalarExpr::Lower(x)
            | ScalarExpr::Length(x)
            | ScalarExpr::Trim(x)
            | ScalarExpr::Abs(x)
            | ScalarExpr::Round(x)
            | ScalarExpr::Ceil(x)
            | ScalarExpr::Floor(x)
            | ScalarExpr::RoundScale(x, _)
            | ScalarExpr::Sqrt(x)
            | ScalarExpr::Substring(x, _)
            | ScalarExpr::Extract(_, x)
            | ScalarExpr::DateTrunc(_, x)
            | ScalarExpr::Cast(x, _) => assert_no_sentinel(x),
            ScalarExpr::Concat(xs) | ScalarExpr::Coalesce(xs) => {
                for x in xs {
                    assert_no_sentinel(x);
                }
            }
            ScalarExpr::Nullif(a, b) | ScalarExpr::Mod(a, b) | ScalarExpr::Power(a, b) => {
                assert_no_sentinel(a);
                assert_no_sentinel(b);
            }
            ScalarExpr::Literal(_) | ScalarExpr::Column(_) => {}
        }
    }

    #[test]
    fn plan_query_with_clock_folds_select_now() {
        // End-to-end: parse `SELECT NOW()`, plan it, verify the
        // resulting Materialize plan's scalar_columns contains a
        // Literal(Timestamp), not a raw `Now` sentinel.
        let schema = test_schema();
        let parsed = parse_test_select("SELECT NOW() FROM users");
        let ts_ns = 1_746_316_800_i64 * 1_000_000_000;
        let plan = plan_query_with_clock(&schema, &parsed, &[], ts_ns).unwrap();

        let scalars = find_scalar_columns(&plan).expect("plan must have scalar projection");
        assert!(!scalars.is_empty(), "expected at least one scalar column");
        for sc in scalars {
            assert_no_sentinel(&sc.expr);
        }
    }
}