reddb-io-server 1.2.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
//! Zero-copy scan path for MSG_QUERY_BINARY.
//!
//! Serves a narrow class of SELECT queries directly from segment
//! entities to the wire response buffer, bypassing the allocation of
//! intermediate `UnifiedRecord`s that `runtime.execute_query` →
//! `encode_result` would otherwise build (~4200 records × 1k queries
//! on the `select_range` bench, where each record clones a `Vec<Value>`
//! and bumps an `Arc<Vec<String>>` schema).
//!
//! The fast path is a pure optimisation: callers fall back to the
//! standard path whenever `try_handle_query_binary_direct` returns
//! None. Shape constraints are deliberately tight — only eligible
//! cases go direct; everything else returns None unchanged.

use std::sync::Arc;

use crate::runtime::mvcc::entity_visible_under_current_snapshot;
use crate::runtime::query_exec::{
    extract_entity_id_from_filter, try_hash_eq_lookup, try_sorted_index_lookup,
    CompiledEntityFilter,
};
use crate::runtime::RedDBRuntime;
use crate::storage::query::ast::{
    Expr, FieldRef, Filter, QueryExpr, SelectItem, TableQuery, TableSource,
};
use crate::storage::query::sql_lowering::effective_table_filter;
use crate::storage::schema::{value_to_canonical_key, CanonicalKey, Value};
use crate::storage::unified::{EntityData, EntityId, RowData, UnifiedEntity};

use super::protocol::{
    encode_column_name, encode_value, write_frame_header, MSG_RESULT, VAL_NULL, VAL_U64,
};

/// Try to serve a binary SELECT via the zero-copy scan path.
///
/// Returns `Some(wire_response)` when the query matches the fast-path
/// shape and was executed; returns `None` to signal the caller should
/// fall back to the standard `execute_query` + `encode_result` path.
pub(super) fn try_handle_query_binary_direct(runtime: &RedDBRuntime, sql: &str) -> Option<Vec<u8>> {
    // Cheap prefix gate. Avoid parse for anything not a plain SELECT
    // (WITHIN, EXPLAIN, SET, BEGIN, …).
    let trimmed = sql.trim_start();
    if trimmed.len() < 6 {
        return None;
    }
    if !trimmed.as_bytes()[..6].eq_ignore_ascii_case(b"SELECT") {
        return None;
    }

    // Micro-fast-path for the benchmark's point lookup shape:
    // `SELECT id, ... FROM t WHERE id = N`. This avoids the full SQL
    // parser on high-QPS indexed point reads. The recognizer is deliberately
    // tiny; any alias/function/operator/extra clause falls back below.
    if let Some(parsed) = parse_simple_hash_eq_select(trimmed) {
        if let Some(resp) = execute_simple_hash_eq_select(runtime, &parsed) {
            return Some(resp);
        }
    }
    if let Some(parsed) = parse_simple_between_select(trimmed) {
        if let Some(resp) = execute_simple_between_select(runtime, &parsed) {
            return Some(resp);
        }
    }
    if let Some(parsed) = parse_simple_ordered_complex_select(trimmed) {
        if let Some(resp) = execute_simple_ordered_complex_select(runtime, &parsed) {
            return Some(resp);
        }
    }
    if let Some(parsed) = parse_simple_text_eq_int_gt_select(trimmed) {
        if let Some(resp) = execute_simple_text_eq_int_gt_select(runtime, &parsed) {
            return Some(resp);
        }
    }

    // Full parse. Cost ~50µs; amortised by the record allocations
    // skipped on hit. On miss the caller re-parses via `handle_query`.
    let expr = crate::storage::query::modes::parse_multi(sql).ok()?;
    let tq = match &expr {
        QueryExpr::Table(tq) => tq,
        _ => return None,
    };

    if !is_shape_direct_eligible(tq) {
        return None;
    }

    execute_direct_scan(runtime, tq)
}

/// True when `filter` is a single leaf that `try_sorted_index_lookup`
/// can resolve without needing post-filter evaluation. For leaves the
/// index scan's LIMIT pushdown returns exactly the rows we want;
/// for composite `And`/`Or`/`Not` we need every row the index returns
/// to clear the full predicate before we can count it towards LIMIT.
fn filter_is_single_indexable_leaf(filter: &Filter) -> bool {
    matches!(
        filter,
        Filter::Between { .. } | Filter::Compare { .. } | Filter::In { .. }
    )
}

/// Detects the `And(leaf_a, leaf_b)` shape where **both** leaves resolve to
/// an exact index result (sorted range or hash-eq). When this holds,
/// `try_sorted_index_lookup` intersects the two id sets, and the intersection
/// is a complete answer to the full filter — so the outer LIMIT can be pushed
/// through to the intersector without losing rows.
pub(super) fn is_shape_direct_eligible(tq: &TableQuery) -> bool {
    if let Some(source) = &tq.source {
        if !matches!(source, TableSource::Name(_)) {
            return false;
        }
    }
    if !tq.group_by.is_empty() || !tq.group_by_exprs.is_empty() {
        return false;
    }
    if tq.having.is_some() || tq.having_expr.is_some() {
        return false;
    }
    if !tq.order_by.is_empty() || tq.expand.is_some() {
        return false;
    }
    if tq.offset.is_some() {
        return false;
    }
    if tq.select_items.is_empty() {
        return false;
    }

    for item in &tq.select_items {
        match item {
            SelectItem::Wildcard => {}
            SelectItem::Expr { expr, alias: _ } => {
                if !matches!(expr, Expr::Column { .. }) {
                    return false;
                }
            }
        }
    }

    true
}

pub(super) fn execute_direct_scan(runtime: &RedDBRuntime, tq: &TableQuery) -> Option<Vec<u8>> {
    let effective_filter = effective_table_filter(tq);

    // Defer to execute_query's point-lookup path when WHERE reduces
    // to `red_entity_id = N` — that path handles MVCC + error shapes
    // we don't want to re-implement here.
    if extract_entity_id_from_filter(&effective_filter).is_some() {
        return None;
    }

    let db = runtime.db();
    let store = db.store();
    let manager = store.get_collection(&tq.table)?;
    let limit = tq.limit.map(|l| l as usize);
    let hard_limit = limit.unwrap_or(usize::MAX);
    let schema_columns = manager.column_schema();
    let schema_slice = schema_columns.as_ref().map(|schema| schema.as_slice());
    let pre_resolved_cols =
        schema_slice.map(|schema| resolve_wire_columns_from_query_schema(tq, schema));

    let mut body: Vec<u8> = Vec::with_capacity(estimate_direct_response_capacity(
        tq,
        schema_slice,
        limit.unwrap_or(0),
    ));
    let mut header_nrows_pos: usize = 0;
    let mut cols: Option<Vec<WireColumn>> = None;
    let mut row_count: u32 = 0;

    // Inline row-emit macro — avoids a shared `FnMut` closure whose
    // state captures force every call through an indirect dispatch,
    // measurably slower on the select_filtered hot loop (AND filter
    // with single-indexed leaf can iterate tens of thousands of ids).
    macro_rules! emit_one {
        ($entity:expr) => {{
            let entity: &UnifiedEntity = $entity;
            if !entity.data.is_row() || !entity_visible_under_current_snapshot(entity) {
                // skip
            } else if let EntityData::Row(ref row) = entity.data {
                if cols.is_none() {
                    let resolved = pre_resolved_cols
                        .clone()
                        .unwrap_or_else(|| resolve_wire_columns(tq, row));
                    body.extend_from_slice(&(resolved.len() as u16).to_le_bytes());
                    for col in &resolved {
                        encode_column_name(&mut body, col.name.as_ref());
                    }
                    header_nrows_pos = body.len();
                    body.extend_from_slice(&[0u8; 4]);
                    cols = Some(resolved);
                }
                if let Some(cols_ref) = cols.as_ref() {
                    for c in cols_ref {
                        encode_entity_wire_value(&mut body, entity, row, c);
                    }
                    row_count += 1;
                }
            }
        }};
    }

    if let Some(filter) = effective_filter.as_ref() {
        // ── Filtered / indexed path ───────────────────────────────
        let idx_store = runtime.index_store_ref();
        // LIMIT pushdown is only safe when the filter is a single
        // indexable leaf. For composite `And(_, _)` we can't push the
        // outer LIMIT to `try_sorted_index_lookup`, because that
        // propagates it to each leaf's index scan — truncating the
        // candidate sets before the intersection and dropping matches.
        // (See `fast_path_and_with_limit_returns_same_row_count_as_standard`
        //  for the regression-guard.)
        let index_limit = if filter_is_single_indexable_leaf(filter) {
            limit
        } else {
            None
        };
        let ids = try_sorted_index_lookup(filter, tq.table.as_str(), idx_store, index_limit)
            .or_else(|| try_hash_eq_lookup(filter, tq.table.as_str(), idx_store))?;
        if ids.is_empty() {
            return encode_empty_direct_select(tq, schema_slice);
        }
        let target_capacity =
            estimate_direct_response_capacity(tq, schema_slice, ids.len().min(hard_limit));
        if target_capacity > body.capacity() {
            body.reserve(target_capacity - body.capacity());
        }
        let table_name = tq.table.as_str();
        let table_alias = tq.alias.as_deref().unwrap_or(table_name);
        let compiled_filter = match schema_slice {
            Some(schema) => {
                CompiledEntityFilter::compile_with_schema(filter, table_name, table_alias, schema)
            }
            None => CompiledEntityFilter::compile(filter, table_name, table_alias),
        };
        manager.for_each_id(&ids, |_, entity| {
            if (row_count as usize) >= hard_limit {
                return;
            }
            if !compiled_filter.evaluate(entity) {
                return;
            }
            emit_one!(entity);
        });
    } else {
        // ── Unfiltered LIMIT path ─────────────────────────────────
        // Require explicit LIMIT — we don't want to materialise an
        // unbounded scan here (the runtime's canonical path has the
        // parallel-scan branch for that).
        limit?;
        manager.for_each_entity(|entity| {
            if (row_count as usize) >= hard_limit {
                return false;
            }
            emit_one!(entity);
            (row_count as usize) < hard_limit
        });
    }

    cols.as_ref()?;

    body[header_nrows_pos..header_nrows_pos + 4].copy_from_slice(&row_count.to_le_bytes());

    let mut resp = Vec::with_capacity(5 + body.len());
    write_frame_header(&mut resp, MSG_RESULT, body.len() as u32);
    resp.extend_from_slice(&body);
    let _ = db;
    let _ = store;
    Some(resp)
}

