ic-db 0.27.7

Experimental embedded Internet Computer database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
//! Bounded fluent traversal. Typed result construction stays outside shared execution.

mod aggregate;
mod distinct;
mod order;
mod probe;
mod range;
mod select;
mod sort;
pub use select::{Column, SelectColumns, SelectedQuery, Selection};

pub use aggregate::{
    Aggregate, GroupCount, GroupOrder, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue,
    SummaryMeasure,
    jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
};

use super::{
    Database, ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, Map, prefix, read_index_owner,
    validate_index_entry,
};
use crate::{
    Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
    codec::Decoder, key, named_schema::TypeGraph, primary::RowKey,
};
use ic_storage::Memory;
use sha2::{Digest, Sha256};
use std::{
    cell::{Ref, RefCell},
    marker::PhantomData,
    ops::Deref,
    rc::Rc,
};

const MAX_TERMS: usize = 8;
const MAX_WORK: usize = 512;
const MAX_OUTPUT: usize = 128 * 1024;
const MAX_COMPARISON_KEY: usize = 4096;
const MAX_DISTINCT_VALUES: usize = 32;
const MAX_STATE_BYTES: usize = 128 * 1024;

/// Direction of one field in an explicit result order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SortDirection {
    /// Smaller values first; absence precedes present values.
    Ascending,
    /// Larger values first; absence follows present values.
    Descending,
}

/// Exact comparison. Equality distinguishes absent values; ranges and pattern matches require presence.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Comparison {
    /// Equal, including two absent values.
    Eq = 0,
    /// Not equal, including absent versus present.
    Ne = 1,
    /// Present and less than the present operand.
    Lt = 2,
    /// Present and less than or equal to the present operand.
    Le = 3,
    /// Present and greater than the present operand.
    Gt = 4,
    /// Present and greater than or equal to the present operand.
    Ge = 5,
    /// Present Text or Blob starts with an exact operand of the same type.
    /// Text uses UTF-8 bytes without normalization; Blob uses raw bytes.
    /// Empty prefixes match all present values, including empty values; other types refuse.
    StartsWith = 6,
    /// Present Text or Blob ends with an exact operand of the same type.
    /// Empty suffixes match all present values; text is not normalized.
    EndsWith = 7,
    /// A present list or set contains an equal scalar member, or a present Text
    /// or Blob contains the exact byte sequence of the same type.
    /// Empty substring needles match every present Text/Blob. Text uses UTF-8 without normalization.
    Contains = 8,
}

impl Comparison {
    fn supports_record_member(self) -> bool {
        self.is_relational() || matches!(self, Self::StartsWith | Self::EndsWith)
    }

    fn is_relational(self) -> bool {
        matches!(
            self,
            Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
        )
    }

    fn supports_scalar(self, field: FieldType) -> bool {
        self.is_relational()
            || matches!(
                key::operand_type(field),
                FieldType::Text { .. } | FieldType::Blob { .. }
            )
    }

    fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
        value.admit(field, optional)?;
        if !self.supports_scalar(field) {
            return Err(Error::InvalidQuery);
        }
        if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
            return Err(Error::InvalidOperand);
        }

        Ok(())
    }

    fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
        if actual.is_none() {
            return self.accepts_absent(operand.is_none());
        }

        match self {
            Self::Eq => actual == operand,
            Self::Ne => actual != operand,
            Self::StartsWith | Self::EndsWith | Self::Contains => {
                // Compare escaped content, never the presence byte or terminator.
                // In particular, optional empty text must not match suffix U+0001.
                fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
                    crate::key::bytes_prefix(key.get(usize::from(optional)..)?)
                }

                actual
                    .and_then(|key| content(key, optional))
                    .zip(operand.and_then(|key| content(key, optional)))
                    .is_some_and(|(actual, operand)| match self {
                        // Prefixes start at a component boundary: escaping each
                        // byte preserves prefix identity for Text and Blob alike.
                        Self::StartsWith => actual.starts_with(operand),
                        // A suffix starting after 00 starts inside an escaped zero
                        // (00 FF), not at a raw-byte boundary. This matters for Blob
                        // operands beginning FF; valid UTF-8 cannot begin there.
                        Self::EndsWith => actual
                            .strip_suffix(operand)
                            .is_some_and(|prefix| prefix.last() != Some(&0)),
                        _ => contains_component(actual, operand),
                    })
            }
            _ if actual.is_none() || operand.is_none() => false,
            Self::Lt => actual < operand,
            Self::Le => actual <= operand,
            Self::Gt => actual > operand,
            Self::Ge => actual >= operand,
        }
    }

    // Residual predicates have typed operands. Only non-byte ordering needs an encoded key.
    fn accepts_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
        match self {
            Self::Eq => Some(equal_values(left, right)),
            Self::Ne => Some(!equal_values(left, right)),
            _ => Some(self.accepts_bytes(scalar_bytes(left)?, scalar_bytes(right)?)),
        }
    }

    // Planning compares admitted literals with the same absence and key order as traversal.
    fn accepts_fixed_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
        if left == IndexValue::Absent || right == IndexValue::Absent {
            return Some(self.accepts_absent(left == right));
        }
        if let Some(result) = self.accepts_values(left, right) {
            return Some(result);
        }
        match self {
            Comparison::Lt | Comparison::Le | Comparison::Gt | Comparison::Ge => {
                // Other admitted scalars use the declared component order.
                let mut encoded = Vec::new();
                left.append_component(false, &mut encoded);
                let split = encoded.len();
                right.append_component(false, &mut encoded);
                let (left, right) = encoded.split_at(split);

                Some(self.accepts(Some(left), Some(right), false))
            }
            _ => None,
        }
    }

    // Text and Blob operands borrowed from rows or fixed query values are already unframed.
    fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
        match self {
            Self::StartsWith => actual.starts_with(operand),
            Self::EndsWith => actual.ends_with(operand),
            Self::Contains => memchr::memmem::find(actual, operand).is_some(),
            _ => self.accepts(Some(actual), Some(operand), false),
        }
    }

    fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
        let encoded = actual.map(u32::to_be_bytes);

        self.accepts(
            encoded.as_ref().map(|v| v.as_slice()),
            Some(&threshold.to_be_bytes()),
            false,
        )
    }

    // These byte-length predicates admit exactly one present scalar value.
    fn empty_length_value(self, threshold: u32, field: FieldType) -> Option<IndexValue<'static>> {
        if !matches!((self, threshold), (Self::Eq | Self::Le, 0) | (Self::Lt, 1)) {
            return None;
        }
        match key::operand_type(field) {
            FieldType::Text { .. } => Some(IndexValue::Text("")),
            FieldType::Blob { .. } => Some(IndexValue::Blob(&[])),
            _ => None,
        }
    }

    // A result is uniform only when every integer in the inclusive interval agrees.
    fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
        match self {
            Self::Eq | Self::Ne if min == max || n < min || n > max => {
                Some(self.accepts_length(Some(min), n))
            }
            Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
            Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
            _ => None,
        }
    }

    // One side is absent. Equality/inequality are symmetric; execution,
    // presence-only filters and sparse membership share this rule.
    fn accepts_absent(self, other_absent: bool) -> bool {
        match self {
            Self::Eq => other_absent,
            Self::Ne => !other_absent,
            _ => false,
        }
    }
}

// Both slices are validated component contents with presence/terminator removed.
fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
    let Some(start) = memchr::memmem::find(actual, needle) else {
        return false;
    };
    if start == 0 || actual[start - 1] != 0 {
        return true;
    }
    // Only a Blob needle starting FF can match inside an escaped zero (00 FF).
    // A valid overlapping match may follow. One raw search avoids repeatedly
    // scanning long prefixes. Each temporary is bounded by the row byte limit.
    fn raw(content: &[u8]) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
        let mut encoded = content.iter();
        while let Some(&byte) = encoded.next() {
            bytes.push(byte);
            if byte == 0 {
                encoded.next();
            }
        }

        bytes
    }

    memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
}

/// A bounded logical position, bound to database, schema, query and direction.
/// It is not an authorization token or a snapshot. Callers may choose positions;
/// the database revalidates all claims and retains no trusted progress counters.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryCursor {
    binding: [u8; 32],
    position: Vec<u8>,
    resume: Resume,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Resume {
    After = 0,
    Retry = 1,
    AfterUnemittedClass = 2,
}
impl QueryCursor {
    pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;

    /// Encode the bounded continuation for an application's transport.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = vec![1, self.resume as u8];
        bytes.extend(self.binding);
        bytes.extend(&self.position);

