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