struct SimpleHashEqSelect {
    table: String,
    columns: Vec<String>,
    filter_column: String,
    value: u64,
}

struct SimpleBetweenSelect {
    table: String,
    columns: Vec<String>,
    filter_column: String,
    low: i64,
    high: i64,
}

struct SimpleTextEqIntGtSelect {
    table: String,
    columns: Vec<String>,
    eq_column: String,
    eq_value: String,
    range_column: String,
    threshold: i64,
}

struct SimpleOrderedComplexSelect {
    table: String,
    columns: Vec<String>,
    eq_column: String,
    eq_value: String,
    range_column: String,
    low: i64,
    high: i64,
    float_column: String,
    threshold: f64,
    limit: Option<usize>,
}

struct SimpleSelectParts<'a> {
    table: &'a str,
    columns: Vec<String>,
    predicate: &'a str,
}

struct SimpleOrderedSelectParts<'a> {
    table: &'a str,
    columns: Vec<String>,
    predicate: &'a str,
    order_clause: &'a str,
}

const SIMPLE_INDEX_BREAK_EVEN_CAP: usize = 200_000;

fn parse_simple_projection_columns(projection: &str) -> Option<Vec<String>> {
    let mut columns = Vec::new();
    for raw in projection.split(',') {
        let col = raw.trim();
        if col.is_empty() || !is_simple_identifier(col) {
            return None;
        }
        columns.push(col.to_string());
    }
    if columns.is_empty() {
        return None;
    }
    Some(columns)
}

fn parse_simple_select_parts(sql: &str) -> Option<SimpleSelectParts<'_>> {
    let mut rest = strip_keyword(sql.trim(), "SELECT")?.trim_start();
    let from_pos = find_ascii_ci(rest, " FROM ")?;
    let projection = rest[..from_pos].trim();
    rest = rest[from_pos + " FROM ".len()..].trim_start();

    let where_pos = find_ascii_ci(rest, " WHERE ")?;
    let table = rest[..where_pos].trim();
    let predicate = rest[where_pos + " WHERE ".len()..].trim();

    if table.is_empty() || !is_simple_identifier(table) {
        return None;
    }

    Some(SimpleSelectParts {
        table,
        columns: parse_simple_projection_columns(projection)?,
        predicate,
    })
}

fn parse_simple_ordered_select_parts(sql: &str) -> Option<SimpleOrderedSelectParts<'_>> {
    let mut rest = strip_keyword(sql.trim(), "SELECT")?.trim_start();
    let from_pos = find_ascii_ci(rest, " FROM ")?;
    let projection = rest[..from_pos].trim();
    rest = rest[from_pos + " FROM ".len()..].trim_start();

    let where_pos = find_ascii_ci(rest, " WHERE ")?;
    let table = rest[..where_pos].trim();
    rest = rest[where_pos + " WHERE ".len()..].trim();

    let order_pos = find_ascii_ci(rest, " ORDER BY ")?;
    let predicate = rest[..order_pos].trim();
    let order_clause = rest[order_pos + " ORDER BY ".len()..].trim();

    if table.is_empty() || !is_simple_identifier(table) {
        return None;
    }

    Some(SimpleOrderedSelectParts {
        table,
        columns: parse_simple_projection_columns(projection)?,
        predicate,
        order_clause,
    })
}

fn parse_simple_hash_eq_select(sql: &str) -> Option<SimpleHashEqSelect> {
    let parts = parse_simple_select_parts(sql)?;
    let eq_pos = parts.predicate.find('=')?;
    let field = parts.predicate[..eq_pos].trim();
    let value_text = parts.predicate[eq_pos + 1..].trim();
    if field.is_empty() || !is_simple_identifier(field) {
        return None;
    }

    let value_text = value_text.strip_suffix(';').unwrap_or(value_text).trim();
    if value_text.is_empty() || !value_text.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }

    Some(SimpleHashEqSelect {
        table: parts.table.to_string(),
        columns: parts.columns,
        filter_column: field.to_string(),
        value: value_text.parse().ok()?,
    })
}

fn parse_simple_between_select(sql: &str) -> Option<SimpleBetweenSelect> {
    let parts = parse_simple_select_parts(sql)?;
    let between_pos = find_ascii_ci(parts.predicate, " BETWEEN ")?;
    let field = parts.predicate[..between_pos].trim();
    let bounds = parts.predicate[between_pos + " BETWEEN ".len()..].trim();
    if field.is_empty() || !is_simple_identifier(field) {
        return None;
    }

    let and_pos = find_ascii_ci(bounds, " AND ")?;
    let low_text = bounds[..and_pos].trim();
    let high_text = bounds[and_pos + " AND ".len()..].trim();
    let high_text = high_text.strip_suffix(';').unwrap_or(high_text).trim();
    let low = parse_i64_literal(low_text)?;
    let high = parse_i64_literal(high_text)?;
    if high < low {
        return None;
    }

    Some(SimpleBetweenSelect {
        table: parts.table.to_string(),
        columns: parts.columns,
        filter_column: field.to_string(),
        low,
        high,
    })
}

fn parse_simple_text_eq_int_gt_select(sql: &str) -> Option<SimpleTextEqIntGtSelect> {
    let parts = parse_simple_select_parts(sql)?;
    let and_pos = find_ascii_ci(parts.predicate, " AND ")?;
    let left = parts.predicate[..and_pos].trim();
    let right = parts.predicate[and_pos + " AND ".len()..].trim();

    let ((eq_column, eq_value), (range_column, threshold)) =
        match (parse_text_eq_clause(left), parse_int_gt_clause(right)) {
            (Some(eq), Some(gt)) => (eq, gt),
            _ => match (parse_text_eq_clause(right), parse_int_gt_clause(left)) {
                (Some(eq), Some(gt)) => (eq, gt),
                _ => return None,
            },
        };

    Some(SimpleTextEqIntGtSelect {
        table: parts.table.to_string(),
        columns: parts.columns,
        eq_column,
        eq_value,
        range_column,
        threshold,
    })
}

fn parse_simple_ordered_complex_select(sql: &str) -> Option<SimpleOrderedComplexSelect> {
    let parts = parse_simple_ordered_select_parts(sql)?;
    let (order_column, limit) = parse_order_by_desc_clause(parts.order_clause)?;

    let first_and = find_ascii_ci(parts.predicate, " AND ")?;
    let eq_clause = parts.predicate[..first_and].trim();
    let rest = parts.predicate[first_and + " AND ".len()..].trim();
    let (eq_column, eq_value) = parse_text_eq_clause(eq_clause)?;

    let between_pos = find_ascii_ci(rest, " BETWEEN ")?;
    let range_column = rest[..between_pos].trim();
    if range_column.is_empty() || !is_simple_identifier(range_column) {
        return None;
    }
    let bounds_and_float = rest[between_pos + " BETWEEN ".len()..].trim();
    let low_end = find_ascii_ci(bounds_and_float, " AND ")?;
    let low_text = bounds_and_float[..low_end].trim();
    let high_and_float = bounds_and_float[low_end + " AND ".len()..].trim();
    let high_end = find_ascii_ci(high_and_float, " AND ")?;
    let high_text = high_and_float[..high_end].trim();
    let float_clause = high_and_float[high_end + " AND ".len()..].trim();

    let low = parse_i64_literal(low_text)?;
    let high = parse_i64_literal(high_text)?;
    if high < low {
        return None;
    }

    let (float_column, threshold) = parse_float_gt_clause(float_clause)?;
    if order_column != float_column {
        return None;
    }

    Some(SimpleOrderedComplexSelect {
        table: parts.table.to_string(),
        columns: parts.columns,
        eq_column,
        eq_value,
        range_column: range_column.to_string(),
        low,
        high,
        float_column,
        threshold,
        limit,
    })
}