        bytes
    }

    /// Decode framing; execution additionally checks query identity and key shape.
    /// # Errors
    /// Refuses unsupported versions, flags and oversized or incomplete frames.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 {
            return Err(Error::InvalidCursor);
        }

        Ok(Self {
            binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
            position: bytes[34..].to_vec(),
            resume: match bytes[1] {
                0 => Resume::After,
                1 => Resume::Retry,
                2 => Resume::AfterUnemittedClass,
                _ => return Err(Error::InvalidCursor),
            },
        })
    }
}

impl serde::Serialize for QueryCursor {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.to_bytes().serialize(serializer)
    }
}

impl<'de> serde::Deserialize<'de> for QueryCursor {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct Frame;

        impl<'de> serde::de::Visitor<'de> for Frame {
            type Value = QueryCursor;

            fn expecting(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                fmt.write_str("a bounded IC DB query cursor frame")
            }

            fn visit_seq<A: serde::de::SeqAccess<'de>>(
                self,
                mut seq: A,
            ) -> Result<QueryCursor, A::Error> {
                let size = seq.size_hint().unwrap_or(0);
                if size > QueryCursor::MAX_ENCODED_BYTES {
                    return Err(serde::de::Error::custom(Error::InvalidCursor));
                }
                let mut frame = Vec::with_capacity(size);
                while let Some(byte) = seq.next_element()? {
                    if frame.len() == QueryCursor::MAX_ENCODED_BYTES {
                        return Err(serde::de::Error::custom(Error::InvalidCursor));
                    }
                    frame.push(byte);
                }
                QueryCursor::from_bytes(&frame).map_err(serde::de::Error::custom)
            }
        }

        deserializer.deserialize_seq(Frame)
    }
}

/// A bounded page. Empty rows do not mean completion when `next` is present.
/// Ordinary queries are live; maintenance source pages read frozen input.
#[derive(Debug)]
pub struct QueryPage<T> {
    /// Matching results in the selected total order.
    pub rows: Vec<T>,
    /// Resume position; only None establishes completion.
    pub next: Option<QueryCursor>,
    /// Examined primary/index candidates, including residual nonmatches and retries.
    pub examined: usize,
    /// Rows fetched; tracked separately from index candidates.
    pub fetched: usize,
    /// Sum of returned encoded entity/projected-record bytes, excluding transport overhead.
    pub output_bytes: usize,
}

impl QueryPage<Vec<u8>> {
    #[inline(never)]
    pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
        Ok(QueryPage {
            rows: self
                .rows
                .iter()
                .map(|bytes| E::decode(bytes))
                .collect::<Result<_, _>>()?,
            next: self.next,
            examined: self.examined,
            fetched: self.fetched,
            output_bytes: self.output_bytes,
        })
    }

    #[inline(never)]
    fn decode_with<R>(
        self,
        decode: impl Fn(&mut Decoder<'_>) -> Result<R, Error>,
    ) -> Result<QueryPage<R>, Error> {
        Ok(QueryPage {
            rows: self
                .rows
                .iter()
                .map(|bytes| {
                    let mut reader = Decoder::new(bytes)?;
                    // Output records replace the entity root, not an extra nested value.
                    let row = decode(&mut reader)?;
                    reader.finish()?;

                    Ok(row)
                })
                .collect::<Result<_, Error>>()?,
            next: self.next,
            examined: self.examined,
            fetched: self.fetched,
            output_bytes: self.output_bytes,
        })
    }
}

/// A literal, row field or length threshold in a fluent predicate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryOperand<'a> {
    /// Compare with this exact typed value.
    Literal(IndexValue<'a>),
    /// Compare the field's byte length (Text/Blob) or item count (list/set/map).
    Length(u32),
    /// Compare with another field or supported direct record member on the same row.
    Field(&'a str),
}

struct Predicate<'a> {
    field: &'a str,
    comparison: Comparison,
    operand: QueryOperand<'a>,
    // Consecutive alternatives form one clause; clauses are ANDed.
    or_next: bool,
}

impl<'a> Predicate<'a> {
    // The opposite operand of a field-to-field comparison, in either spelling.
    fn compared_field(&self, name: &str) -> Option<&'a str> {
        let QueryOperand::Field(right) = self.operand else {
            return None;
        };
        if self.field == name {
            Some(right)
        } else if right == name {
            Some(self.field)
        } else {
            None
        }
    }

    // Endpoints of admitted present scalar values. Text and Blob have an empty minimum.
    fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
        match value {
            IndexValue::Bool(b) => b == upper,
            IndexValue::UnitEnum { ordinal, .. } => entity
                .index_field(self.field)
                .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
            IndexValue::Text("") | IndexValue::Blob([]) => !upper,
            _ => value.is_integer_extreme(upper),
        }
    }

    // The only field value that can satisfy this predicate, when known.
    fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
        if let QueryOperand::Length(n) = self.operand {
            let empty = self
                .comparison
                .empty_length_value(n, entity.index_field(self.field)?.value)?;
            return Some((self.field, empty));
        }
        let QueryOperand::Literal(value) = self.operand else {
            return None;
        };
        // Ordered comparisons exclude absence, including on optional fields.
        let fixed = match (self.comparison, value) {
            (Comparison::Eq, _) => value,
            (Comparison::Ne, IndexValue::Bool(excluded))
                if entity.field_is_required(self.field) =>
            {
                IndexValue::Bool(!excluded)
            }
            (cmp @ (Comparison::Ge | Comparison::Le), _)
                if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
            {
                value
            }
            (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
            (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
            _ => return None,
        };
        Some((self.field, fixed))
    }

    // Each of these predicates matches exactly the rows where the field is present.
    fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
        match (self.comparison, self.operand) {
            (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
            (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
                self.at_extreme(entity, value, cmp == Comparison::Le)
            }
            (_, QueryOperand::Length(_)) => {
                self.present_length_result(entity) == Some(true)
                    && self.comparison != Comparison::Ne
            }
            (
                Comparison::Le
                | Comparison::Ge
                | Comparison::StartsWith
                | Comparison::EndsWith
                | Comparison::Contains,
                QueryOperand::Field(right),
            ) => right == self.field,
            (
                Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
                QueryOperand::Literal(needle),
            ) => {
                // An empty Text/Blob collection member still requires a matching element.
                !matches!(operand, TermOperand::Member { .. })
                    && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
            }
            _ => false,
        }
    }

    // Result for every present length in the declared inclusive range, if uniform.
    fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
        let QueryOperand::Length(n) = self.operand else {
            return None;
        };
        let max = length_limit(entity.index_field(self.field)?.value)?;
        self.comparison.uniform_length_result(0, max, n)
    }

    fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
        if let QueryOperand::Literal(value) = self.operand {
            // Absence also fails these comparisons at the edges of the present domain.
            return match (self.comparison, value) {
                (cmp @ (Comparison::Lt | Comparison::Gt), value)
                    if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
                {
                    Some(false)
                }
                _ => None,
            };
        }
        if matches!(self.operand, QueryOperand::Length(_)) {
            let result = self.present_length_result(entity)?;
            return (result == self.comparison.accepts_absent(false)
                || entity.field_is_required(self.field))
            .then_some(result);
        }
        if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
            return None;
        }
        match self.comparison {
            Comparison::Eq => Some(true),
            Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum SingleResult {
    First,
    Only,
}

struct Request<'a> {
    groups: aggregate::GroupRequest<'a>,
    predicates: Vec<Predicate<'a>>,
    index: Option<(&'a str, Vec<IndexValue<'a>>)>,
    order: Option<Vec<&'a str>>,
    order_descending: u8,
    descending: bool,
    distinct: bool,
    single_result_probe: Option<SingleResult>,
    rows: usize,
    work: usize,
    bytes: usize,
    cursor: Option<&'a QueryCursor>,
    over_limit: bool,
}

impl Default for Request<'_> {
    fn default() -> Self {
        Self {
            groups: aggregate::GroupRequest::default(),
            predicates: Vec::new(),
            index: None,
            order: None,
            order_descending: 0,
            descending: false,
            distinct: false,
            single_result_probe: None,
            rows: 32,
            work: 128,
            bytes: MAX_OUTPUT,
            cursor: None,
            over_limit: false,
        }
    }
}

