Skip to main content

ic_db/store/query/
mod.rs

1//! Bounded fluent traversal. Typed result construction stays outside shared execution.
2
3mod aggregate;
4mod distinct;
5mod order;
6mod probe;
7mod range;
8mod select;
9mod sort;
10pub use select::{Column, SelectColumns, SelectedQuery, Selection};
11
12pub use aggregate::{
13    Aggregate, GroupCount, GroupOrder, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue,
14    SummaryMeasure,
15    jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
16};
17
18use super::{
19    Database, ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, Map, prefix, read_index_owner,
20    validate_index_entry,
21};
22use crate::{
23    Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
24    codec::Decoder, key, named_schema::TypeGraph, primary::RowKey,
25};
26use ic_storage::Memory;
27use sha2::{Digest, Sha256};
28use std::{
29    cell::{Ref, RefCell},
30    marker::PhantomData,
31    ops::Deref,
32    rc::Rc,
33};
34
35const MAX_TERMS: usize = 8;
36const MAX_WORK: usize = 512;
37const MAX_OUTPUT: usize = 128 * 1024;
38const MAX_COMPARISON_KEY: usize = 4096;
39const MAX_DISTINCT_VALUES: usize = 32;
40const MAX_STATE_BYTES: usize = 128 * 1024;
41
42/// Direction of one field in an explicit result order.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum SortDirection {
45    /// Smaller values first; absence precedes present values.
46    Ascending,
47    /// Larger values first; absence follows present values.
48    Descending,
49}
50
51/// Exact comparison. Equality distinguishes absent values; ranges and pattern matches require presence.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53#[repr(u8)]
54pub enum Comparison {
55    /// Equal, including two absent values.
56    Eq = 0,
57    /// Not equal, including absent versus present.
58    Ne = 1,
59    /// Present and less than the present operand.
60    Lt = 2,
61    /// Present and less than or equal to the present operand.
62    Le = 3,
63    /// Present and greater than the present operand.
64    Gt = 4,
65    /// Present and greater than or equal to the present operand.
66    Ge = 5,
67    /// Present Text or Blob starts with an exact operand of the same type.
68    /// Text uses UTF-8 bytes without normalization; Blob uses raw bytes.
69    /// Empty prefixes match all present values, including empty values; other types refuse.
70    StartsWith = 6,
71    /// Present Text or Blob ends with an exact operand of the same type.
72    /// Empty suffixes match all present values; text is not normalized.
73    EndsWith = 7,
74    /// A present list or set contains an equal scalar member, or a present Text
75    /// or Blob contains the exact byte sequence of the same type.
76    /// Empty substring needles match every present Text/Blob. Text uses UTF-8 without normalization.
77    Contains = 8,
78}
79
80impl Comparison {
81    fn supports_record_member(self) -> bool {
82        self.is_relational() || matches!(self, Self::StartsWith | Self::EndsWith)
83    }
84
85    fn is_relational(self) -> bool {
86        matches!(
87            self,
88            Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
89        )
90    }
91
92    fn supports_scalar(self, field: FieldType) -> bool {
93        self.is_relational()
94            || matches!(
95                key::operand_type(field),
96                FieldType::Text { .. } | FieldType::Blob { .. }
97            )
98    }
99
100    fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
101        value.admit(field, optional)?;
102        if !self.supports_scalar(field) {
103            return Err(Error::InvalidQuery);
104        }
105        if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
106            return Err(Error::InvalidOperand);
107        }
108
109        Ok(())
110    }
111
112    fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
113        if actual.is_none() {
114            return self.accepts_absent(operand.is_none());
115        }
116
117        match self {
118            Self::Eq => actual == operand,
119            Self::Ne => actual != operand,
120            Self::StartsWith | Self::EndsWith | Self::Contains => {
121                // Compare escaped content, never the presence byte or terminator.
122                // In particular, optional empty text must not match suffix U+0001.
123                fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
124                    crate::key::bytes_prefix(key.get(usize::from(optional)..)?)
125                }
126
127                actual
128                    .and_then(|key| content(key, optional))
129                    .zip(operand.and_then(|key| content(key, optional)))
130                    .is_some_and(|(actual, operand)| match self {
131                        // Prefixes start at a component boundary: escaping each
132                        // byte preserves prefix identity for Text and Blob alike.
133                        Self::StartsWith => actual.starts_with(operand),
134                        // A suffix starting after 00 starts inside an escaped zero
135                        // (00 FF), not at a raw-byte boundary. This matters for Blob
136                        // operands beginning FF; valid UTF-8 cannot begin there.
137                        Self::EndsWith => actual
138                            .strip_suffix(operand)
139                            .is_some_and(|prefix| prefix.last() != Some(&0)),
140                        _ => contains_component(actual, operand),
141                    })
142            }
143            _ if actual.is_none() || operand.is_none() => false,
144            Self::Lt => actual < operand,
145            Self::Le => actual <= operand,
146            Self::Gt => actual > operand,
147            Self::Ge => actual >= operand,
148        }
149    }
150
151    // Residual predicates have typed operands. Only non-byte ordering needs an encoded key.
152    fn accepts_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
153        match self {
154            Self::Eq => Some(equal_values(left, right)),
155            Self::Ne => Some(!equal_values(left, right)),
156            _ => Some(self.accepts_bytes(scalar_bytes(left)?, scalar_bytes(right)?)),
157        }
158    }
159
160    // Planning compares admitted literals with the same absence and key order as traversal.
161    fn accepts_fixed_values(self, left: IndexValue<'_>, right: IndexValue<'_>) -> Option<bool> {
162        if left == IndexValue::Absent || right == IndexValue::Absent {
163            return Some(self.accepts_absent(left == right));
164        }
165        if let Some(result) = self.accepts_values(left, right) {
166            return Some(result);
167        }
168        match self {
169            Comparison::Lt | Comparison::Le | Comparison::Gt | Comparison::Ge => {
170                // Other admitted scalars use the declared component order.
171                let mut encoded = Vec::new();
172                left.append_component(false, &mut encoded);
173                let split = encoded.len();
174                right.append_component(false, &mut encoded);
175                let (left, right) = encoded.split_at(split);
176
177                Some(self.accepts(Some(left), Some(right), false))
178            }
179            _ => None,
180        }
181    }
182
183    // Text and Blob operands borrowed from rows or fixed query values are already unframed.
184    fn accepts_bytes(self, actual: &[u8], operand: &[u8]) -> bool {
185        match self {
186            Self::StartsWith => actual.starts_with(operand),
187            Self::EndsWith => actual.ends_with(operand),
188            Self::Contains => memchr::memmem::find(actual, operand).is_some(),
189            _ => self.accepts(Some(actual), Some(operand), false),
190        }
191    }
192
193    fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
194        let encoded = actual.map(u32::to_be_bytes);
195
196        self.accepts(
197            encoded.as_ref().map(|v| v.as_slice()),
198            Some(&threshold.to_be_bytes()),
199            false,
200        )
201    }
202
203    // These byte-length predicates admit exactly one present scalar value.
204    fn empty_length_value(self, threshold: u32, field: FieldType) -> Option<IndexValue<'static>> {
205        if !matches!((self, threshold), (Self::Eq | Self::Le, 0) | (Self::Lt, 1)) {
206            return None;
207        }
208        match key::operand_type(field) {
209            FieldType::Text { .. } => Some(IndexValue::Text("")),
210            FieldType::Blob { .. } => Some(IndexValue::Blob(&[])),
211            _ => None,
212        }
213    }
214
215    // A result is uniform only when every integer in the inclusive interval agrees.
216    fn uniform_length_result(self, min: u32, max: u32, n: u32) -> Option<bool> {
217        match self {
218            Self::Eq | Self::Ne if min == max || n < min || n > max => {
219                Some(self.accepts_length(Some(min), n))
220            }
221            Self::Lt | Self::Ge if max < n || min >= n => Some(self.accepts_length(Some(min), n)),
222            Self::Le | Self::Gt if max <= n || min > n => Some(self.accepts_length(Some(min), n)),
223            _ => None,
224        }
225    }
226
227    // One side is absent. Equality/inequality are symmetric; execution,
228    // presence-only filters and sparse membership share this rule.
229    fn accepts_absent(self, other_absent: bool) -> bool {
230        match self {
231            Self::Eq => other_absent,
232            Self::Ne => !other_absent,
233            _ => false,
234        }
235    }
236}
237
238// Both slices are validated component contents with presence/terminator removed.
239fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
240    let Some(start) = memchr::memmem::find(actual, needle) else {
241        return false;
242    };
243    if start == 0 || actual[start - 1] != 0 {
244        return true;
245    }
246    // Only a Blob needle starting FF can match inside an escaped zero (00 FF).
247    // A valid overlapping match may follow. One raw search avoids repeatedly
248    // scanning long prefixes. Each temporary is bounded by the row byte limit.
249    fn raw(content: &[u8]) -> Vec<u8> {
250        let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
251        let mut encoded = content.iter();
252        while let Some(&byte) = encoded.next() {
253            bytes.push(byte);
254            if byte == 0 {
255                encoded.next();
256            }
257        }
258
259        bytes
260    }
261
262    memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
263}
264
265/// A bounded logical position, bound to database, schema, query and direction.
266/// It is not an authorization token or a snapshot. Callers may choose positions;
267/// the database revalidates all claims and retains no trusted progress counters.
268#[derive(Clone, Debug, PartialEq, Eq)]
269pub struct QueryCursor {
270    binding: [u8; 32],
271    position: Vec<u8>,
272    resume: Resume,
273}
274
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276enum Resume {
277    After = 0,
278    Retry = 1,
279    AfterUnemittedClass = 2,
280}
281impl QueryCursor {
282    pub(crate) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
283
284    /// Encode the bounded continuation for an application's transport.
285    #[must_use]
286    pub fn to_bytes(&self) -> Vec<u8> {
287        let mut bytes = vec![1, self.resume as u8];
288        bytes.extend(self.binding);
289        bytes.extend(&self.position);
290
291        bytes
292    }
293
294    /// Decode framing; execution additionally checks query identity and key shape.
295    /// # Errors
296    /// Refuses unsupported versions, flags and oversized or incomplete frames.
297    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
298        if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 {
299            return Err(Error::InvalidCursor);
300        }
301
302        Ok(Self {
303            binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
304            position: bytes[34..].to_vec(),
305            resume: match bytes[1] {
306                0 => Resume::After,
307                1 => Resume::Retry,
308                2 => Resume::AfterUnemittedClass,
309                _ => return Err(Error::InvalidCursor),
310            },
311        })
312    }
313}
314
315impl serde::Serialize for QueryCursor {
316    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
317        serializer.serialize_bytes(&self.to_bytes())
318    }
319}
320
321impl<'de> serde::Deserialize<'de> for QueryCursor {
322    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
323        struct Frame;
324
325        impl<'de> serde::de::Visitor<'de> for Frame {
326            type Value = QueryCursor;
327
328            fn expecting(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
329                fmt.write_str("a bounded IC DB query cursor frame")
330            }
331
332            fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<QueryCursor, E> {
333                QueryCursor::from_bytes(bytes).map_err(E::custom)
334            }
335
336            fn visit_seq<A: serde::de::SeqAccess<'de>>(
337                self,
338                mut seq: A,
339            ) -> Result<QueryCursor, A::Error> {
340                let size = seq.size_hint().unwrap_or(0);
341                if size > QueryCursor::MAX_ENCODED_BYTES {
342                    return Err(serde::de::Error::custom(Error::InvalidCursor));
343                }
344                let mut frame = Vec::with_capacity(size);
345                while let Some(byte) = seq.next_element()? {
346                    if frame.len() == QueryCursor::MAX_ENCODED_BYTES {
347                        return Err(serde::de::Error::custom(Error::InvalidCursor));
348                    }
349                    frame.push(byte);
350                }
351                QueryCursor::from_bytes(&frame).map_err(serde::de::Error::custom)
352            }
353        }
354
355        deserializer.deserialize_bytes(Frame)
356    }
357}
358
359/// A bounded page. Empty rows do not mean completion when `next` is present.
360/// Ordinary queries are live; maintenance source pages read frozen input.
361#[derive(Debug)]
362pub struct QueryPage<T> {
363    /// Matching results in the selected total order.
364    pub rows: Vec<T>,
365    /// Resume position; only None establishes completion.
366    pub next: Option<QueryCursor>,
367    /// Examined primary/index candidates, including residual nonmatches and retries.
368    pub examined: usize,
369    /// Rows fetched; tracked separately from index candidates.
370    pub fetched: usize,
371    /// Sum of returned encoded entity/projected-record bytes, excluding transport overhead.
372    pub output_bytes: usize,
373}
374
375impl QueryPage<Vec<u8>> {
376    #[inline(never)]
377    pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
378        Ok(QueryPage {
379            rows: self
380                .rows
381                .iter()
382                .map(|bytes| E::decode(bytes))
383                .collect::<Result<_, _>>()?,
384            next: self.next,
385            examined: self.examined,
386            fetched: self.fetched,
387            output_bytes: self.output_bytes,
388        })
389    }
390
391    #[inline(never)]
392    fn decode_with<R>(
393        self,
394        decode: impl Fn(&mut Decoder<'_>) -> Result<R, Error>,
395    ) -> Result<QueryPage<R>, Error> {
396        Ok(QueryPage {
397            rows: self
398                .rows
399                .iter()
400                .map(|bytes| {
401                    let mut reader = Decoder::new(bytes)?;
402                    // Output records replace the entity root, not an extra nested value.
403                    let row = decode(&mut reader)?;
404                    reader.finish()?;
405
406                    Ok(row)
407                })
408                .collect::<Result<_, Error>>()?,
409            next: self.next,
410            examined: self.examined,
411            fetched: self.fetched,
412            output_bytes: self.output_bytes,
413        })
414    }
415}
416
417/// A literal, row field or length threshold in a fluent predicate.
418#[derive(Clone, Copy, Debug, PartialEq, Eq)]
419pub enum QueryOperand<'a> {
420    /// Compare with this exact typed value.
421    Literal(IndexValue<'a>),
422    /// Compare the field's byte length (Text/Blob) or item count (list/set/map).
423    Length(u32),
424    /// Compare with another field or supported direct record member on the same row.
425    Field(&'a str),
426}
427
428struct Predicate<'a> {
429    field: &'a str,
430    comparison: Comparison,
431    operand: QueryOperand<'a>,
432    // Consecutive alternatives form one clause; clauses are ANDed.
433    or_next: bool,
434}
435
436impl<'a> Predicate<'a> {
437    // The opposite operand of a field-to-field comparison, in either spelling.
438    fn compared_field(&self, name: &str) -> Option<&'a str> {
439        let QueryOperand::Field(right) = self.operand else {
440            return None;
441        };
442        if self.field == name {
443            Some(right)
444        } else if right == name {
445            Some(self.field)
446        } else {
447            None
448        }
449    }
450
451    // Endpoints of admitted present scalar values. Text and Blob have an empty minimum.
452    fn at_extreme(&self, entity: &EntitySchema, value: IndexValue<'_>, upper: bool) -> bool {
453        match value {
454            IndexValue::Bool(b) => b == upper,
455            IndexValue::UnitEnum { ordinal, .. } => entity
456                .index_field(self.field)
457                .is_some_and(|field| key::is_fixed_extreme(field.value, &[ordinal], upper)),
458            IndexValue::Text("") | IndexValue::Blob([]) => !upper,
459            _ => value.is_integer_extreme(upper),
460        }
461    }
462
463    // The only field value that can satisfy this predicate, when known.
464    fn fixed_equality(&self, entity: &EntitySchema) -> Option<(&'a str, IndexValue<'a>)> {
465        if let QueryOperand::Length(n) = self.operand {
466            let empty = self
467                .comparison
468                .empty_length_value(n, entity.index_field(self.field)?.value)?;
469            return Some((self.field, empty));
470        }
471        let QueryOperand::Literal(value) = self.operand else {
472            return None;
473        };
474        // Ordered comparisons exclude absence, including on optional fields.
475        let fixed = match (self.comparison, value) {
476            (Comparison::Eq, _) => value,
477            (Comparison::Ne, IndexValue::Bool(excluded))
478                if entity.field_is_required(self.field) =>
479            {
480                IndexValue::Bool(!excluded)
481            }
482            (cmp @ (Comparison::Ge | Comparison::Le), _)
483                if self.at_extreme(entity, value, cmp == Comparison::Ge) =>
484            {
485                value
486            }
487            (Comparison::Gt, IndexValue::Bool(false)) => IndexValue::Bool(true),
488            (Comparison::Lt, IndexValue::Bool(true)) => IndexValue::Bool(false),
489            _ => return None,
490        };
491        Some((self.field, fixed))
492    }
493
494    // Each of these predicates matches exactly the rows where the field is present.
495    fn tests_presence(&self, entity: &EntitySchema, operand: &TermOperand) -> bool {
496        match (self.comparison, self.operand) {
497            (Comparison::Ne, QueryOperand::Literal(IndexValue::Absent)) => true,
498            (cmp @ (Comparison::Le | Comparison::Ge), QueryOperand::Literal(value)) => {
499                self.at_extreme(entity, value, cmp == Comparison::Le)
500            }
501            (_, QueryOperand::Length(_)) => {
502                self.present_length_result(entity) == Some(true)
503                    && self.comparison != Comparison::Ne
504            }
505            (
506                Comparison::Le
507                | Comparison::Ge
508                | Comparison::StartsWith
509                | Comparison::EndsWith
510                | Comparison::Contains,
511                QueryOperand::Field(right),
512            ) => right == self.field,
513            (
514                Comparison::StartsWith | Comparison::EndsWith | Comparison::Contains,
515                QueryOperand::Literal(needle),
516            ) => {
517                // An empty Text/Blob collection member still requires a matching element.
518                !matches!(operand, TermOperand::Member { .. })
519                    && scalar_bytes(needle).is_some_and(<[u8]>::is_empty)
520            }
521            _ => false,
522        }
523    }
524
525    // Result for every present length in the declared inclusive range, if uniform.
526    fn present_length_result(&self, entity: &EntitySchema) -> Option<bool> {
527        let QueryOperand::Length(n) = self.operand else {
528            return None;
529        };
530        let max = length_limit(entity.index_field(self.field)?.value)?;
531        self.comparison.uniform_length_result(0, max, n)
532    }
533
534    fn constant_comparison(&self, entity: &EntitySchema) -> Option<bool> {
535        if let QueryOperand::Literal(value) = self.operand {
536            // Absence also fails these comparisons at the edges of the present domain.
537            return match (self.comparison, value) {
538                (cmp @ (Comparison::Lt | Comparison::Gt), value)
539                    if self.at_extreme(entity, value, cmp == Comparison::Gt) =>
540                {
541                    Some(false)
542                }
543                _ => None,
544            };
545        }
546        if matches!(self.operand, QueryOperand::Length(_)) {
547            let result = self.present_length_result(entity)?;
548            return (result == self.comparison.accepts_absent(false)
549                || entity.field_is_required(self.field))
550            .then_some(result);
551        }
552        if !matches!(self.operand, QueryOperand::Field(right) if right == self.field) {
553            return None;
554        }
555        match self.comparison {
556            Comparison::Eq => Some(true),
557            Comparison::Ne | Comparison::Lt | Comparison::Gt => Some(false),
558            _ => None,
559        }
560    }
561}
562
563#[derive(Clone, Copy, PartialEq, Eq)]
564enum SingleResult {
565    First,
566    Only,
567}
568
569struct Request<'a> {
570    groups: aggregate::GroupRequest<'a>,
571    predicates: Vec<Predicate<'a>>,
572    index: Option<(&'a str, Vec<IndexValue<'a>>)>,
573    order: Option<Vec<&'a str>>,
574    order_descending: u8,
575    descending: bool,
576    distinct: bool,
577    single_result_probe: Option<SingleResult>,
578    rows: usize,
579    work: usize,
580    bytes: usize,
581    cursor: Option<&'a QueryCursor>,
582    over_limit: bool,
583}
584
585impl Default for Request<'_> {
586    fn default() -> Self {
587        Self {
588            groups: aggregate::GroupRequest::default(),
589            predicates: Vec::new(),
590            index: None,
591            order: None,
592            order_descending: 0,
593            descending: false,
594            distinct: false,
595            single_result_probe: None,
596            rows: 32,
597            work: 128,
598            bytes: MAX_OUTPUT,
599            cursor: None,
600            over_limit: false,
601        }
602    }
603}
604
605// Request construction depends on operand shapes, not the entity's Rust type.
606// Keep allocation and clause loops out of every typed builder instantiation.
607impl<'a> Request<'a> {
608    // A single-result probe never returns two rows. Once both are proven,
609    // the second needs no space in the response.
610    fn check_result_count(&self, count: usize) -> Result<(), Error> {
611        if self.single_result_probe == Some(SingleResult::Only) && count > 1 {
612            return Err(Error::MultipleMatches);
613        }
614        Ok(())
615    }
616
617    // Every surviving alternative must fix the same field to the same value.
618    fn fixed_equalities<'r>(
619        &'r self,
620        entity: &'r EntitySchema,
621    ) -> impl Iterator<Item = (&'a str, IndexValue<'a>)> + 'r {
622        self.clauses().filter_map(move |clause| {
623            let (predicate, rest) = clause.split_first()?;
624            if !rest.is_empty() {
625                let mut candidate = predicate.fixed_equality(entity)?;
626                for alternative in rest {
627                    let other = alternative.fixed_equality(entity)?;
628                    if candidate.0 != other.0 {
629                        return None;
630                    }
631                    if equal_values(candidate.1, other.1) {
632                        continue;
633                    }
634                    if self.predicates.len() == clause.len() {
635                        return None;
636                    }
637                    if self.excludes_literal(other.0, other.1) {
638                        continue;
639                    }
640                    if !self.excludes_literal(candidate.0, candidate.1) {
641                        return None;
642                    }
643                    candidate = other;
644                }
645                // If every alternative was excluded, the retained candidate
646                // contradicts a mandatory clause during admission.
647                return Some(candidate);
648            }
649            if let Some(equality) = predicate.fixed_equality(entity) {
650                return Some(equality);
651            }
652            // A mandatory lower and upper bound can isolate one value. Only
653            // integers and admitted unit enums have a proven successor here. Keep the original terms
654            // for row evaluation and continuation identity.
655            let QueryOperand::Literal(value) = predicate.operand else {
656                return None;
657            };
658            let lower = match predicate.comparison {
659                Comparison::Ge => value,
660                Comparison::Gt if self.predicates.len() > 1 => value.discrete_successor()?,
661                _ => return None,
662            };
663            self.clauses()
664                .any(|clause| {
665                    let [upper] = clause else { return false };
666                    if upper.field != predicate.field {
667                        return false;
668                    }
669                    match (upper.comparison, upper.operand) {
670                        (Comparison::Le, QueryOperand::Literal(value)) => {
671                            equal_values(lower, value)
672                        }
673                        (Comparison::Lt, QueryOperand::Literal(value)) => {
674                            consecutive_values(lower, value)
675                        }
676                        _ => false,
677                    }
678                })
679                .then_some((predicate.field, lower))
680        })
681    }
682
683    fn excludes_literal(&self, field: &str, value: IndexValue<'_>) -> bool {
684        // One mandatory clause rules out a candidate only if every alternative
685        // rejects that value on this field. Other fields can still satisfy an OR.
686        self.clauses().any(|clause| {
687            clause.iter().all(|predicate| {
688                if predicate.field != field {
689                    return false;
690                }
691                let QueryOperand::Literal(literal) = predicate.operand else {
692                    return false;
693                };
694                match predicate.comparison {
695                    Comparison::Eq
696                    | Comparison::Ne
697                    | Comparison::Lt
698                    | Comparison::Le
699                    | Comparison::Gt
700                    | Comparison::Ge => {
701                        predicate.comparison.accepts_fixed_values(value, literal) == Some(false)
702                    }
703                    _ => false,
704                }
705            })
706        })
707    }
708
709    fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
710        self.predicates.split_inclusive(|p| !p.or_next)
711    }
712
713    #[inline(never)]
714    fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
715        if self.predicates.len() == MAX_TERMS {
716            self.over_limit = true;
717        } else {
718            self.predicates.push(Predicate {
719                field,
720                comparison,
721                operand,
722                or_next: false,
723            });
724        }
725    }
726
727    #[inline(never)]
728    fn or_clause(
729        &mut self,
730        alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
731    ) {
732        let count = alternatives.len();
733
734        if count == 0 || count > MAX_TERMS - self.predicates.len() {
735            self.over_limit = true;
736        } else {
737            self.predicates.extend(alternatives.enumerate().map(
738                |(i, (field, comparison, operand))| Predicate {
739                    field,
740                    comparison,
741                    operand,
742                    or_next: i + 1 < count,
743                },
744            ));
745        }
746    }
747
748    #[inline(never)]
749    fn filter_not_in(
750        &mut self,
751        field: &'a str,
752        values: impl ExactSizeIterator<Item = IndexValue<'a>>,
753    ) {
754        if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
755            self.over_limit = true;
756
757            return;
758        }
759        for value in values {
760            self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
761        }
762    }
763
764    #[inline(never)]
765    fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
766        if values.len() > 4 {
767            self.over_limit = true;
768        } else {
769            self.index = Some((name, values.to_vec()));
770        }
771    }
772
773    #[inline(never)]
774    fn order_by(&mut self, fields: &[&'a str]) {
775        self.order_descending = 0;
776
777        if fields.len() > 4 {
778            self.over_limit = true;
779        } else {
780            self.order = Some(fields.to_vec());
781        }
782    }
783
784    #[inline(never)]
785    fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
786        if fields.len() > 4 {
787            self.over_limit = true;
788
789            return;
790        }
791        self.order = Some(Vec::with_capacity(fields.len()));
792        self.order_descending = 0;
793        for &(field, direction) in fields {
794            self.append_order(field, direction);
795        }
796    }
797
798    fn append_order(&mut self, field: &'a str, direction: SortDirection) {
799        let fields = self.order.get_or_insert_with(Vec::new);
800        if fields.len() == 4 {
801            self.over_limit = true;
802
803            return;
804        }
805        if direction == SortDirection::Descending {
806            self.order_descending |= 1 << fields.len();
807        }
808        fields.push(field);
809    }
810
811    fn primary_descending(&self, entity: &EntitySchema) -> bool {
812        self.order_descending != 0
813            && self.order.as_ref().is_some_and(|fields| {
814                fields.last() == Some(&entity.primary_key)
815                    && self.order_descending & (1 << (fields.len() - 1)) != 0
816            })
817    }
818}
819
820// Maintenance gets only bounded primary traversal, not a second query frontend.
821pub(super) fn source_page<M: Memory>(
822    map: &Map<M>,
823    entity: &EntitySchema,
824    binding: [u8; 32],
825    incarnation: [u8; 16],
826    cursor: Option<&QueryCursor>,
827    rows: usize,
828    bytes: usize,
829) -> Result<QueryPage<Vec<u8>>, Error> {
830    let request = Request {
831        rows,
832        work: rows,
833        bytes,
834        cursor,
835        ..Request::default()
836    };
837    let plan = Plan::admit(
838        entity,
839        &request,
840        binding,
841        incarnation,
842        None,
843        PlanOutput::Rows,
844    )?;
845
846    execute(map, entity, &request, &plan, None)
847}
848
849enum QuerySource<'a, M: Memory> {
850    Direct(&'a Database<M>),
851    Session(Rc<RefCell<Database<M>>>),
852}
853
854enum QueryRead<'a, M: Memory> {
855    Direct(&'a Database<M>),
856    Session(Ref<'a, Database<M>>),
857}
858
859impl<M: Memory> Deref for QueryRead<'_, M> {
860    type Target = Database<M>;
861
862    fn deref(&self) -> &Self::Target {
863        match self {
864            Self::Direct(db) => db,
865            Self::Session(db) => db,
866        }
867    }
868}
869
870impl<M: Memory> QuerySource<'_, M> {
871    fn read(&self) -> Result<QueryRead<'_, M>, Error> {
872        match self {
873            Self::Direct(db) => Ok(QueryRead::Direct(db)),
874            Self::Session(db) => db
875                .try_borrow()
876                .map(QueryRead::Session)
877                .map_err(|_| Error::BorrowConflict),
878        }
879    }
880}
881
882/// Fluent exact predicates over one entity. No callback executor is generated.
883/// Ordering uses primary order, an explicit index, a proven automatic path or
884/// bounded complete sorting. Work exhaustion never returns a sorted prefix.
885pub struct Query<'a, E, M: Memory> {
886    db: QuerySource<'a, M>,
887    request: Request<'a>,
888    entity: PhantomData<E>,
889}
890impl<M: Memory> Database<M> {
891    /// Begin a live primary-key-ordered query. Admission occurs on `fetch`.
892    #[must_use]
893    pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
894        Query {
895            db: QuerySource::Direct(self),
896            entity: PhantomData,
897            request: Request::default(),
898        }
899    }
900}
901impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
902    pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
903        Self {
904            db: QuerySource::Session(db),
905            request: Request::default(),
906            entity: PhantomData,
907        }
908    }
909
910    /// Remove duplicate output records. Proven leading index tuples use live
911    /// pages. Projecting the primary key or the varying fields of a unique key covering every match
912    /// needs no duplicate tracking. Other projections scan to
913    /// completion in one call, retaining at most 32 tuples within 128 KiB.
914    /// That fallback preserves first-match traversal order, refuses cursors and
915    /// returns `Limit` if work, result count or combined bytes cannot fit; it
916    /// never returns a partial result. An individually oversized row returns
917    /// `RowTooLarge`. Comparison keys are bounded to 4096 bytes.
918    /// For enumeration across calls, [`Self::start_distinct`] and [`Self::resume_distinct`]
919    /// retain up to 255 tuples within a 16 KiB job frame, then page the completed result.
920    /// Non-identity sorted DISTINCT retains the best `limit` distinct tuples. Its order
921    /// must lead with all varying projected fields. A mandatory literal equality
922    /// fixes a field. Remove duplicates before applying `limit` and output bytes.
923    #[must_use]
924    pub fn distinct(mut self) -> Self {
925        self.request.distinct = true;
926
927        self
928    }
929
930    /// Add an AND term. A top-level list or set supports exact scalar membership with `Contains`.
931    /// A direct scalar record member selected by [`crate::field_path!`] accepts
932    /// Eq, Ne, Lt, Le, Gt and Ge against a literal. Text and Blob members
933    /// also accept `StartsWith` and `EndsWith` with an operand of the same type.
934    /// Eq/Ne with `IndexValue::Absent` also accept any optional stored field,
935    /// including blobs and containers. Empty values are present, not absent.
936    /// All operands are admitted before storage reads, including contradictory terms.
937    /// On a primary traversal, mandatory Eq/Lt/Le/Gt/Ge primary-key comparisons
938    /// narrow the scanned range. On an index path, those comparisons can narrow
939    /// its first field after the admitted fixed prefix. Only examined rows
940    /// undergo integrity checks; oversized derived bounds remain residual filters.
941    /// Indexed StartsWith can seek that field's exact encoded Text/Blob prefix too.
942    #[must_use]
943    pub fn filter(
944        mut self,
945        field: &'a str,
946        comparison: Comparison,
947        value: impl Into<IndexValue<'a>>,
948    ) -> Self {
949        self.request
950            .filter(field, comparison, QueryOperand::Literal(value.into()));
951
952        self
953    }
954
955    /// Require an exact field value. Equivalent to `filter(field, Comparison::Eq, value)`.
956    #[must_use]
957    pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
958        self.filter(field, Comparison::Eq, value)
959    }
960
961    /// Require a different value, including absent versus present.
962    #[must_use]
963    pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
964        self.filter(field, Comparison::Ne, value)
965    }
966
967    /// Require a present field strictly below the supplied value.
968    #[must_use]
969    pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
970        self.filter(field, Comparison::Lt, value)
971    }
972
973    /// Require a present field at or below the supplied value.
974    #[must_use]
975    pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
976        self.filter(field, Comparison::Le, value)
977    }
978
979    /// Require a present field strictly above the supplied value.
980    #[must_use]
981    pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
982        self.filter(field, Comparison::Gt, value)
983    }
984
985    /// Require a present field at or above the supplied value.
986    #[must_use]
987    pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
988        self.filter(field, Comparison::Ge, value)
989    }
990
991    /// Compare fields on the same row. Eq, Ne, Lt, Le, Gt and Ge also accept
992    /// direct scalar record members on either side, as do StartsWith and EndsWith for Text and Blob.
993    /// Top-level lists and sets support Contains
994    /// with a present scalar field or direct record member of the element type. Text and Blob also
995    /// support StartsWith, EndsWith and Contains with a present right-hand field.
996    /// Types must match; Text and Blob bounds may differ within their respective families.
997    /// Two absent values are equal. An ordered comparison requires two present values.
998    #[must_use]
999    pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
1000        self.request
1001            .filter(left, comparison, QueryOperand::Field(right));
1002
1003        self
1004    }
1005
1006    /// Compare UTF-8 bytes for Text, raw bytes for Blob, or the item count for a
1007    /// list, set or map. A direct Text or Blob record member also supports byte
1008    /// length through [`crate::field_path!`]. Accepts Eq, Ne, Lt, Le, Gt and Ge. An absent field
1009    /// matches Ne only; use Gt(0) for a present, nonempty value.
1010    #[must_use]
1011    pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
1012        self.request
1013            .filter(field, comparison, QueryOperand::Length(length));
1014
1015        self
1016    }
1017
1018    /// Match rows whose optional field has a value, including an empty value.
1019    /// Required and unknown fields return `InvalidQuery` at admission.
1020    #[must_use]
1021    pub fn filter_present(self, field: &'a str) -> Self {
1022        self.filter(field, Comparison::Ne, IndexValue::Absent)
1023    }
1024
1025    /// Match rows whose optional field has no value.
1026    /// Required and unknown fields return `InvalidQuery` at admission.
1027    #[must_use]
1028    pub fn filter_absent(self, field: &'a str) -> Self {
1029        self.filter(field, Comparison::Eq, IndexValue::Absent)
1030    }
1031
1032    /// Match a present field inside an inclusive range, ANDed with other filters.
1033    /// Equivalent to `filter(field, Comparison::Ge, lower)` followed by
1034    /// `filter(field, Comparison::Le, upper)`, including cursor/job identity.
1035    /// Both exact operands are admitted and consume two of the eight comparisons.
1036    /// Absent operands refuse; absent fields never match. Reversed bounds produce
1037    /// no matches, without skipping admission of either operand or other filters.
1038    #[must_use]
1039    pub fn filter_between(
1040        self,
1041        field: &'a str,
1042        lower: impl Into<IndexValue<'a>>,
1043        upper: impl Into<IndexValue<'a>>,
1044    ) -> Self {
1045        self.filter(field, Comparison::Ge, lower)
1046            .filter(field, Comparison::Le, upper)
1047    }
1048
1049    /// Match a present field strictly outside an inclusive range.
1050    /// Equivalent to one `filter_any` clause containing `Lt lower` then `Gt upper`,
1051    /// including cursor/job identity. Both exact operands consume filter terms.
1052    /// Absent operands refuse and absent fields never match; this is not a general
1053    /// negation of `filter_between`. Equal bounds exclude that value; reversed
1054    /// bounds match every present value, once. Uses the existing single traversal
1055    /// and work budget, without seeking separate ranges for the two alternatives.
1056    #[must_use]
1057    pub fn filter_not_between(
1058        self,
1059        field: &'a str,
1060        lower: impl Into<IndexValue<'a>>,
1061        upper: impl Into<IndexValue<'a>>,
1062    ) -> Self {
1063        self.filter_any(&[
1064            (field, Comparison::Lt, lower.into()),
1065            (field, Comparison::Gt, upper.into()),
1066        ])
1067    }
1068
1069    /// Match `lower <= field && field <= upper` using three top-level fields of the row.
1070    /// Both comparisons require present values of compatible types. Equal endpoints
1071    /// are inclusive. Uses the same two comparison terms and continuation as the
1072    /// equivalent chained `filter_fields` calls.
1073    #[must_use]
1074    pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1075        self.filter_fields(field, Comparison::Ge, lower)
1076            .filter_fields(field, Comparison::Le, upper)
1077    }
1078
1079    /// Match `field < lower || field > upper` using fields of the same row.
1080    /// A missing bound makes only its own comparison false. A missing tested field
1081    /// never matches. Uses one OR clause and the same two comparison terms and
1082    /// continuation as the equivalent `filter_any_operands` call.
1083    #[must_use]
1084    pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
1085        self.filter_any_operands(&[
1086            (field, Comparison::Lt, QueryOperand::Field(lower)),
1087            (field, Comparison::Gt, QueryOperand::Field(upper)),
1088        ])
1089    }
1090
1091    /// Add an OR clause of literal comparisons, ANDed with other filters.
1092    /// Alternatives may compare different direct scalar members of a record.
1093    /// Each clause must contain at least one comparison; all filters together
1094    /// may contain at most eight. Empty/oversized clauses refuse with `Error::Limit`
1095    /// at execution. Every operand is admitted, even if another alternative matches.
1096    /// Uses one ordered traversal, without union scans or duplicate rows. Alternatives
1097    /// do not establish fixed index prefixes; a one-term clause behaves like `filter`.
1098    #[must_use]
1099    pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
1100        self.request.or_clause(
1101            alternatives
1102                .iter()
1103                .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
1104        );
1105
1106        self
1107    }
1108
1109    /// Add one OR clause of literal, field-to-field or length comparisons.
1110    /// Each alternative follows its corresponding single-filter admission rules.
1111    /// All alternatives share the eight-comparison budget with the other filters.
1112    /// Literal-only clauses have the same cursor and job identity as `filter_any`.
1113    #[must_use]
1114    pub fn filter_any_operands(
1115        mut self,
1116        alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
1117    ) -> Self {
1118        self.request.or_clause(alternatives.iter().copied());
1119
1120        self
1121    }
1122
1123    /// Match a field against any supplied exact value, ANDed with other filters.
1124    /// Equivalent to `filter_any` with equality comparisons in the supplied order.
1125    /// Include `None` in a slice of optional values to match an absent field.
1126    /// When the field is the next traversal key component, seek between the smallest
1127    /// and largest member, including all tied owners. Interior candidates still consume work.
1128    /// Repeated members never repeat rows, but each counts toward the shared
1129    /// eight-comparison limit. Empty or oversized lists refuse with `Error::Limit`.
1130    /// Every member is admitted before reading; there is no coercion, sorting or
1131    /// deduplication of operands. Reordering members changes cursor/job identity.
1132    #[must_use]
1133    pub fn filter_in(
1134        mut self,
1135        field: &'a str,
1136        values: &[impl Copy + Into<IndexValue<'a>>],
1137    ) -> Self {
1138        self.request.or_clause(
1139            values
1140                .iter()
1141                .copied()
1142                .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1143        );
1144
1145        self
1146    }
1147
1148    /// Exclude every supplied exact value, ANDed with other filters.
1149    /// Equivalent to consecutive `filter(field, Comparison::Ne, value)` calls
1150    /// in the supplied order. Absent fields match unless absence is explicitly
1151    /// excluded. Empty lists refuse; all members, including duplicates, count
1152    /// toward the shared eight-comparison budget. Every operand is admitted.
1153    /// The equivalent inequality chain shares cursor/job identity; reordering
1154    /// the list changes that identity. No coercion or deduplication is performed.
1155    #[must_use]
1156    pub fn filter_not_in(
1157        mut self,
1158        field: &'a str,
1159        values: &[impl Copy + Into<IndexValue<'a>>],
1160    ) -> Self {
1161        self.request
1162            .filter_not_in(field, values.iter().copied().map(Into::into));
1163
1164        self
1165    }
1166
1167    /// Select index order and exact leading components (at most four).
1168    /// All rows matching this prefix are considered. Sparse indexes require
1169    /// every optional indexed component to be proven present by the prefix or
1170    /// filters. Every alternative in a proving OR clause must reject absence.
1171    #[must_use]
1172    pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1173        self.request.using_index(name, values);
1174
1175        self
1176    }
1177
1178    /// Append an ascending sort field. Earlier fields take precedence.
1179    /// The same field, work and continuation rules as [`Self::order_by_each`] apply.
1180    #[must_use]
1181    pub fn order_asc(mut self, field: &'a str) -> Self {
1182        self.request.append_order(field, SortDirection::Ascending);
1183
1184        self
1185    }
1186
1187    /// Append a descending sort field. An implicit primary-key tie-breaker
1188    /// stays ascending; append the primary key explicitly to choose its direction.
1189    #[must_use]
1190    pub fn order_desc(mut self, field: &'a str) -> Self {
1191        self.request.append_order(field, SortDirection::Descending);
1192
1193        self
1194    }
1195
1196    /// Replace the current order with 1..=4 distinct ordered scalar fields, then the primary key.
1197    /// A direct record member can be selected with [`crate::field_path!`].
1198    /// An explicitly listed primary key must be last. All fields share one
1199    /// direction, reversed by `descending`. Prefer a complete ordered path.
1200    /// Otherwise scan to completion while retaining the best `limit` rows within
1201    /// 128 KiB of key/output buffers, then sort them. Non-identity DISTINCT retains
1202    /// the best `limit` distinct tuples. Work exhaustion refuses; no
1203    /// cursor is supported by this fallback. DISTINCT requires an identity result
1204    /// or an order led by all varying projected fields. Equality terms may fix
1205    /// leading index components. With `using_index`, require that path's order.
1206    #[must_use]
1207    pub fn order_by(mut self, fields: &[&'a str]) -> Self {
1208        self.request.order_by(fields);
1209
1210        self
1211    }
1212
1213    /// Replace the order with 1..=4 fields and their individual directions.
1214    /// An explicit primary key must be last; otherwise append it ascending.
1215    /// `descending()` reverses every direction, including that tie-breaker.
1216    /// The same path proof and complete-sort bounds as `order_by` apply.
1217    #[must_use]
1218    pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
1219        self.request.order_by_each(fields);
1220
1221        self
1222    }
1223
1224    /// Reverse the complete result order, including its unique tie-breaker.
1225    #[must_use]
1226    pub fn descending(mut self) -> Self {
1227        self.request.descending = true;
1228
1229        self
1230    }
1231
1232    /// Return at most 1..=32 matching rows in this page.
1233    /// Complete-collection DISTINCT refuses if the full result exceeds this cap.
1234    /// Complete sorting examines the entire admitted input and retains at most
1235    /// the requested number of winners, even when many more rows match.
1236    /// For grouped aggregates, cap the complete selected result instead; use
1237    /// `group_page` to set a retained grouped response's page size separately.
1238    #[must_use]
1239    pub fn limit(mut self, rows: usize) -> Self {
1240        self.request.rows = rows;
1241
1242        self
1243    }
1244
1245    /// Examine at most 1..=512 candidates, independently of the returned row limit.
1246    #[must_use]
1247    pub fn work_limit(mut self, candidates: usize) -> Self {
1248        self.request.work = candidates;
1249
1250        self
1251    }
1252
1253    /// Exercise output exhaustion with a small response in qualification fixtures.
1254    #[cfg(feature = "test-support")]
1255    #[doc(hidden)]
1256    #[must_use]
1257    pub fn test_output_limit(mut self, bytes: usize) -> Self {
1258        self.request.bytes = bytes;
1259
1260        self
1261    }
1262
1263    /// Continue this query; page resource limits may change between calls.
1264    #[must_use]
1265    pub fn after(self, cursor: &'a QueryCursor) -> Self {
1266        self.after_optional(Some(cursor))
1267    }
1268
1269    /// Set the continuation cursor. Passing `None` selects the first page.
1270    #[must_use]
1271    pub fn after_optional(mut self, cursor: Option<&'a QueryCursor>) -> Self {
1272        self.request.cursor = cursor;
1273
1274        self
1275    }
1276
1277    /// Admit and execute one page, then decode only its matching output rows.
1278    /// # Errors
1279    /// Refuses unsupported shapes, inexact operands, limits, invalid cursors and corruption.
1280    /// A selected output row larger than the whole byte allowance returns `RowTooLarge`.
1281    /// # Panics
1282    /// Supplier corruption traps without repair, as for direct record reads.
1283    pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1284        observe!(query, { self.entity_page() })
1285    }
1286
1287    fn entity_page(self) -> Result<QueryPage<E>, Error> {
1288        fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
1289    }
1290
1291    /// Return the first matching entity in query order, or `None` on a proven miss.
1292    /// Uses a one-row page. For partial pages with resumable progress use `fetch`.
1293    /// # Errors
1294    /// Returns the same admission and storage errors as `fetch`. Returns `Limit`
1295    /// if the work budget ends before a match or exhaustion is established.
1296    pub fn first(self) -> Result<Option<E>, Error> {
1297        self.first_with(Self::entity_page)
1298    }
1299
1300    /// Return the first projected record in query order.
1301    /// # Errors
1302    /// Applies the projection checks of [`Self::fetch_as`] and the work bound of [`Self::first`].
1303    pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1304        self.first_with(Self::projected_page::<R>)
1305    }
1306
1307    fn first_with<R>(
1308        self,
1309        fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1310    ) -> Result<Option<R>, Error> {
1311        observe!(query, { fetch(self.probe_matches(SingleResult::First)?) })
1312            .map(|mut page| page.rows.pop())
1313    }
1314
1315    /// Return the only match, or `None` when the query is exhausted without one.
1316    /// A valid row limit is overridden to probe for two matches. Applies to the
1317    /// whole query, so a continuation is refused.
1318    /// # Errors
1319    /// Returns `MultipleMatches` on a second match and `Limit` if the page is
1320    /// incomplete before cardinality is known. Ordinary fetch errors apply.
1321    pub fn try_one(self) -> Result<Option<E>, Error> {
1322        self.try_one_with(Self::entity_page)
1323    }
1324
1325    /// Return the sole projected result, or `None` on a proven miss.
1326    /// With DISTINCT, a literal equality or fixed index prefix covering every
1327    /// projected field lets an ordered traversal finish at the first match.
1328    /// # Errors
1329    /// Applies the projection checks of [`Self::fetch_as`] and the cardinality checks of [`Self::try_one`].
1330    pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1331        self.try_one_with(Self::projected_page::<R>)
1332    }
1333
1334    fn try_one_with<R>(
1335        self,
1336        fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1337    ) -> Result<Option<R>, Error> {
1338        observe!(query, {
1339            if self.request.cursor.is_some() {
1340                return Err(Error::InvalidQuery);
1341            }
1342            fetch(self.probe_matches(SingleResult::Only)?)
1343        })
1344        .map(|mut page| page.rows.pop())
1345    }
1346
1347    fn probe_matches(mut self, probe: SingleResult) -> Result<Self, Error> {
1348        if !(1..=32).contains(&self.request.rows) {
1349            return Err(Error::Limit);
1350        }
1351
1352        self.request.single_result_probe = Some(probe);
1353
1354        Ok(self.limit(match probe {
1355            SingleResult::First => 1,
1356            SingleResult::Only => 2,
1357        }))
1358    }
1359
1360    /// Project matching top-level fields into an existing `#[record]` type.
1361    /// Names, optionality and complete value definitions must match exactly.
1362    /// The record is an output shape, not a new stored entity or schema entry.
1363    /// Byte limits count projected bytes; all source fields still undergo validation.
1364    /// # Errors
1365    /// Refuses non-record/empty or incompatible output shapes, and the same failures
1366    /// as `fetch`. A continuation must use the same selected field shape.
1367    /// # Panics
1368    /// Supplier corruption traps without repair, as for direct record reads.
1369    pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1370        observe!(query, { self.projected_page() })
1371    }
1372
1373    fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1374        let raw = fetch_rows(
1375            &*self.db.read()?,
1376            E::SCHEMA,
1377            self.request,
1378            Some(Projection::Record(R::definition())),
1379        )?;
1380
1381        raw.decode_with(R::decode_from)
1382    }
1383}
1384
1385#[derive(Clone, Copy)]
1386enum Projection<'a> {
1387    Record(&'a TypeSchema),
1388    Columns(&'a [u8]),
1389}
1390
1391impl Projection<'_> {
1392    fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1393        match self {
1394            Self::Record(record) => admit_projection(entity, record),
1395            Self::Columns(columns) => {
1396                let mut mask = 0;
1397                for &column in columns {
1398                    if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1399                        return Err(Error::InvalidQuery);
1400                    }
1401                    mask |= 1 << column;
1402                }
1403                Ok(mask)
1404            }
1405        }
1406    }
1407}
1408
1409// Reuse named-record metadata/codecs rather than a second value tree or a
1410// generic executor per output shape. The full transitive graph matters: named
1411// links compare by identity, which alone cannot establish codec compatibility.
1412fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1413    let TypeBody::Record(fields) = &output.body else {
1414        return Err(Error::InvalidQuery);
1415    };
1416    if fields.is_empty()
1417        || fields.len() > crate::schema::MAX_FIELDS
1418        || fields.windows(2).any(|w| w[0].name >= w[1].name)
1419    {
1420        return Err(Error::InvalidQuery);
1421    }
1422    let mut source = TypeGraph::default();
1423    let mut target = TypeGraph::default();
1424    let mut mask = 0;
1425    for field in *fields {
1426        let position = entity
1427            .field_position(field.name)
1428            .ok_or(Error::InvalidQuery)?;
1429        let stored = &entity.fields[position];
1430        if stored.value != field.value || stored.optional != field.optional {
1431            return Err(Error::InvalidQuery);
1432        }
1433        source
1434            .include(stored.value)
1435            .map_err(|_| Error::InvalidQuery)?;
1436        target
1437            .include(field.value)
1438            .map_err(|_| Error::InvalidQuery)?;
1439        mask |= 1 << position;
1440    }
1441    if !source.contains(&target) {
1442        return Err(Error::InvalidQuery);
1443    }
1444
1445    Ok(mask)
1446}
1447
1448struct Term {
1449    tests_presence: bool,
1450    position: usize,
1451    comparison: Comparison,
1452    operand: TermOperand,
1453    or_next: bool,
1454}
1455
1456enum TermOperand {
1457    Literal {
1458        bytes: Vec<u8>,
1459        absent: bool,
1460    },
1461    Member {
1462        item: FieldType,
1463        needle: MemberNeedle,
1464    },
1465    Nested {
1466        member: crate::member::RecordMember,
1467        literal: Vec<u8>,
1468        absent: bool,
1469    },
1470    Field {
1471        right: usize,
1472        left_member: Option<crate::member::RecordMember>,
1473        right_member: Option<crate::member::RecordMember>,
1474    },
1475    Length {
1476        member: Option<crate::member::RecordMember>,
1477        threshold: u32,
1478    },
1479}
1480
1481enum MemberNeedle {
1482    Literal(Vec<u8>),
1483    Field(usize, Option<crate::member::RecordMember>),
1484}
1485
1486// Operands have already been type-checked. Text and Blob literals carry their
1487// original bytes, before the durable key codec escapes embedded zeros.
1488fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1489    match value {
1490        IndexValue::Text(text) => Some(text.as_bytes()),
1491        IndexValue::Blob(bytes) => Some(bytes),
1492        _ => None,
1493    }
1494}
1495
1496fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1497    low.discrete_successor()
1498        .is_some_and(|next| equal_values(next, high))
1499}
1500
1501fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1502    // Admission already checked both enum contracts.
1503    match (left, right) {
1504        (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1505            a == b
1506        }
1507        _ => left == right,
1508    }
1509}
1510
1511fn length_limit(field: FieldType) -> Option<u32> {
1512    match key::operand_type(field) {
1513        FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1514        FieldType::List { max_items, .. } => Some(max_items),
1515        FieldType::Named(link) => match (link.definition)().body {
1516            TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1517            _ => None,
1518        },
1519        _ => None,
1520    }
1521}
1522
1523fn member_type(field: FieldType) -> Option<FieldType> {
1524    match key::operand_type(field) {
1525        FieldType::List { item, .. } => Some(*item),
1526        FieldType::Named(link) => match (link.definition)().body {
1527            TypeBody::Set { item, .. } => Some(item),
1528            _ => None,
1529        },
1530        _ => None,
1531    }
1532}
1533
1534// inspect_fields has already validated every item, including the tail after a match.
1535fn contains_member(
1536    span: &[u8],
1537    optional: bool,
1538    item: FieldType,
1539    needle: IndexValue<'_>,
1540) -> Result<bool, Error> {
1541    let mut reader = Decoder::new(span)?;
1542    if optional && !reader.boolean()? {
1543        return Ok(false);
1544    }
1545    for _ in 0..reader.nat32()? {
1546        let value = IndexValue::read(&mut reader, item)?;
1547        if equal_values(value, needle) {
1548            return Ok(true);
1549        }
1550    }
1551
1552    Ok(false)
1553}
1554
1555// Admission sets bits only for fields in this entity. Consuming the lowest
1556// bit first preserves the canonical field order of projected records and keys.
1557fn projection_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1558    std::iter::from_fn(move || {
1559        if mask == 0 {
1560            return None;
1561        }
1562        let position = mask.trailing_zeros() as usize;
1563        mask &= mask - 1;
1564        Some(position)
1565    })
1566}
1567
1568fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1569    for i in projection_positions(mask) {
1570        if !key::supports(entity.fields[i].value) {
1571            return Err(Error::InvalidQuery);
1572        }
1573    }
1574
1575    Ok(())
1576}
1577
1578// Grouping, distinct counts and collected DISTINCT share exact tuple equality.
1579fn comparison_key(
1580    entity: &EntitySchema,
1581    mask: u32,
1582    values: &[IndexValue<'_>],
1583    scratch: &mut Vec<u8>,
1584) -> Result<(), Error> {
1585    build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1586}
1587
1588fn build_comparison_key<'a>(
1589    entity: &EntitySchema,
1590    mask: u32,
1591    key: &mut Vec<u8>,
1592    mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1593) -> Result<(), Error> {
1594    key.clear();
1595    for i in projection_positions(mask) {
1596        let field = &entity.fields[i];
1597        value(i, field)?.append_component(field.optional, key);
1598        if key.len() > MAX_COMPARISON_KEY {
1599            return Err(Error::Limit);
1600        }
1601    }
1602
1603    Ok(())
1604}
1605
1606fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1607    if size > limit {
1608        return Err(Error::RowTooLarge);
1609    }
1610    if size > limit - *used {
1611        return Err(Error::Limit);
1612    }
1613    *used += size;
1614
1615    Ok(())
1616}
1617
1618// Size and copy already validated projection spans using the same field mask.
1619fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1620    projection_positions(mask)
1621        .map(|i| {
1622            let (start, end) = spans[i];
1623            usize::from(end - start)
1624        })
1625        .sum()
1626}
1627
1628fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1629    let mut output = Vec::with_capacity(size);
1630    for i in projection_positions(mask) {
1631        let (start, end) = spans[i];
1632        output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1633    }
1634
1635    output
1636}
1637#[derive(Clone, Copy)]
1638enum PlanOutput {
1639    Rows,
1640    Aggregate { grouped: bool },
1641}
1642
1643struct Plan<'a> {
1644    primary: usize,
1645    index: Option<&'a IndexSchema>,
1646    prefix: Vec<u8>,
1647    fixed_components: usize,
1648    terms: Vec<Term>,
1649    selected: u32,
1650    // Non-orderable fields need only their validated optional tags, never key slots.
1651    span_fields: u32,
1652    binding: [u8; 32],
1653    projection: Option<u32>,
1654    distinct: distinct::Strategy,
1655    sort: Option<Vec<order::SortField>>,
1656    descending: bool,
1657}
1658impl<'a> Plan<'a> {
1659    fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1660        self.terms.split_inclusive(|term| !term.or_next)
1661    }
1662
1663    fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1664        self.index = Some(path.index);
1665        self.prefix = path.prefix;
1666        self.fixed_components = path.fixed;
1667        self.selected |= entity.key_fields();
1668    }
1669
1670    fn admit(
1671        entity: &'a EntitySchema,
1672        request: &Request<'_>,
1673        schema: [u8; 32],
1674        incarnation: [u8; 16],
1675        projection: Option<Projection<'_>>,
1676        output: PlanOutput,
1677    ) -> Result<Self, Error> {
1678        if request.over_limit
1679            || !(1..=32).contains(&request.rows)
1680            || !(1..=MAX_WORK).contains(&request.work)
1681            || !(1..=MAX_OUTPUT).contains(&request.bytes)
1682        {
1683            return Err(Error::Limit);
1684        }
1685        if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1686        {
1687            return Err(Error::InvalidQuery);
1688        }
1689        // Bound literal encoding even when a declaration's maximum exceeds one row.
1690        for value in request
1691            .predicates
1692            .iter()
1693            .filter_map(|p| match &p.operand {
1694                QueryOperand::Literal(value) => Some(value),
1695                QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1696            })
1697            .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1698        {
1699            if match value {
1700                IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1701                IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1702                _ => false,
1703            } {
1704                return Err(Error::Limit);
1705            }
1706        }
1707        let primary = entity
1708            .field_position(entity.primary_key)
1709            .filter(|&i| !entity.fields[i].optional)
1710            .ok_or(Error::InvalidQuery)?;
1711        let mut plan = Self {
1712            primary,
1713            index: None,
1714            prefix: prefix(2, entity.id, &[]),
1715            fixed_components: 0,
1716            terms: Vec::new(),
1717            selected: 1 << primary,
1718            span_fields: 0,
1719            binding: [0; 32],
1720            projection: projection.map(|output| output.mask(entity)).transpose()?,
1721            distinct: distinct::Strategy::Identity,
1722            sort: None,
1723            descending: request.descending ^ request.primary_descending(entity),
1724        };
1725        for predicate in &request.predicates {
1726            let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1727            let field = &entity.fields[position];
1728            let member = if predicate.comparison == Comparison::Contains {
1729                member_type(field.value)
1730            } else {
1731                None
1732            };
1733            let operand = match (predicate.operand, record_member) {
1734                (QueryOperand::Literal(value), Some(member)) => {
1735                    if !predicate.comparison.supports_record_member() {
1736                        return Err(Error::InvalidQuery);
1737                    }
1738                    let leaf = member.field();
1739                    predicate.comparison.admit(
1740                        leaf.value,
1741                        field.optional || leaf.optional,
1742                        value,
1743                    )?;
1744                    let mut literal = Vec::new();
1745                    value.append_component(field.optional || leaf.optional, &mut literal);
1746                    plan.span_fields |= 1 << position;
1747                    TermOperand::Nested {
1748                        member,
1749                        literal,
1750                        absent: value == IndexValue::Absent,
1751                    }
1752                }
1753                (QueryOperand::Length(length), member) => {
1754                    let selected = member.map_or(field.value, |m| m.field().value);
1755                    if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1756                        return Err(Error::InvalidQuery);
1757                    }
1758                    plan.span_fields |= 1 << position;
1759
1760                    TermOperand::Length {
1761                        member,
1762                        threshold: length,
1763                    }
1764                }
1765                (QueryOperand::Field(name), left_member) => {
1766                    let (right, right_member) = crate::member::resolve_field(entity, name)?;
1767                    if (left_member.is_some() || right_member.is_some())
1768                        && member.is_none()
1769                        && !predicate.comparison.supports_record_member()
1770                    {
1771                        return Err(Error::InvalidQuery);
1772                    }
1773                    let right_type =
1774                        right_member.map_or(entity.fields[right].value, |m| m.field().value);
1775                    let left_type =
1776                        left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1777                    let compatible = left_type == right_type
1778                        || matches!(
1779                            (left_type, right_type),
1780                            (FieldType::Text { .. }, FieldType::Text { .. })
1781                                | (FieldType::Blob { .. }, FieldType::Blob { .. })
1782                        );
1783                    if !compatible
1784                        || !key::supports(left_type)
1785                        || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1786                    {
1787                        return Err(Error::InvalidQuery);
1788                    }
1789                    if right_member.is_some() {
1790                        plan.span_fields |= 1 << right;
1791                    } else {
1792                        plan.selected |= 1 << right;
1793                    }
1794
1795                    if let Some(item) = member {
1796                        plan.span_fields |= 1 << position;
1797
1798                        TermOperand::Member {
1799                            item,
1800                            needle: MemberNeedle::Field(right, right_member),
1801                        }
1802                    } else {
1803                        if left_member.is_some() {
1804                            plan.span_fields |= 1 << position;
1805                        } else {
1806                            plan.selected |= 1 << position;
1807                        }
1808                        TermOperand::Field {
1809                            right,
1810                            left_member,
1811                            right_member,
1812                        }
1813                    }
1814                }
1815                (QueryOperand::Literal(value), None) => {
1816                    if let Some(item) = member {
1817                        if !key::supports(item) {
1818                            return Err(Error::InvalidQuery);
1819                        }
1820                        value.admit(item, false)?;
1821                        let mut bytes = Vec::new();
1822                        value.append_component(false, &mut bytes);
1823                        plan.span_fields |= 1 << position;
1824
1825                        TermOperand::Member {
1826                            item,
1827                            needle: MemberNeedle::Literal(bytes),
1828                        }
1829                    } else {
1830                        let absent = value == IndexValue::Absent;
1831                        if key::supports(field.value) {
1832                            plan.selected |= 1 << position;
1833                        } else if absent
1834                            && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1835                        {
1836                            plan.span_fields |= 1 << position;
1837                        } else {
1838                            return Err(Error::InvalidQuery);
1839                        }
1840                        predicate
1841                            .comparison
1842                            .admit(field.value, field.optional, value)?;
1843                        let mut bytes = Vec::new();
1844                        value.append_component(field.optional, &mut bytes);
1845
1846                        TermOperand::Literal { bytes, absent }
1847                    }
1848                }
1849            };
1850            plan.terms.push(Term {
1851                tests_presence: predicate.tests_presence(entity, &operand),
1852                position,
1853                comparison: predicate.comparison,
1854                operand,
1855                or_next: predicate.or_next,
1856            });
1857        }
1858        // Admit every operand before selecting a path, even for empty or
1859        // contradictory queries. The scanner consumes this one proven choice.
1860        match order::select(entity, request, output)? {
1861            order::Path::Primary => {}
1862            order::Path::Index(path, descending) => {
1863                plan.use_index(entity, path);
1864                plan.descending = request.descending ^ descending;
1865            }
1866            order::Path::Filtered { sort } => {
1867                order::select_filtered_path(entity, request, &mut plan, None)?;
1868                for field in sort.iter().flatten() {
1869                    if field.member.is_some() {
1870                        plan.span_fields |= 1 << field.position;
1871                    } else {
1872                        plan.selected |= 1 << field.position;
1873                    }
1874                }
1875                plan.sort = sort;
1876            }
1877        }
1878        if request.distinct {
1879            plan.distinct = distinct::admit(entity, request, &plan)?;
1880            match plan.distinct {
1881                distinct::Strategy::FirstMatch => plan.sort = None,
1882                distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1883                _ => {}
1884            }
1885        }
1886        let mut hash = Sha256::new();
1887        hash.update(b"ic-db:query:v1\0");
1888        hash.update(schema);
1889        hash.update(incarnation);
1890        hash.update([u8::from(request.descending)]);
1891        hash.update((plan.prefix.len() as u32).to_le_bytes());
1892        hash.update(&plan.prefix);
1893        for term in &plan.terms {
1894            hash.update([term.position as u8, term.comparison as u8]);
1895
1896            match &term.operand {
1897                TermOperand::Nested {
1898                    member,
1899                    literal,
1900                    absent,
1901                } => {
1902                    hash.update((u32::MAX - 2).to_le_bytes());
1903                    hash.update([member.position() as u8, u8::from(*absent)]);
1904                    // The binding already records absence separately from the scalar payload.
1905                    let literal = &literal[usize::from(
1906                        entity.fields[term.position].optional || member.field().optional,
1907                    )..];
1908                    hash.update((literal.len() as u32).to_le_bytes());
1909                    hash.update(literal);
1910                }
1911                TermOperand::Literal { bytes, .. }
1912                | TermOperand::Member {
1913                    needle: MemberNeedle::Literal(bytes),
1914                    ..
1915                } => {
1916                    hash.update((bytes.len() as u32).to_le_bytes());
1917                    hash.update(bytes);
1918                }
1919                TermOperand::Length { member, threshold } => {
1920                    if let Some(member) = member {
1921                        hash.update((u32::MAX - 3).to_le_bytes());
1922                        hash.update([member.position() as u8]);
1923                    } else {
1924                        hash.update((u32::MAX - 1).to_le_bytes());
1925                    }
1926                    hash.update(threshold.to_le_bytes());
1927                }
1928                TermOperand::Field {
1929                    right,
1930                    left_member: None,
1931                    right_member: None,
1932                }
1933                | TermOperand::Member {
1934                    needle: MemberNeedle::Field(right, None),
1935                    ..
1936                } => {
1937                    // Outside the bounded literal length domain.
1938                    hash.update(u32::MAX.to_le_bytes());
1939                    hash.update([*right as u8]);
1940                }
1941                TermOperand::Member {
1942                    needle: MemberNeedle::Field(right, Some(member)),
1943                    ..
1944                } => {
1945                    hash.update((u32::MAX - 4).to_le_bytes());
1946                    hash.update([u8::MAX, *right as u8, member.position() as u8]);
1947                }
1948                TermOperand::Field {
1949                    right,
1950                    left_member,
1951                    right_member,
1952                } => {
1953                    hash.update((u32::MAX - 4).to_le_bytes());
1954                    let slot = |member: &Option<crate::member::RecordMember>| {
1955                        member.map_or(u8::MAX, |m| m.position() as u8)
1956                    };
1957                    hash.update([slot(left_member), *right as u8, slot(right_member)]);
1958                }
1959            }
1960        }
1961        // Keep existing conjunction identities unchanged. A bounded clause mask
1962        // distinguishes OR grouping without persisting another predicate model.
1963        let clauses = plan
1964            .terms
1965            .iter()
1966            .enumerate()
1967            .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1968        if clauses != 0 {
1969            hash.update(b"or-clauses\0");
1970            hash.update([clauses]);
1971        }
1972        if let Some(order) = &request.order {
1973            hash.update(b"order\0");
1974            hash.update([order.len() as u8]);
1975            for name in order {
1976                // Field names were admitted by order selection above.
1977                if let Some(position) = entity.field_position(name) {
1978                    hash.update([position as u8]);
1979                } else {
1980                    // A top-level position is at most 31. Frame each admitted nested path.
1981                    hash.update([u8::MAX, name.len() as u8]);
1982                    hash.update(name.as_bytes());
1983                }
1984            }
1985        }
1986        if request.order_descending != 0 {
1987            hash.update(b"order-directions\0");
1988            hash.update([request.order_descending]);
1989        }
1990        // Preserve existing entity-result cursors. Projected shapes add a
1991        // domain-separated suffix; output Rust names do not change semantics.
1992        if let Some(mask) = plan.projection {
1993            hash.update(b"projection\0");
1994            hash.update(mask.to_le_bytes());
1995            if let Some(Projection::Columns(columns)) = projection {
1996                hash.update(b"columns\0");
1997                hash.update(columns);
1998            }
1999        }
2000        if request.distinct {
2001            hash.update(b"distinct\0");
2002        }
2003        plan.binding = hash.finalize().into();
2004        if let Some(cursor) = request.cursor {
2005            if cursor.binding != plan.binding {
2006                return Err(Error::InvalidCursor);
2007            }
2008            plan.validate_position(entity, cursor)
2009                .map_err(|_| Error::InvalidCursor)?;
2010        }
2011
2012        Ok(plan)
2013    }
2014
2015    fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
2016        if cursor.resume == Resume::AfterUnemittedClass
2017            && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
2018        {
2019            return Err(Error::InvalidCursor);
2020        }
2021        let bytes = cursor.position.as_slice();
2022        if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
2023            return Err(Error::InvalidCursor);
2024        }
2025        if let Some(index) = self.index {
2026            let mut remaining = bytes
2027                .get(INDEX_PREFIX_BYTES..)
2028                .ok_or(Error::InvalidCursor)?;
2029            for name in index.fields {
2030                consume_index_component(entity, index, name, &mut remaining)?;
2031            }
2032            if !index.unique {
2033                key::consume(&mut remaining, entity.key_type()?)?;
2034            }
2035            if !remaining.is_empty() {
2036                return Err(Error::InvalidCursor);
2037            }
2038        } else {
2039            RowKey::decode(
2040                bytes
2041                    .get(ENTITY_PREFIX_BYTES..)
2042                    .ok_or(Error::InvalidCursor)?,
2043                entity.key_type()?,
2044            )?;
2045        }
2046
2047        Ok(())
2048    }
2049
2050    fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
2051        QueryCursor {
2052            binding: self.binding,
2053            position: position.to_vec(),
2054            resume,
2055        }
2056    }
2057}
2058
2059// Cursor framing and DISTINCT equivalence boundaries use the same key decoder.
2060fn consume_index_component(
2061    entity: &EntitySchema,
2062    index: &IndexSchema,
2063    name: &str,
2064    remaining: &mut &[u8],
2065) -> Result<(), Error> {
2066    let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
2067
2068    key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
2069}
2070
2071// Admission, execution and request cleanup share one entity-independent boundary.
2072// Only conversion of the returned bytes remains in the typed public terminals.
2073#[inline(never)]
2074#[expect(
2075    clippy::needless_pass_by_value,
2076    reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
2077)]
2078fn fetch_rows<M: Memory>(
2079    db: &Database<M>,
2080    entity: &EntitySchema,
2081    request: Request<'_>,
2082    projection: Option<Projection<'_>>,
2083) -> Result<QueryPage<Vec<u8>>, Error> {
2084    db.schema.admits(entity)?;
2085    let plan = Plan::admit(
2086        entity,
2087        &request,
2088        db.schema.fingerprint(),
2089        db.incarnation,
2090        projection,
2091        PlanOutput::Rows,
2092    )?;
2093
2094    execute(&db.map, entity, &request, &plan, None)
2095}
2096
2097fn execute<M: Memory>(
2098    map: &Map<M>,
2099    entity: &EntitySchema,
2100    request: &Request<'_>,
2101    plan: &Plan<'_>,
2102    mut aggregate: Option<aggregate::Accumulator<'_>>,
2103) -> Result<QueryPage<Vec<u8>>, Error> {
2104    execute_inner(
2105        map,
2106        entity,
2107        request,
2108        plan,
2109        range::bounds(entity, request, plan)?,
2110        aggregate.as_mut(),
2111        None,
2112    )
2113}
2114
2115// Retained aggregates use the same traversal, but checkpoint at a work boundary.
2116// Reserve a maximum candidate before the next fetch, including index/owner keys.
2117const STEP_INPUT_BYTES: usize = 64 * 1024;
2118const fn candidate_byte_limit(row_bytes: usize) -> usize {
2119    row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
2120}
2121
2122fn execute_inner<M: Memory>(
2123    map: &Map<M>,
2124    entity: &EntitySchema,
2125    request: &Request<'_>,
2126    plan: &Plan<'_>,
2127    bounds: Option<range::Bounds>,
2128    mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
2129    mut input_bytes: Option<&mut usize>,
2130) -> Result<QueryPage<Vec<u8>>, Error> {
2131    let mut page = QueryPage {
2132        rows: Vec::new(),
2133        next: None,
2134        examined: 0,
2135        fetched: 0,
2136        output_bytes: 0,
2137    };
2138    let Some(bounds) = bounds else {
2139        return Ok(page);
2140    };
2141    let terminal = range::terminal_key(&bounds, plan.descending);
2142    let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
2143    let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
2144        Some(distinct::Collection::new(
2145            plan.projection.ok_or(Error::InvalidQuery)?,
2146            key_fields,
2147        ))
2148    } else {
2149        None
2150    };
2151    let mut sorted = plan
2152        .sort
2153        .as_ref()
2154        .map(|_| sort::Collection::new(request, plan.distinct));
2155    let mut component = Vec::new();
2156    let mut right_component = Vec::new();
2157    // Only suppress a class already emitted by this traversal.
2158    let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
2159        distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
2160    } else {
2161        None
2162    };
2163    let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
2164    let primary_type = entity.fields[plan.primary].value;
2165    let needs_spans = plan.index.is_some()
2166        || plan.span_fields != 0
2167        || match &aggregate {
2168            Some(accumulator) => accumulator.needs_spans(),
2169            None => plan.projection.is_some(),
2170        };
2171    // Inspection overwrites every declared field's span, including absent fields.
2172    let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
2173    while let Some(entry) = if plan.descending {
2174        entries.next_back()
2175    } else {
2176        entries.next()
2177    } {
2178        // An exhausted iterator proves completion even at the candidate budget.
2179        // Refuse another entry before inspecting its key, value or owner.
2180        if page.examined == request.work {
2181            return Err(Error::Limit);
2182        }
2183        page.examined += 1;
2184        let stored_key = entry.key();
2185        let mut read_bytes = stored_key.len();
2186        let (owner, bytes) = if plan.index.is_some() {
2187            let owner_bytes = entry.value();
2188            read_bytes += owner_bytes.len();
2189            read_index_owner(map, entity.id, primary_type, &owner_bytes)?
2190        } else {
2191            (
2192                RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
2193                entry.value(),
2194            )
2195        };
2196        if let Some(used) = input_bytes.as_deref_mut() {
2197            read_bytes += bytes.len();
2198            if read_bytes > candidate_bytes {
2199                return Err(Error::Corrupt);
2200            }
2201            *used += read_bytes;
2202        }
2203        page.fetched += 1;
2204        let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
2205        entity.inspect_fields(
2206            &bytes,
2207            plan.selected,
2208            &mut values,
2209            needs_spans.then_some(&mut spans),
2210        )?;
2211        if plan.index.is_some() {
2212            validate_index_entry(
2213                entity,
2214                &entity.row_info(&values, &bytes, &spans)?,
2215                owner,
2216                stored_key,
2217            )?;
2218        } else if RowKey::from_index(values[plan.primary])? != owner {
2219            return Err(Error::Corrupt);
2220        }
2221        let read = |position: usize, member: Option<crate::member::RecordMember>| {
2222            if let Some(member) = member {
2223                let (start, end) = spans[position];
2224                member.read(
2225                    &bytes[usize::from(start)..usize::from(end)],
2226                    entity.fields[position].optional,
2227                )
2228            } else {
2229                Ok(values[position])
2230            }
2231        };
2232        let mut accepts = |term: &Term, supplied: &QueryOperand<'_>| -> Result<bool, Error> {
2233            let mut value = values[term.position];
2234            component.clear();
2235            let (operand, optional) = match &term.operand {
2236                TermOperand::Nested {
2237                    member,
2238                    literal,
2239                    absent,
2240                } => {
2241                    value = read(term.position, Some(*member))?;
2242                    if *absent {
2243                        return Ok(term.comparison.accepts_absent(value == IndexValue::Absent));
2244                    }
2245                    (
2246                        Some(literal.as_slice()),
2247                        entity.fields[term.position].optional || member.field().optional,
2248                    )
2249                }
2250                TermOperand::Literal { absent: true, .. } => {
2251                    let absent = if plan.span_fields & (1 << term.position) != 0 {
2252                        bytes[usize::from(spans[term.position].0)] == 0
2253                    } else {
2254                        value == IndexValue::Absent
2255                    };
2256
2257                    return Ok(term.comparison.accepts_absent(absent));
2258                }
2259                TermOperand::Member { item, needle } => {
2260                    let needle = match (needle, supplied) {
2261                        (MemberNeedle::Literal(_), QueryOperand::Literal(value)) => *value,
2262                        (MemberNeedle::Field(right, member), QueryOperand::Field(_)) => {
2263                            read(*right, *member)?
2264                        }
2265                        _ => return Err(Error::Corrupt),
2266                    };
2267                    if needle == IndexValue::Absent {
2268                        return Ok(false);
2269                    }
2270                    let (start, end) = spans[term.position];
2271
2272                    return contains_member(
2273                        &bytes[usize::from(start)..usize::from(end)],
2274                        entity.fields[term.position].optional,
2275                        *item,
2276                        needle,
2277                    );
2278                }
2279                TermOperand::Length { member, threshold } => {
2280                    let (start, end) = spans[term.position];
2281                    let span = &bytes[usize::from(start)..usize::from(end)];
2282                    let optional = entity.fields[term.position].optional;
2283                    let actual = if let Some(member) = member {
2284                        match member.read(span, optional)? {
2285                            IndexValue::Absent => None,
2286                            value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
2287                        }
2288                    } else {
2289                        crate::codec::validated_length(span, optional)
2290                    };
2291
2292                    return Ok(term.comparison.accepts_length(actual, *threshold));
2293                }
2294                TermOperand::Literal {
2295                    bytes,
2296                    absent: false,
2297                } => (
2298                    Some(bytes.as_slice()),
2299                    entity.fields[term.position].optional,
2300                ),
2301                TermOperand::Field {
2302                    right,
2303                    left_member,
2304                    right_member,
2305                } => {
2306                    value = read(term.position, *left_member)?;
2307                    let rhs = read(*right, *right_member)?;
2308                    if value == IndexValue::Absent || rhs == IndexValue::Absent {
2309                        return Ok(term.comparison.accepts_absent(value == rhs));
2310                    }
2311                    if let Some(matches) = term.comparison.accepts_values(value, rhs) {
2312                        return Ok(matches);
2313                    }
2314                    right_component.clear();
2315                    rhs.append_component(false, &mut right_component);
2316
2317                    (Some(right_component.as_slice()), false)
2318                }
2319            };
2320            if let QueryOperand::Literal(right) = supplied
2321                && let Some(matches) = term.comparison.accepts_values(value, *right)
2322            {
2323                return Ok(matches);
2324            }
2325            value.append_component(optional, &mut component);
2326
2327            Ok(term.comparison.accepts(
2328                (value != IndexValue::Absent).then_some(component.as_slice()),
2329                operand,
2330                optional,
2331            ))
2332        };
2333        let matches = 'matches: {
2334            let mut clause_matches = false;
2335            for (term, predicate) in plan.terms.iter().zip(&request.predicates) {
2336                clause_matches = clause_matches || accepts(term, &predicate.operand)?;
2337                if !term.or_next {
2338                    if !clause_matches {
2339                        break 'matches false;
2340                    }
2341                    clause_matches = false;
2342                }
2343            }
2344
2345            true
2346        };
2347        let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
2348        let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2349        if matches && let Some(accumulator) = aggregate.as_mut() {
2350            accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2351            if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
2352                // One validated match proves existence, even at the work boundary.
2353                return Ok(page);
2354            }
2355        } else if matches && let Some(collection) = collected.as_mut() {
2356            collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2357            // First occurrences follow traversal order, so first() can finish here.
2358            if request.single_result_probe == Some(SingleResult::First) {
2359                break;
2360            }
2361        } else if matches && let Some(collection) = sorted.as_mut() {
2362            collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2363            // Later candidates can change the top two, but cannot make them one result.
2364            request.check_result_count(collection.result_count())?;
2365        } else if matches && !duplicate {
2366            request.check_result_count(page.rows.len() + 1)?;
2367            let size = plan
2368                .projection
2369                .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2370            if size > request.bytes {
2371                return Err(Error::RowTooLarge);
2372            }
2373            if size > request.bytes - page.output_bytes {
2374                page.next = Some(plan.cursor(stored_key, Resume::Retry));
2375
2376                return Ok(page);
2377            }
2378            page.output_bytes += size;
2379            if let Some(mask) = plan.projection {
2380                page.rows.push(copy_projection(&bytes, &spans, mask, size));
2381            } else {
2382                page.rows.push(bytes);
2383            }
2384            if request.single_result_probe == Some(SingleResult::First)
2385                || plan.distinct.finishes_on_match(plan.fixed_components)
2386            {
2387                return Ok(page);
2388            }
2389            if let Some(boundary) = boundary {
2390                previous = Some(boundary.to_vec());
2391            }
2392        }
2393        if page.rows.len() == request.rows
2394            || page.examined == request.work
2395            || input_bytes
2396                .as_deref()
2397                .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2398        {
2399            if terminal == Some(stored_key) {
2400                break;
2401            }
2402            if request.single_result_probe.is_some()
2403                || (aggregate.is_some() && input_bytes.is_none())
2404                || collected.is_some()
2405                || sorted.is_some()
2406            {
2407                // A complete result can use the final work unit. The next iteration
2408                // either observes exhaustion or refuses the extra candidate.
2409                continue;
2410            }
2411            let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2412                Resume::AfterUnemittedClass
2413            } else {
2414                Resume::After
2415            };
2416            page.next = Some(plan.cursor(stored_key, resume));
2417
2418            return Ok(page);
2419        }
2420    }
2421    if let Some(collection) = collected {
2422        page.output_bytes = collection.output_bytes;
2423        page.rows = collection.rows;
2424    }
2425    if let Some(collection) = sorted {
2426        collection.finish(request.bytes, &mut page)?;
2427    }
2428
2429    Ok(page)
2430}