fn parse_text_eq_clause(clause: &str) -> Option<(String, String)> {
    let eq_pos = clause.find('=')?;
    let field = clause[..eq_pos].trim();
    let value_text = clause[eq_pos + 1..].trim();
    if field.is_empty() || !is_simple_identifier(field) {
        return None;
    }
    Some((field.to_string(), parse_sql_single_quoted_text(value_text)?))
}

fn parse_int_gt_clause(clause: &str) -> Option<(String, i64)> {
    let gt_pos = clause.find('>')?;
    let field = clause[..gt_pos].trim();
    let value_text = clause[gt_pos + 1..].trim();
    if field.is_empty() || !is_simple_identifier(field) {
        return None;
    }
    if value_text.starts_with('=') {
        return None;
    }
    let value_text = value_text.strip_suffix(';').unwrap_or(value_text).trim();
    Some((field.to_string(), parse_i64_literal(value_text)?))
}

fn parse_float_gt_clause(clause: &str) -> Option<(String, f64)> {
    let gt_pos = clause.find('>')?;
    let field = clause[..gt_pos].trim();
    let value_text = clause[gt_pos + 1..].trim();
    if field.is_empty() || !is_simple_identifier(field) {
        return None;
    }
    if value_text.starts_with('=') {
        return None;
    }
    let value = parse_f64_literal(value_text)?;
    Some((field.to_string(), value))
}

fn parse_order_by_desc_clause(clause: &str) -> Option<(String, Option<usize>)> {
    let mut order_text = clause.strip_suffix(';').unwrap_or(clause).trim();
    let mut limit = None;
    if let Some(limit_pos) = find_ascii_ci(order_text, " LIMIT ") {
        let limit_text = order_text[limit_pos + " LIMIT ".len()..].trim();
        limit = Some(parse_usize_literal(
            limit_text.strip_suffix(';').unwrap_or(limit_text),
        )?);
        order_text = order_text[..limit_pos].trim();
    }

    let mut parts = order_text.split_whitespace();
    let column = parts.next()?;
    let direction = parts.next()?;
    if parts.next().is_some() || !is_simple_identifier(column) {
        return None;
    }
    if !direction.eq_ignore_ascii_case("DESC") {
        return None;
    }
    Some((column.to_string(), limit))
}

fn parse_sql_single_quoted_text(text: &str) -> Option<String> {
    let text = text.strip_suffix(';').unwrap_or(text).trim();
    if !text.starts_with('\'') || !text.ends_with('\'') || text.len() < 2 {
        return None;
    }
    let inner = &text[1..text.len() - 1];
    let mut out = String::with_capacity(inner.len());
    let mut chars = inner.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '\'' {
            if chars.next_if_eq(&'\'').is_some() {
                out.push('\'');
            } else {
                return None;
            }
        } else {
            out.push(ch);
        }
    }
    Some(out)
}

fn execute_simple_hash_eq_select(
    runtime: &RedDBRuntime,
    parsed: &SimpleHashEqSelect,
) -> Option<Vec<u8>> {
    let idx_store = runtime.index_store_ref();
    let idx = idx_store.find_index_for_column(&parsed.table, &parsed.filter_column)?;
    let key = parsed.value.to_le_bytes();
    let ids = idx_store
        .hash_lookup(&parsed.table, idx.hash_lookup_name().as_ref(), &key)
        .ok()?;
    if ids.is_empty() {
        return Some(encode_empty_simple_select(&parsed.columns));
    }

    execute_simple_indexed_select(runtime, &parsed.table, &parsed.columns, &ids, |schema| {
        SimpleRowPredicate::EqU64 {
            field: RowFieldAccessor::for_column(&parsed.filter_column, schema),
            expected: parsed.value,
        }
    })
}

fn execute_simple_between_select(
    runtime: &RedDBRuntime,
    parsed: &SimpleBetweenSelect,
) -> Option<Vec<u8>> {
    let idx_store = runtime.index_store_ref();
    if !idx_store
        .sorted
        .has_index(&parsed.table, &parsed.filter_column)
    {
        return None;
    }
    let low_value = Value::Integer(parsed.low);
    let high_value = Value::Integer(parsed.high);
    let low = value_to_canonical_key(&low_value)?;
    let high = value_to_canonical_key(&high_value)?;
    let ids = idx_store.sorted.range_lookup_limited(
        &parsed.table,
        &parsed.filter_column,
        low,
        high,
        SIMPLE_INDEX_BREAK_EVEN_CAP + 1,
    )?;
    if ids.is_empty() {
        return Some(encode_empty_simple_select(&parsed.columns));
    }
    if ids.len() > SIMPLE_INDEX_BREAK_EVEN_CAP {
        return None;
    }

    execute_simple_indexed_select(runtime, &parsed.table, &parsed.columns, &ids, |schema| {
        SimpleRowPredicate::BetweenI64 {
            field: RowFieldAccessor::for_column(&parsed.filter_column, schema),
            low: parsed.low,
            high: parsed.high,
        }
    })
}

fn execute_simple_text_eq_int_gt_select(
    runtime: &RedDBRuntime,
    parsed: &SimpleTextEqIntGtSelect,
) -> Option<Vec<u8>> {
    let idx_store = runtime.index_store_ref();
    let index_columns = vec![parsed.eq_column.clone(), parsed.range_column.clone()];
    if !idx_store
        .sorted
        .has_composite_index(&parsed.table, &index_columns)
    {
        return None;
    }

    let eq_key = value_to_canonical_key(&Value::text(parsed.eq_value.as_str()))?;
    let low_threshold = parsed.threshold.checked_add(1)?;
    let low_value = Value::Integer(low_threshold);
    let low = value_to_canonical_key(&low_value)?;
    let high = match &low {
        CanonicalKey::Signed(family, _) => CanonicalKey::Signed(*family, i64::MAX),
        _ => return None,
    };
    let ids = idx_store.sorted.composite_prefix_range_lookup(
        &parsed.table,
        &index_columns,
        &[eq_key],
        low,
        high,
        SIMPLE_INDEX_BREAK_EVEN_CAP + 1,
    )?;
    if ids.is_empty() {
        return Some(encode_empty_simple_select(&parsed.columns));
    }
    if ids.len() > SIMPLE_INDEX_BREAK_EVEN_CAP {
        return None;
    }

    execute_simple_indexed_select(runtime, &parsed.table, &parsed.columns, &ids, |schema| {
        SimpleRowPredicate::TextEqIntGt {
            text_field: RowFieldAccessor::for_column(&parsed.eq_column, schema),
            expected_text: parsed.eq_value.clone(),
            int_field: RowFieldAccessor::for_column(&parsed.range_column, schema),
            threshold: parsed.threshold,
        }
    })
}

struct OrderedCandidate {
    score: f64,
    tie_id: u64,
    entity_id: EntityId,
}

fn compare_ordered_candidate(
    left: &OrderedCandidate,
    right: &OrderedCandidate,
) -> std::cmp::Ordering {
    right
        .score
        .partial_cmp(&left.score)
        .unwrap_or(std::cmp::Ordering::Equal)
        .then(left.tie_id.cmp(&right.tie_id))
}