// Request construction depends on operand shapes, not the entity's Rust type.
// Keep allocation and clause loops out of every typed builder instantiation.
impl<'a> Request<'a> {
    // A single-result probe never returns two rows. Once both are proven,
    // the second needs no space in the response.
    fn check_result_count(&self, count: usize) -> Result<(), Error> {
        if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
            return Err(Error::MultipleMatches);
        }
        Ok(())
    }

    // Every surviving alternative must fix the same field to the same value.
    fn fixed_equalities<'r>(
        &'r self,
        entity: &'r EntitySchema,
    ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
        self.clauses().filter_map(move |clause| {
            let (predicate, rest) = clause.split_first()?;
            if !rest.is_empty() {
                let mut candidate = predicate.fixed_equality(entity)?;
                for alternative in rest {
                    let other = alternative.fixed_equality(entity)?;
                    if candidate.0 != other.0 {
                        return None;
                    }
                    if equal_values(candidate.1, other.1) {
                        continue;
                    }
                    if self.predicates.len() == clause.len() {
                        return None;
                    }
                    if self.excludes_literal(other.0, other.1) {
                        continue;
                    }
                    if !self.excludes_literal(candidate.0, candidate.1) {
                        return None;
                    }
                    candidate = other;
                }
                // If every alternative was excluded, the retained candidate
                // contradicts a mandatory clause during admission.
                return Some(candidate);
            }
            if let Some(equality) = predicate.fixed_equality(entity) {
                return Some(equality);
            }
            // A mandatory lower and upper bound can isolate one value. Only
            // integers and admitted unit enums have a proven successor here. Keep the original terms
            // for row evaluation and continuation identity.
            let QueryOperand::Literal(value) = predicate.operand else {
                return None;
            };
            let lower = match predicate.comparison {
                Comparison::Ge => value,
                Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
                _ => return None,
            };
            self.clauses()
                .any(|clause| {
                    let [upper] = clause else { return false };
                    if upper.field != predicate.field {
                        return false;
                    }
                    match (upper.comparison, upper.operand) {
                        (Comparison::Le, QueryOperand::Literal(value)) => {
                            equal_values(lower, value)
                        }
                        (Comparison::Lt, QueryOperand::Literal(value)) => {
                            consecutive_values(lower, value)
                        }
                        _ => false,
                    }
                })
                .then_some((predicate.field, lower))
        })
    }

    fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
        // One mandatory clause rules out a candidate only if every alternative
        // rejects that value on this field. Other fields can still satisfy an OR.
        self.clauses().any(|clause| {
            clause.iter().all(|predicate| {
                if predicate.field != field {
                    return false;
                }
                let QueryOperand::Literal(literal) = predicate.operand else {
                    return false;
                };
                match predicate.comparison {
                    Comparison::Eq
                    | Comparison::Ne
                    | Comparison::Lt
                    | Comparison::Le
                    | Comparison::Gt
                    | Comparison::Ge => {
                        predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
                    }
                    _ => false,
                }
            })
        })
    }

    fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
        self.predicates.split_inclusive(|p| !p.or_next)
    }

    #[inline(never)]
    fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
        if self.predicates.len() == MAX_TERMS {
            self.over_limit = true;
        } else {
            self.predicates.push(Predicate {
                field,
                comparison,
                operand,
                or_next: false,
            });
        }
    }

    #[inline(never)]
    fn or_clause(
        &mut self,
        alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
    ) {
        let count = alternatives.len();

        if count == 0 || count > MAX_TERMS - self.predicates.len() {
            self.over_limit = true;
        } else {
            self.predicates.extend(alternatives.enumerate().map(
                |(i, (field, comparison, operand))| Predicate {
                    field,
                    comparison,
                    operand,
                    or_next: i + 1 < count,
                },
            ));
        }
    }

    #[inline(never)]
    fn filter_not_in(
        &mut self,
        field: &'a str,
        values: impl ExactSizeIterator<Item = IndexValue<'a>>,
    ) {
        if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
            self.over_limit = true;

            return;
        }
        for value in values {
            self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
        }
    }

    #[inline(never)]
    fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
        if values.len() > 4 {
            self.over_limit = true;
        } else {
            self.index = Some((name, values.to_vec()));
        }
    }

    #[inline(never)]
    fn order_by(&mut self, fields: &[&'a str]) {
        self.order_descending = 0;

        if fields.len() > 4 {
            self.over_limit = true;
        } else {
            self.order = Some(fields.to_vec());
        }
    }

    #[inline(never)]
    fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
        if fields.len() > 4 {
            self.over_limit = true;

            return;
        }
        self.order = Some(Vec::with_capacity(fields.len()));
        self.order_descending = 0;
        for &(field, direction) in fields {
            self.append_order(field, direction);
        }
    }

    fn append_order(&mut self, field: &'a str, direction: SortDirection) {
        let fields = self.order.get_or_insert_with(Vec::new);
        if fields.len() == 4 {
            self.over_limit = true;

            return;
        }
        if direction == SortDirection::Descending {
            self.order_descending |= 1 << fields.len();
        }
        fields.push(field);
    }

    fn primary_descending(&self, entity: &EntitySchema) -> bool {
        self.order_descending != 0
            && self.order.as_ref().is_some_and(|fields| {
                fields.last() == Some(&entity.primary_key)
                    && self.order_descending & (1 << (fields.len() - 1)) != 0
            })
    }
}

// Maintenance gets only bounded primary traversal, not a second query frontend.
pub(super) fn source_page<M: Memory>(
    map: &Map<M>,
    entity: &EntitySchema,
    binding: [u8; 32],
    incarnation: [u8; 16],
    cursor: Option<&QueryCursor>,
    rows: usize,
    bytes: usize,
) -> Result<QueryPage<Vec<u8>>, Error> {
    let request = Request {
        rows,
        work: rows,
        bytes,
        cursor,
        ..Request::default()
    };
    let plan = Plan::admit(
        entity,
        &request,
        binding,
        incarnation,
        None,
        PlanOutput::Rows,
    )?;

    execute(map, entity, &request, &plan, None)
}

enum QuerySource<'a, M: Memory> {
    Direct(&'a Database<M>),
    Session(Rc<RefCell<Database<M>>>),
}

enum QueryRead<'a, M: Memory> {
    Direct(&'a Database<M>),
    Session(Ref<'a, Database<M>>),
}

impl<M: Memory> Deref for QueryRead<'_, M> {
    type Target = Database<M>;

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Direct(db) => db,
            Self::Session(db) => db,
        }
    }
}

impl<M: Memory> QuerySource<'_, M> {
    fn read(&self) -> Result<QueryRead<'_, M>, Error> {
        match self {
            Self::Direct(db) => Ok(QueryRead::Direct(db)),
            Self::Session(db) => db
                .try_borrow()
                .map(QueryRead::Session)
                .map_err(|_| Error::BorrowConflict),
        }
    }
}

/// Fluent exact predicates over one entity. No callback executor is generated.
/// Ordering uses primary order, an explicit index, a proven automatic path or
/// bounded complete sorting. Work exhaustion never returns a sorted prefix.
pub struct Query<'a, E, M: Memory> {
    db: QuerySource<'a, M>,
    request: Request<'a>,
    entity: PhantomData<E>,
}
impl<M: Memory> Database<M> {
    /// Begin a live primary-key-ordered query. Admission occurs on `fetch`.
    #[must_use]
    pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
        Query {
            db: QuerySource::Direct(self),
            entity: PhantomData,
            request: Request::default(),
        }
    }
}
impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
    pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
        Self {
            db: QuerySource::Session(db),
            request: Request::default(),
            entity: PhantomData,
        }
    }

    /// Remove duplicate output records. Proven leading index tuples use live
    /// pages. Projecting the primary key or the varying fields of a unique key covering every match
    /// needs no duplicate tracking. Other projections scan to
    /// completion in one call, retaining at most 32 tuples within 128 KiB.
    /// That fallback preserves first-match traversal order, refuses cursors and
    /// returns `Limit` if work, result count or combined bytes cannot fit; it
    /// never returns a partial result. An individually oversized row returns
    /// `RowTooLarge`. Comparison keys are bounded to 4096 bytes.
    /// For enumeration across calls, [`Self::start_distinct`] and [`Self::resume_distinct`]
    /// retain up to 255 tuples within a 16 KiB job frame, then page the completed result.
    /// Non-identity sorted DISTINCT retains the best `limit` distinct tuples. Its order
    /// must lead with all varying projected fields. A mandatory literal equality
    /// fixes a field. Remove duplicates before applying `limit` and output bytes.
    #[must_use]
    pub fn distinct(mut self) -> Self {
        self.request.distinct = true;

        self
    }

    /// Add an AND term. A top-level list or set supports exact scalar membership with `Contains`.
    /// A direct scalar record member selected by [`crate::field_path!`] accepts
    /// Eq, Ne, Lt, Le, Gt and Ge against a literal. Text and Blob members
    /// also accept `StartsWith` and `EndsWith` with an operand of the same type.
    /// Eq/Ne with `IndexValue::Absent` also accept any optional stored field,
    /// including blobs and containers. Empty values are present, not absent.
    /// All operands are admitted before storage reads, including contradictory terms.
    /// On a primary traversal, mandatory Eq/Lt/Le/Gt/Ge primary-key comparisons
    /// narrow the scanned range. On an index path, those comparisons can narrow
    /// its first field after the admitted fixed prefix. Only examined rows
    /// undergo integrity checks; oversized derived bounds remain residual filters.
    /// Indexed StartsWith can seek that field's exact encoded Text/Blob prefix too.
    #[must_use]
    pub fn filter(
        mut self,
        field: &'a str,
        comparison: Comparison,
        value: impl Into<IndexValue<'a>>,
    ) -> Self {
        self.request
            .filter(field, comparison, QueryOperand::Literal(value.into()));

        self
    }

    /// Require an exact field value. Equivalent to `filter(field, Comparison::Eq, value)`.
    #[must_use]
    pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
        self.filter(field, Comparison::Eq, value)
    }

    /// Require a different value, including absent versus present.
    #[must_use]
    pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
        self.filter(field, Comparison::Ne, value)
    }

    /// Require a present field strictly below the supplied value.
    #[must_use]
    pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
        self.filter(field, Comparison::Lt, value)
    }

    /// Require a present field at or below the supplied value.
    #[must_use]
    pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
        self.filter(field, Comparison::Le, value)
    }

    /// Require a present field strictly above the supplied value.
    #[must_use]
    pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
        self.filter(field, Comparison::Gt, value)
    }

    /// Require a present field at or above the supplied value.
    #[must_use]
    pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
        self.filter(field, Comparison::Ge, value)
    }

    /// Compare fields on the same row. Eq, Ne, Lt, Le, Gt and Ge also accept
    /// direct scalar record members on either side, as do StartsWith and EndsWith for Text and Blob.
    /// Top-level lists and sets support Contains
    /// with a present scalar field or direct record member of the element type. Text and Blob also
    /// support StartsWith, EndsWith and Contains with a present right-hand field.
    /// Types must match; Text and Blob bounds may differ within their respective families.
    /// Two absent values are equal. An ordered comparison requires two present values.
    #[must_use]
    pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
        self.request
            .filter(left, comparison, QueryOperand::Field(right));

        self
    }

    /// Compare UTF-8 bytes for Text, raw bytes for Blob, or the item count for a
    /// list, set or map. A direct Text or Blob record member also supports byte
    /// length through [`crate::field_path!`]. Accepts Eq, Ne, Lt, Le, Gt and Ge. An absent field
    /// matches Ne only; use Gt(0) for a present, nonempty value.
    #[must_use]
    pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
        self.request
            .filter(field, comparison, QueryOperand::Length(length));

        self
    }

    /// Match rows whose optional field has a value, including an empty value.
    /// Required and unknown fields return `InvalidQuery` at admission.
    #[must_use]
    pub fn filter_present(self, field: &'a str) -> Self {
        self.filter(field, Comparison::Ne, IndexValue::Absent)
    }

    /// Match rows whose optional field has no value.
    /// Required and unknown fields return `InvalidQuery` at admission.
    #[must_use]
    pub fn filter_absent(self, field: &'a str) -> Self {
        self.filter(field, Comparison::Eq, IndexValue::Absent)
    }

    /// Match a present field inside an inclusive range, ANDed with other filters.
    /// Equivalent to `filter(field, Comparison::Ge, lower)` followed by
    /// `filter(field, Comparison::Le, upper)`, including cursor/job identity.
    /// Both exact operands are admitted and consume two of the eight comparisons.
    /// Absent operands refuse; absent fields never match. Reversed bounds produce
    /// no matches, without skipping admission of either operand or other filters.
    #[must_use]
    pub fn filter_between(
        self,
        field: &'a str,
        lower: impl Into<IndexValue<'a>>,
        upper: impl Into<IndexValue<'a>>,
    ) -> Self {
        self.filter(field, Comparison::Ge, lower)
            .filter(field, Comparison::Le, upper)
    }

    /// Match a present field strictly outside an inclusive range.
    /// Equivalent to one `filter_any` clause containing `Lt lower` then `Gt upper`,
    /// including cursor/job identity. Both exact operands consume filter terms.
    /// Absent operands refuse and absent fields never match; this is not a general
    /// negation of `filter_between`. Equal bounds exclude that value; reversed
    /// bounds match every present value, once. Uses the existing single traversal
    /// and work budget, without seeking separate ranges for the two alternatives.
    #[must_use]
    pub fn filter_not_between(
        self,
        field: &'a str,
        lower: impl Into<IndexValue<'a>>,
        upper: impl Into<IndexValue<'a>>,
    ) -> Self {
        self.filter_any(&[
            (field, Comparison::Lt, lower.into()),
            (field, Comparison::Gt, upper.into()),
        ])
    }

    /// Match `lower <= field && field <= upper` using three top-level fields of the row.
    /// Both comparisons require present values of compatible types. Equal endpoints
    /// are inclusive. Uses the same two comparison terms and continuation as the
    /// equivalent chained `filter_fields` calls.
    #[must_use]
    pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
        self.filter_fields(field, Comparison::Ge, lower)
            .filter_fields(field, Comparison::Le, upper)
    }

    /// Match `field < lower || field > upper` using fields of the same row.
    /// A missing bound makes only its own comparison false. A missing tested field
    /// never matches. Uses one OR clause and the same two comparison terms and
    /// continuation as the equivalent `filter_any_operands` call.
    #[must_use]
    pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
        self.filter_any_operands(&[
            (field, Comparison::Lt, QueryOperand::Field(lower)),
            (field, Comparison::Gt, QueryOperand::Field(upper)),
        ])
    }

    /// Add an OR clause of literal comparisons, ANDed with other filters.
    /// Alternatives may compare different direct scalar members of a record.
    /// Each clause must contain at least one comparison; all filters together
    /// may contain at most eight. Empty/oversized clauses refuse with `Error::Limit`
    /// at execution. Every operand is admitted, even if another alternative matches.
    /// Uses one ordered traversal, without union scans or duplicate rows. Alternatives
    /// do not establish fixed index prefixes; a one-term clause behaves like `filter`.
    #[must_use]
    pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
        self.request.or_clause(
            alternatives
                .iter()
                .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
        );

        self
    }

    /// Add one OR clause of literal, field-to-field or length comparisons.
    /// Each alternative follows its corresponding single-filter admission rules.
    /// All alternatives share the eight-comparison budget with the other filters.
    /// Literal-only clauses have the same cursor and job identity as `filter_any`.
    #[must_use]
    pub fn filter_any_operands(
        mut self,
        alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
    ) -> Self {
        self.request.or_clause(alternatives.iter().copied());

        self
    }

    /// Match a field against any supplied exact value, ANDed with other filters.
    /// Equivalent to `filter_any` with equality comparisons in the supplied order.
    /// Include `None` in a slice of optional values to match an absent field.
    /// When the field is the next traversal key component, seek between the smallest
    /// and largest member, including all tied owners. Interior candidates still consume work.
    /// Repeated members never repeat rows, but each counts toward the shared
    /// eight-comparison limit. Empty or oversized lists refuse with `Error::Limit`.
    /// Every member is admitted before reading; there is no coercion, sorting or
    /// deduplication of operands. Reordering members changes cursor/job identity.
    #[must_use]
    pub fn filter_in(
        mut self,
        field: &'a str,
        values: &[impl Copy + Into<IndexValue<'a>>],
    ) -> Self {
        self.request.or_clause(
            values
                .iter()
                .copied()
                .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
        );

        self
    }

    /// Exclude every supplied exact value, ANDed with other filters.
    /// Equivalent to consecutive `filter(field, Comparison::Ne, value)` calls
    /// in the supplied order. Absent fields match unless absence is explicitly
    /// excluded. Empty lists refuse; all members, including duplicates, count
    /// toward the shared eight-comparison budget. Every operand is admitted.
    /// The equivalent inequality chain shares cursor/job identity; reordering
    /// the list changes that identity. No coercion or deduplication is performed.
    #[must_use]
    pub fn filter_not_in(
        mut self,
        field: &'a str,
        values: &[impl Copy + Into<IndexValue<'a>>],
    ) -> Self {
        self.request
            .filter_not_in(field, values.iter().copied().map(Into::into));

        self
    }

    /// Select index order and exact leading components (at most four).
    /// All rows matching this prefix are considered. Sparse indexes require
    /// every optional indexed component to be proven present by the prefix or
    /// filters. Every alternative in a proving OR clause must reject absence.
    #[must_use]
    pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
        self.request.using_index(name, values);

        self
    }

    /// Append an ascending sort field. Earlier fields take precedence.
    /// The same field, work and continuation rules as [`Self::order_by_each`] apply.
    #[must_use]
    pub fn order_asc(mut self, field: &'a str) -> Self {
        self.request.append_order(field, SortDirection::Ascending);

        self
    }

    /// Append a descending sort field. An implicit primary-key tie-breaker
    /// stays ascending; append the primary key explicitly to choose its direction.
    #[must_use]
    pub fn order_desc(mut self, field: &'a str) -> Self {
        self.request.append_order(field, SortDirection::Descending);

        self
    }

    /// Replace the current order with 1..=4 distinct ordered scalar fields, then the primary key.
    /// A direct record member can be selected with [`crate::field_path!`].
    /// An explicitly listed primary key must be last. All fields share one
    /// direction, reversed by `descending`. Prefer a complete ordered path.
    /// Otherwise scan to completion while retaining the best `limit` rows within
    /// 128 KiB of key/output buffers, then sort them. Non-identity DISTINCT retains
    /// the best `limit` distinct tuples. Work exhaustion refuses; no
    /// cursor is supported by this fallback. DISTINCT requires an identity result
    /// or an order led by all varying projected fields. Equality terms may fix
    /// leading index components. With `using_index`, require that path's order.
    #[must_use]
    pub fn order_by(mut self, fields: &[&'a str]) -> Self {
        self.request.order_by(fields);

        self
    }

    /// Replace the order with 1..=4 fields and their individual directions.
    /// An explicit primary key must be last; otherwise append it ascending.
    /// `descending()` reverses every direction, including that tie-breaker.
    /// The same path proof and complete-sort bounds as `order_by` apply.
    #[must_use]
    pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
        self.request.order_by_each(fields);

        self
    }

    /// Reverse the complete result order, including its unique tie-breaker.
    #[must_use]
    pub fn descending(mut self) -> Self {
        self.request.descending = true;

        self
    }

    /// Return at most 1..=32 matching rows in this page.
    /// Complete-collection DISTINCT refuses if the full result exceeds this cap.
    /// Complete sorting examines the entire admitted input and retains at most
    /// the requested number of winners, even when many more rows match.
    /// For grouped aggregates, cap the complete selected result instead; use
    /// `group_page` to set a retained grouped response's page size separately.
    #[must_use]
    pub fn limit(mut self, rows: usize) -> Self {
        self.request.rows = rows;

        self
    }

    /// Examine at most 1..=512 candidates, independently of the returned row limit.
    #[must_use]
    pub fn work_limit(mut self, candidates: usize) -> Self {
        self.request.work = candidates;

        self
    }

    /// Exercise output exhaustion with a small response in qualification fixtures.
    #[cfg(feature = "test-support")]
    #[doc(hidden)]
    #[must_use]
    pub fn test_output_limit(mut self, bytes: usize) -> Self {
        self.request.bytes = bytes;

        self
    }

    /// Continue this query; page resource limits may change between calls.
    #[must_use]
    pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
        self.request.cursor = Some(cursor);

        self
    }

    /// Admit and execute one page, then decode only its matching output rows.
    /// # Errors
    /// Refuses unsupported shapes, inexact operands, limits, invalid cursors and corruption.
    /// A selected output row larger than the whole byte allowance returns `RowTooLarge`.
    /// # Panics
    /// Supplier corruption traps without repair, as for direct record reads.
    pub fn fetch(self) -> Result<QueryPage<E>, Error> {
        observe!(query, { self.entity_page() })
    }

    fn entity_page(self) -> Result<QueryPage<E>, Error> {
        fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
    }

    /// Return the first matching entity in query order, or `None` on a proven miss.
    /// Uses a one-row page. For partial pages with resumable progress use `fetch`.
    /// # Errors
    /// Returns the same admission and storage errors as `fetch`. Returns `Limit`
    /// if the work budget ends before a match or exhaustion is established.
    pub fn first(self) -> Result<Option<E>, Error> {
        self.first_with(Self::entity_page)
    }

    /// Return the first projected record in query order.
    /// # Errors
    /// Applies the projection checks of [`Self::fetch_as`] and the work bound of [`Self::first`].
    pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
        self.first_with(Self::projected_page::<R>)
    }

    fn first_with<R>(
        self,
        fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
    ) -> Result<Option<R>, Error> {
        observe!(query, { fetch(self.probe_matches(SingleResult::First)?) })
            .map(|mut page| page.rows.pop())
    }

    /// Return the only match, or `None` when the query is exhausted without one.
    /// A valid row limit is overridden to probe for two matches. Applies to the
    /// whole query, so a continuation is refused.
    /// # Errors
    /// Returns `MultipleMatches` on a second match and `Limit` if the page is
    /// incomplete before cardinality is known. Ordinary fetch errors apply.
    pub fn try_one(self) -> Result<Option<E>, Error> {
        self.try_one_with(Self::entity_page)
    }

    /// Return the sole projected result, or `None` on a proven miss.
    /// With DISTINCT, a literal equality or fixed index prefix covering every
    /// projected field lets an ordered traversal finish at the first match.
    /// # Errors
    /// Applies the projection checks of [`Self::fetch_as`] and the cardinality checks of [`Self::try_one`].
    pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
        self.try_one_with(Self::projected_page::<R>)
    }

    fn try_one_with<R>(
        self,
        fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
    ) -> Result<Option<R>, Error> {
        observe!(query, {
            if self.request.cursor.is_some() {
                return Err(Error::InvalidQuery);
            }
            fetch(self.probe_matches(SingleResult::Only)?)
        })
        .map(|mut page| page.rows.pop())
    }

    fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
        if !(1..=32).contains(&self.request.rows) {
            return Err(Error::Limit);
        }

        self.request.single_result_probe = Some(probe);

        Ok(self.limit(match probe {
            SingleResult::First => 1,
            SingleResult::Only => 2,
        }))
    }

    /// Project matching top-level fields into an existing `#[record]` type.
    /// Names, optionality and complete value definitions must match exactly.
    /// The record is an output shape, not a new stored entity or schema entry.
    /// Byte limits count projected bytes; all source fields still undergo validation.
    /// # Errors
    /// Refuses non-record/empty or incompatible output shapes, and the same failures
    /// as `fetch`. A continuation must use the same selected field shape.
    /// # Panics
    /// Supplier corruption traps without repair, as for direct record reads.
    pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
        observe!(query, { self.projected_page() })
    }

    fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
        let raw = fetch_rows(
            &*self.db.read()?,
            E::SCHEMA,
            self.request,
            Some(Projection::Record(R::definition())),
        )?;

        raw.decode_with(R::decode_from)
    }
}