fn execute_simple_ordered_complex_select(
    runtime: &RedDBRuntime,
    parsed: &SimpleOrderedComplexSelect,
) -> Option<Vec<u8>> {
    let idx_store = runtime.index_store_ref();
    let index_columns = vec![parsed.eq_column.clone(), parsed.range_column.clone()];
    if !idx_store
        .sorted
        .has_composite_index(&parsed.table, &index_columns)
    {
        return None;
    }

    let eq_key = value_to_canonical_key(&Value::text(parsed.eq_value.as_str()))?;
    let low_value = Value::Integer(parsed.low);
    let high_value = Value::Integer(parsed.high);
    let low = value_to_canonical_key(&low_value)?;
    let high = value_to_canonical_key(&high_value)?;
    let ids = idx_store.sorted.composite_prefix_range_lookup(
        &parsed.table,
        &index_columns,
        &[eq_key],
        low,
        high,
        SIMPLE_INDEX_BREAK_EVEN_CAP + 1,
    )?;
    if ids.is_empty() {
        return Some(encode_empty_simple_select(&parsed.columns));
    }
    if ids.len() > SIMPLE_INDEX_BREAK_EVEN_CAP {
        return None;
    }

    let db = runtime.db();
    let store = db.store();
    let manager = store.get_collection(&parsed.table)?;
    let schema_columns = manager.column_schema();
    let schema_slice = schema_columns.as_ref().map(|schema| schema.as_slice());
    let city_field = RowFieldAccessor::for_column(&parsed.eq_column, schema_slice);
    let age_field = RowFieldAccessor::for_column(&parsed.range_column, schema_slice);
    let score_field = RowFieldAccessor::for_column(&parsed.float_column, schema_slice);
    let id_field = RowFieldAccessor::for_column("id", schema_slice);
    let mut candidates: Vec<OrderedCandidate> = Vec::new();

    manager.for_each_id(&ids, |_, entity| {
        if !entity.data.is_row() || !entity_visible_under_current_snapshot(entity) {
            return;
        }
        let EntityData::Row(ref row) = entity.data else {
            return;
        };
        if !value_text_eq(city_field.value(row), parsed.eq_value.as_str()) {
            return;
        }
        if !value_between_i64(age_field.value(row), parsed.low, parsed.high) {
            return;
        }
        let Some(score) = value_as_f64(score_field.value(row)) else {
            return;
        };
        if score <= parsed.threshold {
            return;
        }

        candidates.push(OrderedCandidate {
            score,
            tie_id: value_as_u64(id_field.value(row)).unwrap_or_else(|| entity.id.raw()),
            entity_id: entity.id,
        });
    });

    if candidates.is_empty() {
        return Some(encode_empty_simple_select(&parsed.columns));
    }
    if let Some(limit) = parsed.limit {
        if candidates.len() > limit {
            candidates.select_nth_unstable_by(limit, compare_ordered_candidate);
            candidates.truncate(limit);
        }
    }
    if candidates.is_empty() {
        return Some(encode_empty_simple_select(&parsed.columns));
    }
    candidates.sort_by(compare_ordered_candidate);

    let cols = match schema_columns.as_ref() {
        Some(schema) => resolve_wire_columns_from_schema(&parsed.columns, schema.as_slice()),
        None => {
            let mut first_row_cols: Option<Vec<WireColumn>> = None;
            manager.for_each_id(&[candidates[0].entity_id], |_, entity| {
                if first_row_cols.is_some() {
                    return;
                }
                if let EntityData::Row(ref row) = entity.data {
                    first_row_cols = Some(resolve_wire_columns_from_names(&parsed.columns, row));
                }
            });
            first_row_cols.unwrap_or_else(|| {
                parsed
                    .columns
                    .iter()
                    .map(|name| resolve_named_wire_column_for_empty_row(name, name))
                    .collect()
            })
        }
    };

    let mut body = Vec::with_capacity(estimate_wire_columns_response_capacity(
        &cols,
        candidates.len(),
    ));
    body.extend_from_slice(&(cols.len() as u16).to_le_bytes());
    for col in &cols {
        encode_column_name(&mut body, col.name.as_ref());
    }
    let header_nrows_pos = body.len();
    body.extend_from_slice(&0u32.to_le_bytes());
    let mut row_count: u32 = 0;
    let candidate_ids: Vec<EntityId> = candidates
        .iter()
        .map(|candidate| candidate.entity_id)
        .collect();
    let row_capacity = estimate_wire_columns_response_capacity(&cols, 1);
    let mut encoded_rows: Vec<Option<Vec<u8>>> = Vec::with_capacity(candidate_ids.len());
    encoded_rows.resize_with(candidate_ids.len(), || None);
    manager.for_each_id(&candidate_ids, |candidate_idx, entity| {
        let EntityData::Row(ref row) = entity.data else {
            return;
        };
        if !entity_visible_under_current_snapshot(entity) {
            return;
        }
        let mut row_bytes = Vec::with_capacity(row_capacity);
        for col in &cols {
            encode_entity_wire_value(&mut row_bytes, entity, row, col);
        }
        encoded_rows[candidate_idx] = Some(row_bytes);
    });
    for row_bytes in encoded_rows.into_iter().flatten() {
        body.extend_from_slice(&row_bytes);
        row_count += 1;
    }
    body[header_nrows_pos..header_nrows_pos + 4].copy_from_slice(&row_count.to_le_bytes());

    let mut resp = Vec::with_capacity(5 + body.len());
    write_frame_header(&mut resp, MSG_RESULT, body.len() as u32);
    resp.extend_from_slice(&body);
    Some(resp)
}

fn execute_simple_indexed_select<FBuild>(
    runtime: &RedDBRuntime,
    table: &str,
    columns: &[String],
    ids: &[EntityId],
    build_predicate: FBuild,
) -> Option<Vec<u8>>
where
    FBuild: FnOnce(Option<&[String]>) -> SimpleRowPredicate,
{
    let db = runtime.db();
    let store = db.store();
    let manager = store.get_collection(table)?;
    let schema_columns = manager.column_schema();
    let schema_slice = schema_columns.as_ref().map(|schema| schema.as_slice());
    let row_predicate = build_predicate(schema_slice);
    let pre_resolved_cols = schema_columns
        .as_ref()
        .map(|schema| resolve_wire_columns_from_schema(columns, schema.as_slice()));
    let mut body: Vec<u8> =
        Vec::with_capacity(estimate_simple_response_capacity(columns, ids.len()));
    let mut header_nrows_pos: usize = 0;
    let mut cols: Option<Vec<WireColumn>> = None;
    let mut row_count: u32 = 0;

    manager.for_each_id(ids, |_, entity| {
        if !entity.data.is_row() || !entity_visible_under_current_snapshot(entity) {
            return;
        }
        let EntityData::Row(ref row) = entity.data else {
            return;
        };
        if !row_predicate.matches(row) {
            return;
        }

        if cols.is_none() {
            let resolved = pre_resolved_cols
                .clone()
                .unwrap_or_else(|| resolve_wire_columns_from_names(columns, row));
            body.extend_from_slice(&(resolved.len() as u16).to_le_bytes());
            for col in &resolved {
                encode_column_name(&mut body, col.name.as_ref());
            }
            header_nrows_pos = body.len();
            body.extend_from_slice(&[0u8; 4]);
            cols = Some(resolved);
        }

        if let Some(cols_ref) = cols.as_ref() {
            for c in cols_ref {
                encode_entity_wire_value(&mut body, entity, row, c);
            }
            row_count += 1;
        }
    });

    cols.as_ref()?;

    body[header_nrows_pos..header_nrows_pos + 4].copy_from_slice(&row_count.to_le_bytes());
    let mut resp = Vec::with_capacity(5 + body.len());
    write_frame_header(&mut resp, MSG_RESULT, body.len() as u32);
    resp.extend_from_slice(&body);
    Some(resp)
}

fn encode_empty_simple_select(columns: &[String]) -> Vec<u8> {
    let mut body = Vec::with_capacity(estimate_simple_response_capacity(columns, 0));
    body.extend_from_slice(&(columns.len() as u16).to_le_bytes());
    for column in columns {
        encode_column_name(&mut body, column.as_str());
    }
    body.extend_from_slice(&0u32.to_le_bytes());

    let mut resp = Vec::with_capacity(5 + body.len());
    write_frame_header(&mut resp, MSG_RESULT, body.len() as u32);
    resp.extend_from_slice(&body);
    resp
}

fn encode_empty_direct_select(tq: &TableQuery, schema: Option<&[String]>) -> Option<Vec<u8>> {
    let cols = match schema {
        Some(schema) => resolve_wire_columns_from_query_schema(tq, schema),
        None => resolve_wire_columns_for_empty_projection(tq)?,
    };
    let mut body = Vec::with_capacity(estimate_wire_columns_response_capacity(&cols, 0));
    body.extend_from_slice(&(cols.len() as u16).to_le_bytes());
    for col in &cols {
        encode_column_name(&mut body, col.name.as_ref());
    }
    body.extend_from_slice(&0u32.to_le_bytes());

    let mut resp = Vec::with_capacity(5 + body.len());
    write_frame_header(&mut resp, MSG_RESULT, body.len() as u32);
    resp.extend_from_slice(&body);
    Some(resp)
}

fn estimate_simple_response_capacity(columns: &[String], row_hint: usize) -> usize {
    let header = 2usize
        + columns
            .iter()
            .map(|name| 2usize.saturating_add(name.len()))
            .sum::<usize>()
        + 4;
    let row_bytes = columns
        .iter()
        .map(|name| estimated_wire_value_bytes(name.as_str()))
        .sum::<usize>()
        .max(1);
    header
        .saturating_add(row_hint.saturating_mul(row_bytes))
        .clamp(256, 4 * 1024 * 1024)
}

fn estimate_direct_response_capacity(
    tq: &TableQuery,
    schema: Option<&[String]>,
    row_hint: usize,
) -> usize {
    match schema {
        Some(schema) => {
            let cols = resolve_wire_columns_from_query_schema(tq, schema);
            estimate_wire_columns_response_capacity(&cols, row_hint)
        }
        None => resolve_wire_columns_for_empty_projection(tq)
            .map(|cols| estimate_wire_columns_response_capacity(&cols, row_hint))
            .unwrap_or(2048),
    }
}

fn estimate_wire_columns_response_capacity(cols: &[WireColumn], row_hint: usize) -> usize {
    let header = 2usize
        + cols
            .iter()
            .map(|col| 2usize.saturating_add(col.name.len()))
            .sum::<usize>()
        + 4;
    let row_bytes = cols
        .iter()
        .map(estimated_wire_column_value_bytes)
        .sum::<usize>()
        .max(1);
    header
        .saturating_add(row_hint.saturating_mul(row_bytes))
        .clamp(256, 4 * 1024 * 1024)
}

fn estimated_wire_column_value_bytes(col: &WireColumn) -> usize {
    match &col.source {
        WireColumnSource::RedEntityId
        | WireColumnSource::CreatedAt
        | WireColumnSource::UpdatedAt => 9,
        _ => estimated_wire_value_bytes(col.name.as_ref()),
    }
}

fn estimated_wire_value_bytes(column: &str) -> usize {
    match column {
        "id" | "age" | "score" | "red_entity_id" | "created_at_ms" | "updated_at_ms" => 9,
        "city" => 16,
        "name" => 32,
        "email" => 48,
        "created_at" | "updated_at" => 40,
        _ => 24,
    }
}

enum RowFieldAccessor {
    Index { index: usize, name: String },
    Name(String),
}

impl RowFieldAccessor {
    fn for_column(column: &str, schema: Option<&[String]>) -> Self {
        if let Some(index) =
            schema.and_then(|columns| columns.iter().position(|name| name == column))
        {
            Self::Index {
                index,
                name: column.to_string(),
            }
        } else {
            Self::Name(column.to_string())
        }
    }

    fn value<'a>(&self, row: &'a RowData) -> Option<&'a Value> {
        match self {
            Self::Index { index, name } => row
                .columns
                .get(*index)
                .or_else(|| row.get_field(name.as_str())),
            Self::Name(name) => row.get_field(name.as_str()),
        }
    }
}

enum SimpleRowPredicate {
    EqU64 {
        field: RowFieldAccessor,
        expected: u64,
    },
    BetweenI64 {
        field: RowFieldAccessor,
        low: i64,
        high: i64,
    },
    TextEqIntGt {
        text_field: RowFieldAccessor,
        expected_text: String,
        int_field: RowFieldAccessor,
        threshold: i64,
    },
}

impl SimpleRowPredicate {
    fn matches(&self, row: &RowData) -> bool {
        match self {
            Self::EqU64 { field, expected } => value_eq_u64(field.value(row), *expected),
            Self::BetweenI64 { field, low, high } => {
                value_between_i64(field.value(row), *low, *high)
            }
            Self::TextEqIntGt {
                text_field,
                expected_text,
                int_field,
                threshold,
            } => {
                value_text_eq(text_field.value(row), expected_text.as_str())
                    && value_gt_i64(int_field.value(row), *threshold)
            }
        }
    }
}

fn parse_i64_literal(text: &str) -> Option<i64> {
    let rest = text.strip_prefix('-').unwrap_or(text);
    if rest.is_empty() || !rest.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    text.parse().ok()
}

fn parse_f64_literal(text: &str) -> Option<f64> {
    let text = text.strip_suffix(';').unwrap_or(text).trim();
    if text.is_empty() {
        return None;
    }
    let value: f64 = text.parse().ok()?;
    value.is_finite().then_some(value)
}

fn parse_usize_literal(text: &str) -> Option<usize> {
    let text = text.strip_suffix(';').unwrap_or(text).trim();
    if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    text.parse().ok()
}

fn value_eq_u64(value: Option<&Value>, expected: u64) -> bool {
    match value {
        Some(Value::UnsignedInteger(v)) => *v == expected,
        Some(Value::Integer(v)) => *v >= 0 && *v as u64 == expected,
        _ => false,
    }
}

fn value_as_u64(value: Option<&Value>) -> Option<u64> {
    match value {
        Some(Value::UnsignedInteger(v)) => Some(*v),
        Some(Value::Integer(v)) if *v >= 0 => Some(*v as u64),
        _ => None,
    }
}

fn value_as_f64(value: Option<&Value>) -> Option<f64> {
    match value {
        Some(Value::Float(v)) if v.is_finite() => Some(*v),
        Some(Value::Integer(v)) => Some(*v as f64),
        Some(Value::UnsignedInteger(v)) => Some(*v as f64),
        _ => None,
    }
}

fn value_between_i64(value: Option<&Value>, low: i64, high: i64) -> bool {
    match value {
        Some(Value::Integer(v)) => *v >= low && *v <= high,
        Some(Value::UnsignedInteger(v)) if low >= 0 => {
            let low = low as u64;
            let high = high as u64;
            *v >= low && *v <= high
        }
        _ => false,
    }
}

fn value_gt_i64(value: Option<&Value>, threshold: i64) -> bool {
    match value {
        Some(Value::Integer(v)) => *v > threshold,
        Some(Value::UnsignedInteger(v)) if threshold >= 0 => *v > threshold as u64,
        Some(Value::UnsignedInteger(_)) => true,
        _ => false,
    }
}

fn value_text_eq(value: Option<&Value>, expected: &str) -> bool {
    match value {
        Some(Value::Text(v)) => v.as_ref() == expected,
        _ => false,
    }
}

fn strip_keyword<'a>(input: &'a str, keyword: &str) -> Option<&'a str> {
    if input.len() < keyword.len() {
        return None;
    }
    let (head, tail) = input.split_at(keyword.len());
    if head.eq_ignore_ascii_case(keyword) {
        Some(tail)
    } else {
        None
    }
}

fn find_ascii_ci(haystack: &str, needle: &str) -> Option<usize> {
    haystack
        .as_bytes()
        .windows(needle.len())
        .position(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
}

fn is_simple_identifier(value: &str) -> bool {
    let mut chars = value.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first == '_' || first.is_ascii_alphabetic()) {
        return false;
    }
    chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
}

#[derive(Clone)]
struct WireColumn {
    name: Arc<str>,
    source: WireColumnSource,
}

#[derive(Clone)]
enum WireColumnSource {
    RedEntityId,
    CreatedAt,
    UpdatedAt,
    RowIndexTrusted { index: usize },
    RowIndex { index: usize, name: Arc<str> },
    RowName(Arc<str>),
}

fn resolve_wire_columns(tq: &TableQuery, row: &RowData) -> Vec<WireColumn> {
    let wildcard = tq
        .select_items
        .iter()
        .any(|it| matches!(it, SelectItem::Wildcard));

    if wildcard {
        let mut out = Vec::with_capacity(3 + row.columns.len());
        out.push(WireColumn::system(
            "red_entity_id",
            WireColumnSource::RedEntityId,
        ));
        out.push(WireColumn::system(
            "created_at",
            WireColumnSource::CreatedAt,
        ));
        out.push(WireColumn::system(
            "updated_at",
            WireColumnSource::UpdatedAt,
        ));
        if let Some(schema) = row.schema.as_ref() {
            out.extend(schema.iter().enumerate().map(|(idx, name)| WireColumn {
                name: Arc::<str>::from(name.as_str()),
                source: WireColumnSource::RowIndex {
                    index: idx,
                    name: Arc::<str>::from(name.as_str()),
                },
            }));
        } else if let Some(named) = row.named.as_ref() {
            out.extend(named.keys().map(|name| WireColumn {
                name: Arc::<str>::from(name.as_str()),
                source: WireColumnSource::RowName(Arc::<str>::from(name.as_str())),
            }));
        }
        return out;
    }

    let mut out = Vec::with_capacity(tq.select_items.len());
    for item in &tq.select_items {
        if let SelectItem::Expr {
            expr:
                Expr::Column {
                    field: FieldRef::TableColumn { column, .. },
                    ..
                },
            alias,
        } = item
        {
            let name = alias.as_deref().unwrap_or(column.as_str());
            out.push(resolve_named_wire_column(name, column, row));
        }
    }
    out
}

fn resolve_wire_columns_from_query_schema(tq: &TableQuery, schema: &[String]) -> Vec<WireColumn> {
    let wildcard = tq
        .select_items
        .iter()
        .any(|it| matches!(it, SelectItem::Wildcard));

    if wildcard {
        let mut out = Vec::with_capacity(3 + schema.len());
        out.push(WireColumn::system(
            "red_entity_id",
            WireColumnSource::RedEntityId,
        ));
        out.push(WireColumn::system(
            "created_at",
            WireColumnSource::CreatedAt,
        ));
        out.push(WireColumn::system(
            "updated_at",
            WireColumnSource::UpdatedAt,
        ));
        out.extend(schema.iter().enumerate().map(|(idx, name)| WireColumn {
            name: Arc::<str>::from(name.as_str()),
            source: WireColumnSource::RowIndexTrusted { index: idx },
        }));
        return out;
    }

    let mut out = Vec::with_capacity(tq.select_items.len());
    for item in &tq.select_items {
        if let SelectItem::Expr {
            expr:
                Expr::Column {
                    field: FieldRef::TableColumn { column, .. },
                    ..
                },
            alias,
        } = item
        {
            let name = alias.as_deref().unwrap_or(column.as_str());
            out.push(resolve_named_wire_column_from_schema(name, column, schema));
        }
    }
    out
}