#[derive(Clone, Copy)]
enum Projection<'a> {
    Record(&'a TypeSchema),
    Columns(&'a [u8]),
}

impl Projection<'_> {
    fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
        match self {
            Self::Record(record) => admit_projection(entity, record),
            Self::Columns(columns) => {
                let mut mask = 0;
                for &column in columns {
                    if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
                        return Err(Error::InvalidQuery);
                    }
                    mask |= 1 << column;
                }
                Ok(mask)
            }
        }
    }
}

// Reuse named-record metadata/codecs rather than a second value tree or a
// generic executor per output shape. The full transitive graph matters: named
// links compare by identity, which alone cannot establish codec compatibility.
fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
    let TypeBody::Record(fields) = &output.body else {
        return Err(Error::InvalidQuery);
    };
    if fields.is_empty()
        || fields.len() > crate::schema::MAX_FIELDS
        || fields.windows(2).any(|w| w[0].name >= w[1].name)
    {
        return Err(Error::InvalidQuery);
    }
    let mut source = TypeGraph::default();
    let mut target = TypeGraph::default();
    let mut mask = 0;
    for field in *fields {
        let position = entity
            .field_position(field.name)
            .ok_or(Error::InvalidQuery)?;
        let stored = &entity.fields[position];
        if stored.value != field.value || stored.optional != field.optional {
            return Err(Error::InvalidQuery);
        }
        source
            .include(stored.value)
            .map_err(|_| Error::InvalidQuery)?;
        target
            .include(field.value)
            .map_err(|_| Error::InvalidQuery)?;
        mask |= 1 << position;
    }
    if !source.contains(&target) {
        return Err(Error::InvalidQuery);
    }

    Ok(mask)
}

struct Term {
    tests_presence: bool,
    position: usize,
    comparison: Comparison,
    operand: TermOperand,
    or_next: bool,
}

enum TermOperand {
    Literal {
        bytes: Vec<u8>,
        absent: bool,
    },
    Member {
        item: FieldType,
        needle: MemberNeedle,
    },
    Nested {
        member: crate::member::RecordMember,
        literal: Vec<u8>,
        absent: bool,
    },
    Field {
        right: usize,
        left_member: Option<crate::member::RecordMember>,
        right_member: Option<crate::member::RecordMember>,
    },
    Length {
        member: Option<crate::member::RecordMember>,
        threshold: u32,
    },
}