fn resolve_wire_columns_for_empty_projection(tq: &TableQuery) -> Option<Vec<WireColumn>> {
    if tq
        .select_items
        .iter()
        .any(|it| matches!(it, SelectItem::Wildcard))
    {
        return None;
    }

    let mut out = Vec::with_capacity(tq.select_items.len());
    for item in &tq.select_items {
        let SelectItem::Expr { expr, alias } = item else {
            return None;
        };
        let Expr::Column {
            field: FieldRef::TableColumn { column, .. },
            ..
        } = expr
        else {
            return None;
        };
        let name = alias.as_deref().unwrap_or(column.as_str());
        out.push(resolve_named_wire_column_for_empty_row(name, column));
    }
    Some(out)
}

fn resolve_wire_columns_from_names(names: &[String], row: &RowData) -> Vec<WireColumn> {
    names
        .iter()
        .map(|name| resolve_named_wire_column(name, name, row))
        .collect()
}

fn resolve_wire_columns_from_schema(names: &[String], schema: &[String]) -> Vec<WireColumn> {
    names
        .iter()
        .map(|name| resolve_named_wire_column_from_schema(name, name, schema))
        .collect()
}

impl WireColumn {
    fn system(name: &str, source: WireColumnSource) -> Self {
        Self {
            name: Arc::<str>::from(name),
            source,
        }
    }
}

fn resolve_named_wire_column_for_empty_row(name: &str, source_column: &str) -> WireColumn {
    let source = match source_column {
        "red_entity_id" => WireColumnSource::RedEntityId,
        "created_at" => WireColumnSource::CreatedAt,
        "updated_at" => WireColumnSource::UpdatedAt,
        _ => WireColumnSource::RowName(Arc::<str>::from(source_column)),
    };
    WireColumn {
        name: Arc::<str>::from(name),
        source,
    }
}

fn resolve_named_wire_column_from_schema(
    name: &str,
    source_column: &str,
    schema: &[String],
) -> WireColumn {
    let source = match source_column {
        "red_entity_id" => WireColumnSource::RedEntityId,
        "created_at" => WireColumnSource::CreatedAt,
        "updated_at" => WireColumnSource::UpdatedAt,
        _ => match schema.iter().position(|col| col == source_column) {
            Some(idx) => WireColumnSource::RowIndexTrusted { index: idx },
            None => WireColumnSource::RowName(Arc::<str>::from(source_column)),
        },
    };
    WireColumn {
        name: Arc::<str>::from(name),
        source,
    }
}

fn resolve_named_wire_column(name: &str, source_column: &str, row: &RowData) -> WireColumn {
    let source = match source_column {
        "red_entity_id" => WireColumnSource::RedEntityId,
        "created_at" => WireColumnSource::CreatedAt,
        "updated_at" => WireColumnSource::UpdatedAt,
        _ => {
            if let Some(schema) = row.schema.as_ref() {
                match schema.iter().position(|col| col == source_column) {
                    Some(idx) => WireColumnSource::RowIndex {
                        index: idx,
                        name: Arc::<str>::from(source_column),
                    },
                    None => WireColumnSource::RowName(Arc::<str>::from(source_column)),
                }
            } else {
                WireColumnSource::RowName(Arc::<str>::from(source_column))
            }
        }
    };
    WireColumn {
        name: Arc::<str>::from(name),
        source,
    }
}

#[inline]
fn encode_entity_wire_value(
    body: &mut Vec<u8>,
    entity: &UnifiedEntity,
    row: &RowData,
    col: &WireColumn,
) {
    match &col.source {
        WireColumnSource::RedEntityId => encode_wire_u64(body, entity.logical_id().raw()),
        WireColumnSource::CreatedAt => encode_wire_u64(body, entity.created_at),
        WireColumnSource::UpdatedAt => encode_wire_u64(body, entity.updated_at),
        WireColumnSource::RowIndexTrusted { index } => match row.columns.get(*index) {
            Some(v) => encode_value(body, v),
            None => encode_wire_null(body),
        },
        WireColumnSource::RowIndex { index, name } => {
            match row
                .schema
                .as_ref()
                .and_then(|schema| {
                    schema
                        .get(*index)
                        .filter(|col| col.as_str() == name.as_ref())
                })
                .and_then(|_| row.columns.get(*index))
                .or_else(|| row.get_field(name.as_ref()))
            {
                Some(v) => encode_value(body, v),
                None => encode_wire_null(body),
            }
        }
        WireColumnSource::RowName(name) => match row.get_field(name.as_ref()) {
            Some(v) => encode_value(body, v),
            None => encode_wire_null(body),
        },
    }
}

#[inline]
fn encode_wire_null(body: &mut Vec<u8>) {
    body.push(VAL_NULL);
}