enum MemberNeedle {
    Literal(Vec<u8>),
    Field(usize, Option<crate::member::RecordMember>),
}

// Operands have already been type-checked. Text and Blob literals carry their
// original bytes, before the durable key codec escapes embedded zeros.
fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
    match value {
        IndexValue::Text(text) => Some(text.as_bytes()),
        IndexValue::Blob(bytes) => Some(bytes),
        _ => None,
    }
}

fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
    low.discrete_successor()
        .is_some_and(|next| equal_values(next, high))
}

fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
    // Admission already checked both enum contracts.
    match (left, right) {
        (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
            a == b
        }
        _ => left == right,
    }
}

fn length_limit(field: FieldType) -> Option<u32> {
    match key::operand_type(field) {
        FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
        FieldType::List { max_items, .. } => Some(max_items),
        FieldType::Named(link) => match (link.definition)().body {
            TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
            _ => None,
        },
        _ => None,
    }
}

fn member_type(field: FieldType) -> Option<FieldType> {
    match key::operand_type(field) {
        FieldType::List { item, .. } => Some(*item),
        FieldType::Named(link) => match (link.definition)().body {
            TypeBody::Set { item, .. } => Some(item),
            _ => None,
        },
        _ => None,
    }
}

// inspect_fields has already validated every item, including the tail after a match.
fn contains_member(
    span: &[u8],
    optional: bool,
    item: FieldType,
    needle: IndexValue<'_>,
) -> Result<bool, Error> {
    let mut reader = Decoder::new(span)?;
    if optional && !reader.boolean()? {
        return Ok(false);
    }
    for _ in 0..reader.nat32()? {
        let value = IndexValue::read(&mut reader, item)?;
        if equal_values(value, needle) {
            return Ok(true);
        }
    }

    Ok(false)
}

// Admission sets bits only for fields in this entity. Consuming the lowest
// bit first preserves the canonical field order of projected records and keys.
fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
    std::iter::from_fn(move || {
        if mask == 0 {
            return None;
        }
        let position = mask.trailing_zeros() as usize;
        mask &= mask - 1;
        Some(position)
    })
}

fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
    for i in projection_positions(mask) {
        if !key::supports(entity.fields[i].value) {
            return Err(Error::InvalidQuery);
        }
    }

    Ok(())
}

// Grouping, distinct counts and collected DISTINCT share exact tuple equality.
fn comparison_key(
    entity: &EntitySchema,
    mask: u32,
    values: &[IndexValue<'_>],
    scratch: &mut Vec<u8>,
) -> Result<(), Error> {
    build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
}

fn build_comparison_key<'a>(
    entity: &EntitySchema,
    mask: u32,
    key: &mut Vec<u8>,
    mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
) -> Result<(), Error> {
    key.clear();
    for i in projection_positions(mask) {
        let field = &entity.fields[i];
        value(i, field)?.append_component(field.optional, key);
        if key.len() > MAX_COMPARISON_KEY {
            return Err(Error::Limit);
        }
    }

    Ok(())
}

fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
    if size > limit {
        return Err(Error::RowTooLarge);
    }
    if size > limit - *used {
        return Err(Error::Limit);
    }
    *used += size;

    Ok(())
}

// Size and copy already validated projection spans using the same field mask.
fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
    projection_positions(mask)
        .map(|i| {
            let (start, end) = spans[i];
            usize::from(end - start)
        })
        .sum()
}

fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
    let mut output = Vec::with_capacity(size);
    for i in projection_positions(mask) {
        let (start, end) = spans[i];
        output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
    }

    output
}
#[derive(Clone, Copy)]
enum PlanOutput {
    Rows,
    Aggregate { grouped: bool },
}

struct Plan<'a> {
    primary: usize,
    index: Option<&'a IndexSchema>,
    prefix: Vec<u8>,
    fixed_components: usize,
    terms: Vec<Term>,
    selected: u32,
    // Non-orderable fields need only their validated optional tags, never key slots.
    span_fields: u32,
    binding: [u8; 32],
    projection: Option<u32>,
    distinct: distinct::Strategy,
    sort: Option<Vec<order::SortField>>,
    descending: bool,
}
impl<'a> Plan<'a> {
    fn clauses(&self) -> impl Iterator<Item = &[Term]> {
        self.terms.split_inclusive(|term| !term.or_next)
    }

    fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
        self.index = Some(path.index);
        self.prefix = path.prefix;
        self.fixed_components = path.fixed;
        self.selected |= entity.key_fields();
    }

    fn admit(
        entity: &'a EntitySchema,
        request: &Request<'_>,
        schema: [u8; 32],
        incarnation: [u8; 16],
        projection: Option<Projection<'_>>,
        output: PlanOutput,
    ) -> Result<Self, Error> {
        if request.over_limit
            || !(1..=32).contains(&request.rows)
            || !(1..=MAX_WORK).contains(&request.work)
            || !(1..=MAX_OUTPUT).contains(&request.bytes)
        {
            return Err(Error::Limit);
        }
        if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
        {
            return Err(Error::InvalidQuery);
        }
        // Bound literal encoding even when a declaration's maximum exceeds one row.
        for value in request
            .predicates
            .iter()
            .filter_map(|p| match &p.operand {
                QueryOperand::Literal(value) => Some(value),
                QueryOperand::Field(_) | QueryOperand::Length(_) => None,
            })
            .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
        {
            if match value {
                IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
                IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
                _ => false,
            } {
                return Err(Error::Limit);
            }
        }
        let primary = entity
            .field_position(entity.primary_key)
            .filter(|&i| !entity.fields[i].optional)
            .ok_or(Error::InvalidQuery)?;
        let mut plan = Self {
            primary,
            index: None,
            prefix: prefix(2, entity.id, &[]),
            fixed_components: 0,
            terms: Vec::new(),
            selected: 1 << primary,
            span_fields: 0,
            binding: [0; 32],
            projection: projection.map(|output| output.mask(entity)).transpose()?,
            distinct: distinct::Strategy::Identity,
            sort: None,
            descending: request.descending ^ request.primary_descending(entity),
        };
        for predicate in &request.predicates {
            let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
            let field = &entity.fields[position];
            let member = if predicate.comparison == Comparison::Contains {
                member_type(field.value)
            } else {
                None
            };
            let operand = match (predicate.operand, record_member) {
                (QueryOperand::Literal(value), Some(member)) => {
                    if !predicate.comparison.supports_record_member() {
                        return Err(Error::InvalidQuery);
                    }
                    let leaf = member.field();
                    predicate.comparison.admit(
                        leaf.value,
                        field.optional || leaf.optional,
                        value,
                    )?;
                    let mut literal = Vec::new();
                    value.append_component(field.optional || leaf.optional, &mut literal);
                    plan.span_fields |= 1 << position;
                    TermOperand::Nested {
                        member,
                        literal,
                        absent: value == IndexValue::Absent,
                    }
                }
                (QueryOperand::Length(length), member) => {
                    let selected = member.map_or(field.value, |m| m.field().value);
                    if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
                        return Err(Error::InvalidQuery);
                    }
                    plan.span_fields |= 1 << position;

                    TermOperand::Length {
                        member,
                        threshold: length,
                    }
                }
                (QueryOperand::Field(name), left_member) => {
                    let (right, right_member) = crate::member::resolve_field(entity, name)?;
                    if (left_member.is_some() || right_member.is_some())
                        && member.is_none()
                        && !predicate.comparison.supports_record_member()
                    {
                        return Err(Error::InvalidQuery);
                    }
                    let right_type =
                        right_member.map_or(entity.fields[right].value, |m| m.field().value);
                    let left_type =
                        left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
                    let compatible = left_type == right_type
                        || matches!(
                            (left_type, right_type),
                            (FieldType::Text { .. }, FieldType::Text { .. })
                                | (FieldType::Blob { .. }, FieldType::Blob { .. })
                        );
                    if !compatible
                        || !key::supports(left_type)
                        || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
                    {
                        return Err(Error::InvalidQuery);
                    }
                    if right_member.is_some() {
                        plan.span_fields |= 1 << right;
                    } else {
                        plan.selected |= 1 << right;
                    }

                    if let Some(item) = member {
                        plan.span_fields |= 1 << position;

                        TermOperand::Member {
                            item,
                            needle: MemberNeedle::Field(right, right_member),
                        }
                    } else {
                        if left_member.is_some() {
                            plan.span_fields |= 1 << position;
                        } else {
                            plan.selected |= 1 << position;
                        }
                        TermOperand::Field {
                            right,
                            left_member,
                            right_member,
                        }
                    }
                }
                (QueryOperand::Literal(value), None) => {
                    if let Some(item) = member {
                        if !key::supports(item) {
                            return Err(Error::InvalidQuery);
                        }
                        value.admit(item, false)?;
                        let mut bytes = Vec::new();
                        value.append_component(false, &mut bytes);
                        plan.span_fields |= 1 << position;

                        TermOperand::Member {
                            item,
                            needle: MemberNeedle::Literal(bytes),
                        }
                    } else {
                        let absent = value == IndexValue::Absent;
                        if key::supports(field.value) {
                            plan.selected |= 1 << position;
                        } else if absent
                            && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
                        {
                            plan.span_fields |= 1 << position;
                        } else {
                            return Err(Error::InvalidQuery);
                        }
                        predicate
                            .comparison
                            .admit(field.value, field.optional, value)?;
                        let mut bytes = Vec::new();
                        value.append_component(field.optional, &mut bytes);

                        TermOperand::Literal { bytes, absent }
                    }
                }
            };
            plan.terms.push(Term {
                tests_presence: predicate.tests_presence(entity, &operand),
                position,
                comparison: predicate.comparison,
                operand,
                or_next: predicate.or_next,
            });
        }
        // Admit every operand before selecting a path, even for empty or
        // contradictory queries. The scanner consumes this one proven choice.
        match order::select(entity, request, output)? {
            order::Path::Primary => {}
            order::Path::Index(path, descending) => {
                plan.use_index(entity, path);
                plan.descending = request.descending ^ descending;
            }
            order::Path::Filtered { sort } => {
                order::select_filtered_path(entity, request, &mut plan, None)?;
                for field in sort.iter().flatten() {
                    if field.member.is_some() {
                        plan.span_fields |= 1 << field.position;
                    } else {
                        plan.selected |= 1 << field.position;
                    }
                }
                plan.sort = sort;
            }
        }
        if request.distinct {
            plan.distinct = distinct::admit(entity, request, &plan)?;
            match plan.distinct {
                distinct::Strategy::FirstMatch => plan.sort = None,
                distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
                _ => {}
            }
        }
        let mut hash = Sha256::new();
        hash.update(b"ic-db:query:v1\0");
        hash.update(schema);
        hash.update(incarnation);
        hash.update([u8::from(request.descending)]);
        hash.update((plan.prefix.len() as u32).to_le_bytes());
        hash.update(&plan.prefix);
        for term in &plan.terms {
            hash.update([term.position as u8, term.comparison as u8]);

            match &term.operand {
                TermOperand::Nested {
                    member,
                    literal,
                    absent,
                } => {
                    hash.update((u32::MAX - 2).to_le_bytes());
                    hash.update([member.position() as u8, u8::from(*absent)]);
                    // The binding already records absence separately from the scalar payload.
                    let literal = &literal[usize::from(
                        entity.fields[term.position].optional || member.field().optional,
                    )..];
                    hash.update((literal.len() as u32).to_le_bytes());
                    hash.update(literal);
                }
                TermOperand::Literal { bytes, .. }
                | TermOperand::Member {
                    needle: MemberNeedle::Literal(bytes),
                    ..
                } => {
                    hash.update((bytes.len() as u32).to_le_bytes());
                    hash.update(bytes);
                }
                TermOperand::Length { member, threshold } => {
                    if let Some(member) = member {
                        hash.update((u32::MAX - 3).to_le_bytes());
                        hash.update([member.position() as u8]);
                    } else {
                        hash.update((u32::MAX - 1).to_le_bytes());
                    }
                    hash.update(threshold.to_le_bytes());
                }
                TermOperand::Field {
                    right,
                    left_member: None,
                    right_member: None,
                }
                | TermOperand::Member {
                    needle: MemberNeedle::Field(right, None),
                    ..
                } => {
                    // Outside the bounded literal length domain.
                    hash.update(u32::MAX.to_le_bytes());
                    hash.update([*right as u8]);
                }
                TermOperand::Member {
                    needle: MemberNeedle::Field(right, Some(member)),
                    ..
                } => {
                    hash.update((u32::MAX - 4).to_le_bytes());
                    hash.update([u8::MAX, *right as u8, member.position() as u8]);
                }
                TermOperand::Field {
                    right,
                    left_member,
                    right_member,
                } => {
                    hash.update((u32::MAX - 4).to_le_bytes());
                    let slot = |member: &Option<crate::member::RecordMember>| {
                        member.map_or(u8::MAX, |m| m.position() as u8)
                    };
                    hash.update([slot(left_member), *right as u8, slot(right_member)]);
                }
            }
        }
        // Keep existing conjunction identities unchanged. A bounded clause mask
        // distinguishes OR grouping without persisting another predicate model.
        let clauses = plan
            .terms
            .iter()
            .enumerate()
            .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
        if clauses != 0 {
            hash.update(b"or-clauses\0");
            hash.update([clauses]);
        }
        if let Some(order) = &request.order {
            hash.update(b"order\0");
            hash.update([order.len() as u8]);
            for name in order {
                // Field names were admitted by order selection above.
                if let Some(position) = entity.field_position(name) {
                    hash.update([position as u8]);
                } else {
                    // A top-level position is at most 31. Frame each admitted nested path.
                    hash.update([u8::MAX, name.len() as u8]);
                    hash.update(name.as_bytes());
                }
            }
        }
        if request.order_descending != 0 {
            hash.update(b"order-directions\0");
            hash.update([request.order_descending]);
        }
        // Preserve existing entity-result cursors. Projected shapes add a
        // domain-separated suffix; output Rust names do not change semantics.
        if let Some(mask) = plan.projection {
            hash.update(b"projection\0");
            hash.update(mask.to_le_bytes());
            if let Some(Projection::Columns(columns)) = projection {
                hash.update(b"columns\0");
                hash.update(columns);
            }
        }
        if request.distinct {
            hash.update(b"distinct\0");
        }
        plan.binding = hash.finalize().into();
        if let Some(cursor) = request.cursor {
            if cursor.binding != plan.binding {
                return Err(Error::InvalidCursor);
            }
            plan.validate_position(entity, cursor)
                .map_err(|_| Error::InvalidCursor)?;
        }

        Ok(plan)
    }

    fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
        if cursor.resume == Resume::AfterUnemittedClass
            && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
        {
            return Err(Error::InvalidCursor);
        }
        let bytes = cursor.position.as_slice();
        if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
            return Err(Error::InvalidCursor);
        }
        if let Some(index) = self.index {
            let mut remaining = bytes
                .get(INDEX_PREFIX_BYTES..)
                .ok_or(Error::InvalidCursor)?;
            for name in index.fields {
                consume_index_component(entity, index, name, &mut remaining)?;
            }
            if !index.unique {
                key::consume(&mut remaining, entity.key_type()?)?;
            }
            if !remaining.is_empty() {
                return Err(Error::InvalidCursor);
            }
        } else {
            RowKey::decode(
                bytes
                    .get(ENTITY_PREFIX_BYTES..)
                    .ok_or(Error::InvalidCursor)?,
                entity.key_type()?,
            )?;
        }

        Ok(())
    }

    fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
        QueryCursor {
            binding: self.binding,
            position: position.to_vec(),
            resume,
        }
    }
}

// Cursor framing and DISTINCT equivalence boundaries use the same key decoder.
fn consume_index_component(
    entity: &EntitySchema,
    index: &IndexSchema,
    name: &str,
    remaining: &mut &[u8],
) -> Result<(), Error> {
    let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;

    key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
}

// Admission, execution and request cleanup share one entity-independent boundary.
// Only conversion of the returned bytes remains in the typed public terminals.
#[inline(never)]
#[expect(
    clippy::needless_pass_by_value,
    reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
)]
fn fetch_rows<M: Memory>(
    db: &Database<M>,
    entity: &EntitySchema,
    request: Request<'_>,
    projection: Option<Projection<'_>>,
) -> Result<QueryPage<Vec<u8>>, Error> {
    db.schema.admits(entity)?;
    let plan = Plan::admit(
        entity,
        &request,
        db.schema.fingerprint(),
        db.incarnation,
        projection,
        PlanOutput::Rows,
    )?;

    execute(&db.map, entity, &request, &plan, None)
}

fn execute<M: Memory>(
    map: &Map<M>,
    entity: &EntitySchema,
    request: &Request<'_>,
    plan: &Plan<'_>,
    mut aggregate: Option<aggregate::Accumulator<'_>>,
) -> Result<QueryPage<Vec<u8>>, Error> {
    execute_inner(
        map,
        entity,
        request,
        plan,
        range::bounds(entity, request, plan)?,
        aggregate.as_mut(),
        None,
    )
}

// Retained aggregates use the same traversal, but checkpoint at a work boundary.
// Reserve a maximum candidate before the next fetch, including index/owner keys.
const STEP_INPUT_BYTES: usize = 64 * 1024;
const fn candidate_byte_limit(row_bytes: usize) -> usize {
    row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
}

fn execute_inner<M: Memory>(
    map: &Map<M>,
    entity: &EntitySchema,
    request: &Request<'_>,
    plan: &Plan<'_>,
    bounds: Option<range::Bounds>,
    mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
    mut input_bytes: Option<&mut usize>,
) -> Result<QueryPage<Vec<u8>>, Error> {
    let mut page = QueryPage {
        rows: Vec::new(),
        next: None,
        examined: 0,
        fetched: 0,
        output_bytes: 0,
    };
    let Some(bounds) = bounds else {
        return Ok(page);
    };
    let terminal = range::terminal_key(&bounds, plan.descending);
    let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
    let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
        Some(distinct::Collection::new(
            plan.projection.ok_or(Error::InvalidQuery)?,
            key_fields,
        ))
    } else {
        None
    };
    let mut sorted = plan
        .sort
        .as_ref()
        .map(|_| sort::Collection::new(request, plan.distinct));
    let mut component = Vec::new();
    let mut right_component = Vec::new();
    // Only suppress a class already emitted by this traversal.
    let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
        distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
    } else {
        None
    };
    let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
    let primary_type = entity.fields[plan.primary].value;
    let needs_spans = plan.index.is_some()
        || plan.span_fields != 0
        || match &aggregate {
            Some(accumulator) => accumulator.needs_spans(),
            None => plan.projection.is_some(),
        };
    // Inspection overwrites every declared field's span, including absent fields.
    let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
    while let Some(entry) = if plan.descending {
        entries.next_back()
    } else {
        entries.next()
    } {
        // An exhausted iterator proves completion even at the candidate budget.
        // Refuse another entry before inspecting its key, value or owner.
        if page.examined == request.work {
            return Err(Error::Limit);
        }
        page.examined += 1;
        let stored_key = entry.key();
        let mut read_bytes = stored_key.len();
        let (owner, bytes) = if plan.index.is_some() {
            let owner_bytes = entry.value();
            read_bytes += owner_bytes.len();
            read_index_owner(map, entity.id, primary_type, &owner_bytes)?
        } else {
            (
                RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
                entry.value(),
            )
        };
        if let Some(used) = input_bytes.as_deref_mut() {
            read_bytes += bytes.len();
            if read_bytes > candidate_bytes {
                return Err(Error::Corrupt);
            }
            *used += read_bytes;
        }
        page.fetched += 1;
        let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
        entity.inspect_fields(
            &bytes,
            plan.selected,
            &mut values,
            needs_spans.then_some(&mut spans),
        )?;
        if plan.index.is_some() {
            validate_index_entry(
                entity,
                &entity.row_info(&values, &bytes, &spans)?,
                owner,
                stored_key,
            )?;
        } else if RowKey::from_index(values[plan.primary])? != owner {
            return Err(Error::Corrupt);
        }
        let read = |position: usize, member: Option<crate::member::RecordMember>| {
            if let Some(member) = member {
                let (start, end) = spans[position];
                member.read(
                    &bytes[usize::from(start)..usize::from(end)],
                    entity.fields[position].optional,
                )
            } else {
                Ok(values[position])
            }
        };
        let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
            let mut value = values[term.position];
            component.clear();
            let (operand, optional) = match &term.operand {
                TermOperand::Nested {
                    member,
                    literal,
                    absent,
                } => {
                    value = read(term.position, Some(*member))?;
                    if *absent {
                        return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
                    }
                    (
                        Some(literal.as_slice()),
                        entity.fields[term.position].optional || member.field().optional,
                    )
                }
                TermOperand::Literal { absent: true, .. } => {
                    let absent = if plan.span_fields & (1 << term.position) != 0 {
                        bytes[usize::from(spans[term.position].0)] == 0
                    } else {
                        value == IndexValue::Absent
                    };

                    return Ok(term.comparison.accepts_absent(absent));
                }
                TermOperand::Member { item, needle } => {
                    let needle = match (needle, supplied) {
                        (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
                        (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
                            read(*right, *member)?
                        }
                        _ => return Err(Error::Corrupt),
                    };
                    if needle == IndexValue::Absent {
                        return Ok(false);
                    }
                    let (start, end) = spans[term.position];

                    return contains_member(
                        &bytes[usize::from(start)..usize::from(end)],
                        entity.fields[term.position].optional,
                        *item,
                        needle,
                    );
                }
                TermOperand::Length { member, threshold } => {
                    let (start, end) = spans[term.position];
                    let span = &bytes[usize::from(start)..usize::from(end)];
                    let optional = entity.fields[term.position].optional;
                    let actual = if let Some(member) = member {
                        match member.read(span, optional)? {
                            IndexValue::Absent => None,
                            value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
                        }
                    } else {
                        crate::codec::validated_length(span, optional)
                    };

                    return Ok(term.comparison.accepts_length(actual, *threshold));
                }
                TermOperand::Literal {
                    bytes,
                    absent: false,
                } => (
                    Some(bytes.as_slice()),
                    entity.fields[term.position].optional,
                ),
                TermOperand::Field {
                    right,
                    left_member,
                    right_member,
                } => {
                    value = read(term.position, *left_member)?;
                    let rhs = read(*right, *right_member)?;
                    if value == IndexValue::Absent || rhs == IndexValue::Absent {
                        return Ok(term.comparison.accepts_absent(value == rhs));
                    }
                    if let Some(matches) = term.comparison.accepts_values(value, rhs) {
                        return Ok(matches);
                    }
                    right_component.clear();
                    rhs.append_component(false, &mut right_component);

                    (Some(right_component.as_slice()), false)
                }
            };
            if let QueryOperand::Literal(right) = supplied
                && let Some(matches) = term.comparison.accepts_values(value, *right)
            {
                return Ok(matches);
            }
            value.append_component(optional, &mut component);

            Ok(term.comparison.accepts(
                (value != IndexValue::Absent).then_some(component.as_slice()),
                operand,
                optional,
            ))
        };
        let matches = 'matches: {
            let mut clause_matches = false;
            for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
                clause_matches = clause_matches || accepts(term, &predicate.operand)?;
                if !term.or_next {
                    if !clause_matches {
                        break 'matches false;
                    }
                    clause_matches = false;
                }
            }

            true
        };
        let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
        let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
        if matches && let Some(accumulator) = aggregate.as_mut() {
            accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
            if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
                // One validated match proves existence, even at the work boundary.
                return Ok(page);
            }
        } else if matches && let Some(collection) = collected.as_mut() {
            collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
            // First occurrences follow traversal order, so first() can finish here.
            if request.single_result_probe == Some(SingleResult::First) {
                break;
            }
        } else if matches && let Some(collection) = sorted.as_mut() {
            collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
            // Later candidates can change the top two, but cannot make them one result.
            request.check_result_count(collection.result_count())?;
        } else if matches && !duplicate {
            request.check_result_count(page.rows.len() + 1)?;
            let size = plan
                .projection
                .map_or(bytes.len(), |mask| projection_size(&spans, mask));
            if size > request.bytes {
                return Err(Error::RowTooLarge);
            }
            if size > request.bytes - page.output_bytes {
                page.next = Some(plan.cursor(stored_key, Resume::Retry));

                return Ok(page);
            }
            page.output_bytes += size;
            if let Some(mask) = plan.projection {
                page.rows.push(copy_projection(&bytes, &spans, mask, size));
            } else {
                page.rows.push(bytes);
            }
            if request.single_result_probe == Some(SingleResult::First)
                || plan.distinct.finishes_on_match(plan.fixed_components)
            {
                return Ok(page);
            }
            if let Some(boundary) = boundary {
                previous = Some(boundary.to_vec());
            }
        }
        if page.rows.len() == request.rows
            || page.examined == request.work
            || input_bytes
                .as_deref()
                .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
        {
            if terminal == Some(stored_key) {
                break;
            }
            if request.single_result_probe.is_some()
                || (aggregate.is_some() && input_bytes.is_none())
                || collected.is_some()
                || sorted.is_some()
            {
                // A complete result can use the final work unit. The next iteration
                // either observes exhaustion or refuses the extra candidate.
                continue;
            }
            let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
                Resume::AfterUnemittedClass
            } else {
                Resume::After
            };
            page.next = Some(plan.cursor(stored_key, resume));

            return Ok(page);
        }
    }
    if let Some(collection) = collected {
        page.output_bytes = collection.output_bytes;
        page.rows = collection.rows;
    }
    if let Some(collection) = sorted {
        collection.finish(request.bytes, &mut page)?;
    }

    Ok(page)
}