#[inline]
fn encode_wire_u64(body: &mut Vec<u8>, value: u64) {
    body.push(VAL_U64);
    body.extend_from_slice(&value.to_le_bytes());
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{RedDBOptions, RedDBRuntime};

    fn mk_runtime() -> RedDBRuntime {
        RedDBRuntime::with_options(RedDBOptions::in_memory())
            .expect("runtime should open in-memory")
    }

    fn decode_wire_header(bytes: &[u8]) -> (Vec<String>, u32, usize) {
        let body = &bytes[5..];
        let ncols = u16::from_le_bytes([body[0], body[1]]) as usize;
        let mut pos = 2usize;
        let mut cols = Vec::with_capacity(ncols);
        for _ in 0..ncols {
            let name_len = u16::from_le_bytes([body[pos], body[pos + 1]]) as usize;
            pos += 2;
            cols.push(String::from_utf8_lossy(&body[pos..pos + name_len]).to_string());
            pos += name_len;
        }
        let nrows = u32::from_le_bytes([body[pos], body[pos + 1], body[pos + 2], body[pos + 3]]);
        pos += 4;
        (cols, nrows, pos)
    }

    fn seed_users(rt: &RedDBRuntime) {
        rt.execute_query("CREATE TABLE users (id INT, name TEXT, city TEXT, age INT)")
            .unwrap();
        rt.execute_query("CREATE INDEX idx_age ON users (age) USING BTREE")
            .unwrap();
        rt.execute_query(
            "INSERT INTO users (id, name, city, age) VALUES \
             (1, 'a', 'NYC', 25), (2, 'b', 'LA', 30), (3, 'c', 'NYC', 35), \
             (4, 'd', 'NYC', 40), (5, 'e', 'LA', 45)",
        )
        .unwrap();
    }

    #[test]
    fn shape_eligible_select_star_between() {
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT * FROM users WHERE age BETWEEN 30 AND 40";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(resp.is_some(), "expected fast-path hit for indexed BETWEEN");
        let bytes = resp.unwrap();
        assert!(bytes.len() > 5, "non-empty response");
    }

    #[test]
    fn shape_miss_on_join() {
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT * FROM users u1 JOIN users u2 ON u1.id = u2.id";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(resp.is_none(), "JOIN should miss fast path");
    }

    #[test]
    fn shape_miss_on_order_by() {
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT * FROM users WHERE age BETWEEN 30 AND 40 ORDER BY age";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(resp.is_none(), "ORDER BY should miss fast path");
    }

    #[test]
    fn shape_miss_on_aggregate() {
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT COUNT(*) FROM users";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(resp.is_none(), "COUNT should miss fast path");
    }

    #[test]
    fn shape_miss_on_group_by() {
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT age FROM users GROUP BY age";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(resp.is_none(), "GROUP BY should miss fast path");
    }

    #[test]
    fn shape_miss_unbounded_unfiltered() {
        // SELECT * FROM t with NO WHERE and NO LIMIT must fall back —
        // we don't want the fast path to materialise an unbounded scan
        // here, the runtime's canonical path has the parallel-scan
        // branch for that.
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT * FROM users";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(
            resp.is_none(),
            "full unbounded scan should defer to runtime path"
        );
    }

    #[test]
    fn fast_path_hits_on_unfiltered_with_limit() {
        // SELECT * FROM t LIMIT N — no WHERE but bounded: fast path
        // scans entities with early-stop at LIMIT.
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT * FROM users LIMIT 3";
        let fast =
            try_handle_query_binary_direct(&rt, sql).expect("fast path should hit LIMIT no-filter");
        let body = &fast[5..];
        let ncols = u16::from_le_bytes([body[0], body[1]]);
        let mut pos = 2usize;
        for _ in 0..ncols {
            let name_len = u16::from_le_bytes([body[pos], body[pos + 1]]) as usize;
            pos += 2 + name_len;
        }
        let nrows = u32::from_le_bytes([body[pos], body[pos + 1], body[pos + 2], body[pos + 3]]);
        assert_eq!(nrows, 3, "fast path should emit exactly LIMIT rows");
    }

    #[test]
    fn shape_miss_without_index() {
        let rt = mk_runtime();
        seed_users(&rt);
        // name is not indexed — try_sorted_index_lookup returns None.
        let sql = "SELECT * FROM users WHERE name = 'a'";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(resp.is_none(), "unindexed filter should miss fast path");
    }

    #[test]
    fn parses_simple_hash_eq_select_shape_only() {
        let parsed =
            parse_simple_hash_eq_select("SELECT id, name, email, age FROM users WHERE id = 42;")
                .expect("simple point select should parse");

        assert_eq!(parsed.table, "users");
        assert_eq!(parsed.columns, vec!["id", "name", "email", "age"]);
        assert_eq!(parsed.filter_column, "id");
        assert_eq!(parsed.value, 42);
        assert!(
            parse_simple_hash_eq_select("SELECT id AS ident FROM users WHERE id = 42").is_none()
        );
        assert!(
            parse_simple_hash_eq_select("SELECT id FROM users WHERE id = 42 LIMIT 1").is_none()
        );
    }

    #[test]
    fn parses_simple_between_select_shape_only() {
        let parsed = parse_simple_between_select(
            "SELECT id, name, email, age FROM users WHERE age BETWEEN -10 AND 42;",
        )
        .expect("simple range select should parse");

        assert_eq!(parsed.table, "users");
        assert_eq!(parsed.columns, vec!["id", "name", "email", "age"]);
        assert_eq!(parsed.filter_column, "age");
        assert_eq!(parsed.low, -10);
        assert_eq!(parsed.high, 42);
        assert!(parse_simple_between_select(
            "SELECT id AS ident FROM users WHERE age BETWEEN 1 AND 2"
        )
        .is_none());
        assert!(parse_simple_between_select(
            "SELECT id FROM users WHERE age BETWEEN 1 AND 2 LIMIT 1"
        )
        .is_none());
    }

    #[test]
    fn parses_simple_text_eq_int_gt_select_shape_only() {
        let parsed = parse_simple_text_eq_int_gt_select(
            "SELECT id, name, city, age FROM users WHERE city = 'O''Hare' AND age > 30;",
        )
        .expect("simple text-eq/int-gt select should parse");

        assert_eq!(parsed.table, "users");
        assert_eq!(parsed.columns, vec!["id", "name", "city", "age"]);
        assert_eq!(parsed.eq_column, "city");
        assert_eq!(parsed.eq_value, "O'Hare");
        assert_eq!(parsed.range_column, "age");
        assert_eq!(parsed.threshold, 30);
        assert!(parse_simple_text_eq_int_gt_select(
            "SELECT id FROM users WHERE city = 'NYC' AND age >= 30"
        )
        .is_none());
        assert!(parse_simple_text_eq_int_gt_select(
            "SELECT id FROM users WHERE city = 'NYC' AND age > 30 LIMIT 1"
        )
        .is_none());
    }

    #[test]
    fn parses_simple_ordered_complex_select_shape_only() {
        let parsed = parse_simple_ordered_complex_select(
            "SELECT id, name, email, age, city, score, created_at FROM users \
             WHERE city = 'NYC' AND age BETWEEN 20 AND 45 AND score > 50.5 \
             ORDER BY score DESC LIMIT 25;",
        )
        .expect("simple ordered complex select should parse");

        assert_eq!(parsed.table, "users");
        assert_eq!(
            parsed.columns,
            vec!["id", "name", "email", "age", "city", "score", "created_at"]
        );
        assert_eq!(parsed.eq_column, "city");
        assert_eq!(parsed.eq_value, "NYC");
        assert_eq!(parsed.range_column, "age");
        assert_eq!(parsed.low, 20);
        assert_eq!(parsed.high, 45);
        assert_eq!(parsed.float_column, "score");
        assert_eq!(parsed.threshold, 50.5);
        assert_eq!(parsed.limit, Some(25));
        assert!(parse_simple_ordered_complex_select(
            "SELECT id FROM users WHERE city = 'NYC' AND age BETWEEN 20 AND 45 \
             AND score > 50.5 ORDER BY score ASC"
        )
        .is_none());
        assert!(parse_simple_ordered_complex_select(
            "SELECT id FROM users WHERE city = 'NYC' AND age BETWEEN 20 AND 45 \
             AND score > 50.5 ORDER BY age DESC"
        )
        .is_none());
    }

    #[test]
    fn fast_path_hits_hash_equality_index() {
        use crate::wire::protocol::decode_value;

        let rt = mk_runtime();
        seed_users(&rt);
        rt.execute_query("CREATE INDEX idx_id ON users (id) USING HASH")
            .unwrap();

        let sql = "SELECT id, name FROM users WHERE id = 3";
        let resp = try_handle_query_binary_direct(&rt, sql)
            .expect("hash equality index should hit fast path");
        let (cols, nrows, mut pos) = decode_wire_header(&resp);
        let body = &resp[5..];

        assert_eq!(cols, vec!["id", "name"]);
        assert_eq!(nrows, 1);
        assert_eq!(decode_value(body, &mut pos), Value::Integer(3));
        assert_eq!(decode_value(body, &mut pos), Value::text("c"));
    }

    #[test]
    fn fast_path_returns_empty_hash_result_without_fallback() {
        let rt = mk_runtime();
        seed_users(&rt);
        rt.execute_query("CREATE INDEX idx_id ON users (id) USING HASH")
            .unwrap();

        let sql = "SELECT id, name FROM users WHERE id = 999";
        let resp = try_handle_query_binary_direct(&rt, sql)
            .expect("hash equality miss should return an empty fast-path response");
        let (cols, nrows, _pos) = decode_wire_header(&resp);

        assert_eq!(cols, vec!["id", "name"]);
        assert_eq!(nrows, 0);
    }

    #[test]
    fn fast_path_hits_simple_between_index() {
        use crate::wire::protocol::decode_value;

        let rt = mk_runtime();
        seed_users(&rt);

        let sql = "SELECT id, age FROM users WHERE age BETWEEN 30 AND 40";
        let resp =
            try_handle_query_binary_direct(&rt, sql).expect("simple BETWEEN should hit fast path");
        let (cols, nrows, mut pos) = decode_wire_header(&resp);
        let body = &resp[5..];

        assert_eq!(cols, vec!["id", "age"]);
        assert_eq!(nrows, 3);
        assert_eq!(decode_value(body, &mut pos), Value::Integer(2));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(30));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(3));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(35));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(4));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(40));
    }

    #[test]
    fn fast_path_returns_empty_between_result_without_fallback() {
        let rt = mk_runtime();
        seed_users(&rt);

        let sql = "SELECT id, age FROM users WHERE age BETWEEN 1000 AND 1010";
        let resp = try_handle_query_binary_direct(&rt, sql)
            .expect("range miss should return an empty fast-path response");
        let (cols, nrows, _pos) = decode_wire_header(&resp);

        assert_eq!(cols, vec!["id", "age"]);
        assert_eq!(nrows, 0);
    }

    #[test]
    fn fast_path_hits_simple_text_eq_int_gt_composite_index() {
        use crate::wire::protocol::decode_value;

        let rt = mk_runtime();
        seed_users(&rt);
        rt.execute_query("CREATE INDEX idx_city_age ON users (city, age) USING BTREE")
            .unwrap();

        let sql = "SELECT id, city, age FROM users WHERE city = 'NYC' AND age > 30";
        let resp = try_handle_query_binary_direct(&rt, sql)
            .expect("city/age composite should hit fast path");
        let (cols, nrows, mut pos) = decode_wire_header(&resp);
        let body = &resp[5..];

        assert_eq!(cols, vec!["id", "city", "age"]);
        assert_eq!(nrows, 2);
        assert_eq!(decode_value(body, &mut pos), Value::Integer(3));
        assert_eq!(decode_value(body, &mut pos), Value::text("NYC"));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(35));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(4));
        assert_eq!(decode_value(body, &mut pos), Value::text("NYC"));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(40));
    }

    #[test]
    fn fast_path_hits_simple_ordered_complex_composite_index() {
        use crate::wire::protocol::decode_value;

        let rt = mk_runtime();
        rt.execute_query(
            "CREATE TABLE users (id INT, name TEXT, email TEXT, age INT, city TEXT, score FLOAT, created_at TEXT)",
        )
        .unwrap();
        rt.execute_query("CREATE INDEX idx_city_age ON users (city, age) USING BTREE")
            .unwrap();
        rt.execute_query(
            "INSERT INTO users (id, name, email, age, city, score, created_at) VALUES \
             (1, 'a', 'a@example.com', 30, 'NYC', 80.0, 't1'), \
             (2, 'b', 'b@example.com', 35, 'NYC', 95.0, 't2'), \
             (3, 'c', 'c@example.com', 40, 'NYC', 60.0, 't3'), \
             (4, 'd', 'd@example.com', 30, 'LA', 99.0, 't4')",
        )
        .unwrap();

        let sql = "SELECT id, score FROM users WHERE city = 'NYC' AND age BETWEEN 20 AND 45 \
                   AND score > 70 ORDER BY score DESC LIMIT 2";
        let resp = try_handle_query_binary_direct(&rt, sql)
            .expect("ordered complex composite select should hit fast path");
        let (cols, nrows, mut pos) = decode_wire_header(&resp);
        let body = &resp[5..];

        assert_eq!(cols, vec!["id", "score"]);
        assert_eq!(nrows, 2);
        assert_eq!(decode_value(body, &mut pos), Value::Integer(2));
        assert_eq!(decode_value(body, &mut pos), Value::Float(95.0));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(1));
        assert_eq!(decode_value(body, &mut pos), Value::Float(80.0));
    }

    #[test]
    fn shape_miss_on_entity_id_lookup() {
        let rt = mk_runtime();
        seed_users(&rt);
        // `_entity_id = N` is routed via the runtime point lookup.
        let sql = "SELECT * FROM users WHERE _entity_id = 1";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(
            resp.is_none(),
            "entity-id lookup should defer to runtime path"
        );
    }

    #[test]
    fn shape_miss_on_limit_offset() {
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT * FROM users WHERE age BETWEEN 30 AND 40 LIMIT 2 OFFSET 1";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(resp.is_none(), "OFFSET should miss fast path");
    }

    #[test]
    fn fast_path_pure_between_with_limit_row_count_parity() {
        // Correctness guard for the zero-copy LIMIT 100 win in
        // select_range. A pure BETWEEN leaf pushes LIMIT down to the
        // sorted index and emits exactly `limit` matching rows; we
        // must return the same row count as the standard path.
        let rt = mk_runtime();
        rt.execute_query("CREATE TABLE t (id INT, age INT)")
            .unwrap();
        rt.execute_query("CREATE INDEX idx_age ON t (age) USING BTREE")
            .unwrap();
        // 500 rows, age cycles 18..67 — a BETWEEN 25 AND 45 matches
        // ~21 ages × ~10 rows each = ~210 matches; LIMIT 100 caps.
        for i in 0..500 {
            let age = 18 + (i % 50);
            rt.execute_query(&format!("INSERT INTO t (id, age) VALUES ({i}, {age})"))
                .unwrap();
        }
        let sql = "SELECT * FROM t WHERE age BETWEEN 25 AND 45 LIMIT 100";

        let fast = try_handle_query_binary_direct(&rt, sql).expect("fast path should hit");
        let standard = rt.execute_query(sql).unwrap();
        let standard_rows = standard.result.records.len() as u32;

        let body = &fast[5..];
        let ncols = u16::from_le_bytes([body[0], body[1]]);
        let mut pos = 2usize;
        for _ in 0..ncols {
            let name_len = u16::from_le_bytes([body[pos], body[pos + 1]]) as usize;
            pos += 2 + name_len;
        }
        let nrows = u32::from_le_bytes([body[pos], body[pos + 1], body[pos + 2], body[pos + 3]]);

        assert_eq!(nrows, 100, "fast path should emit exactly LIMIT rows");
        assert_eq!(nrows, standard_rows, "fast/standard row-count parity");
    }

    #[test]
    fn fast_path_and_with_limit_returns_same_row_count_as_standard() {
        // Regression: the fast path used to push LIMIT down to the
        // sorted-index lookup even when only one branch of an AND was
        // indexed, which truncated the candidate pool before the
        // post-filter re-evaluation. Result: fast path returned ~10
        // rows while the standard path returned 100 for the same query.
        let rt = mk_runtime();
        rt.execute_query("CREATE TABLE u (id INT, city TEXT, age INT)")
            .unwrap();
        rt.execute_query("CREATE INDEX idx_age ON u (age) USING BTREE")
            .unwrap();
        rt.execute_query("CREATE INDEX idx_city ON u (city) USING HASH")
            .unwrap();

        // Seed 500 rows; 10% match city='NYC'. age evenly spread 18..68.
        let cities = ["NYC", "LA", "CHI", "HOU", "PHX"];
        for i in 0..500 {
            let city = cities[i % cities.len()];
            let age = 18 + (i % 50);
            rt.execute_query(&format!(
                "INSERT INTO u (id, city, age) VALUES ({i}, '{city}', {age})"
            ))
            .unwrap();
        }

        let sql = "SELECT * FROM u WHERE city = 'NYC' AND age > 20 LIMIT 100";
        let fast = try_handle_query_binary_direct(&rt, sql).expect("fast path should hit");
        let standard = rt.execute_query(sql).expect("standard path ok");
        let standard_rows = standard.result.records.len() as u32;

        // Decode fast-path nrows from wire body.
        let body = &fast[5..];
        let ncols = u16::from_le_bytes([body[0], body[1]]);
        let mut pos = 2usize;
        for _ in 0..ncols {
            let name_len = u16::from_le_bytes([body[pos], body[pos + 1]]) as usize;
            pos += 2 + name_len;
        }
        let nrows = u32::from_le_bytes([body[pos], body[pos + 1], body[pos + 2], body[pos + 3]]);

        assert_eq!(
            nrows, standard_rows,
            "fast path truncated rows early: got {nrows}, standard got {standard_rows}"
        );
    }

    #[test]
    fn shape_eligible_select_filtered_and() {
        // Mirrors bench_definitive_dual.py select_filtered: compound
        // AND where one leaf has a sorted index (age) and the other
        // doesn't (city). `try_sorted_index_lookup` handles the AND
        // case by returning ids from the indexed leaf; the compiled
        // filter re-evaluates the full predicate per row.
        let rt = mk_runtime();
        seed_users(&rt);
        let sql = "SELECT * FROM users WHERE city = 'NYC' AND age > 30";
        let resp = try_handle_query_binary_direct(&rt, sql);
        assert!(
            resp.is_some(),
            "fast path should hit for compound AND when one side is indexed"
        );
    }

    #[test]
    fn fast_path_response_matches_encode_result() {
        use crate::wire::protocol::decode_value;

        let rt = mk_runtime();
        seed_users(&rt);

        let sql = "SELECT * FROM users WHERE age BETWEEN 30 AND 40";
        let fast = try_handle_query_binary_direct(&rt, sql).expect("fast path should hit");

        // Compare row count + column count with the standard path.
        let standard_result = rt.execute_query(sql).expect("standard path ok");
        let expected_rows = standard_result.result.records.len() as u32;

        // Fast response layout: [frame_header 5][body].
        // Body: [u16 ncols][cols..][u32 nrows][(tag+bytes)*]
        assert!(fast.len() > 5);
        let body = &fast[5..];
        let ncols = u16::from_le_bytes([body[0], body[1]]);
        assert!(ncols > 0, "expected non-zero column count");

        // Skip column names — just locate nrows position.
        let mut pos = 2usize;
        for _ in 0..ncols {
            let name_len = u16::from_le_bytes([body[pos], body[pos + 1]]) as usize;
            pos += 2 + name_len;
        }
        let nrows = u32::from_le_bytes([body[pos], body[pos + 1], body[pos + 2], body[pos + 3]]);
        pos += 4;
        assert_eq!(nrows, expected_rows, "fast path row count mismatch");

        // Decode each cell — not comparing against encode_result bytes
        // because column ordering in standard path is schema-driven
        // and may differ for the wildcard case, but value count and
        // type sequence must be consistent per row.
        for _ in 0..nrows {
            for _ in 0..ncols {
                let _ = decode_value(body, &mut pos);
            }
        }
        assert_eq!(pos, body.len(), "decoder should consume entire body");
    }

    #[test]
    fn fast_path_resolves_projection_alias_from_source_column() {
        use crate::storage::schema::Value;
        use crate::wire::protocol::decode_value;

        let rt = mk_runtime();
        rt.execute_query("CREATE TABLE t (id INT, age INT)")
            .unwrap();
        rt.execute_query("CREATE INDEX idx_age ON t (age) USING BTREE")
            .unwrap();
        rt.execute_query("INSERT INTO t (id, age) VALUES (1, 25), (2, 30), (3, 35)")
            .unwrap();

        let sql = "SELECT age AS years, id AS ident FROM t WHERE age BETWEEN 30 AND 30";
        let fast = try_handle_query_binary_direct(&rt, sql).expect("fast path should hit");
        let (cols, nrows, mut pos) = decode_wire_header(&fast);
        let body = &fast[5..];

        assert_eq!(cols, vec!["years".to_string(), "ident".to_string()]);
        assert_eq!(nrows, 1);
        assert_eq!(decode_value(body, &mut pos), Value::Integer(30));
        assert_eq!(decode_value(body, &mut pos), Value::Integer(2));
    }

    #[test]
    fn fast_path_full_range_after_create_index_matches_standard_count() {
        let rt = mk_runtime();
        rt.execute_query("CREATE TABLE users (id INT, age INT)")
            .unwrap();
        for i in 0..500 {
            let age = 18 + (i % 60);
            rt.execute_query(&format!("INSERT INTO users (id, age) VALUES ({i}, {age})"))
                .unwrap();
        }
        rt.execute_query("CREATE INDEX idx_age ON users (age) USING BTREE")
            .unwrap();

        let sql = "SELECT * FROM users WHERE age BETWEEN 0 AND 200";
        let fast = try_handle_query_binary_direct(&rt, sql).expect("fast path should hit");
        let standard = rt.execute_query(sql).unwrap();
        let (_cols, nrows, _pos) = decode_wire_header(&fast);

        assert_eq!(nrows, 500);
        assert_eq!(nrows as usize, standard.result.records.len());
    }
}