Skip to main content

ic_db/store/query/
mod.rs

1//! Bounded fluent traversal. Typed result construction stays outside shared execution.
2mod aggregate;
3mod distinct;
4mod order;
5mod range;
6mod sort;
7pub use aggregate::{
8    Aggregate, GroupCount, GroupOrder, GroupValue,
9    jobs::{AggregateJobs, GroupCursor, GroupPage, JobHandle, JobOutcome, JobStep},
10};
11
12use super::{Database, Map, prefix, row_key, validate_index_entry};
13use crate::{
14    Entity, EntitySchema, Error, FieldType, IndexSchema, IndexValue, TypeBody, TypeSchema, Value,
15    codec::Decoder, key, primary::RowKey, types::TypeGraph,
16};
17use ic_storage::Memory;
18use sha2::{Digest, Sha256};
19use std::{
20    cell::{Ref, RefCell},
21    marker::PhantomData,
22    ops::Deref,
23    rc::Rc,
24};
25
26const MAX_TERMS: usize = 8;
27const MAX_WORK: usize = 512;
28const MAX_OUTPUT: usize = 128 * 1024;
29const MAX_COMPARISON_KEY: usize = 4096;
30const MAX_DISTINCT_VALUES: usize = 32;
31const MAX_STATE_BYTES: usize = 128 * 1024;
32
33/// Direction of one field in an explicit result order.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum SortDirection {
36    /// Smaller values first; absence precedes present values.
37    Ascending,
38    /// Larger values first; absence follows present values.
39    Descending,
40}
41
42/// Exact comparison. Equality distinguishes absent values; ranges and pattern matches require presence.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44#[repr(u8)]
45pub enum Comparison {
46    /// Equal, including two absent values.
47    Eq = 0,
48    /// Not equal, including absent versus present.
49    Ne = 1,
50    /// Present and less than the present operand.
51    Lt = 2,
52    /// Present and less than or equal to the present operand.
53    Le = 3,
54    /// Present and greater than the present operand.
55    Gt = 4,
56    /// Present and greater than or equal to the present operand.
57    Ge = 5,
58    /// Present Text or Blob starts with an exact operand of the same type.
59    /// Text uses UTF-8 bytes without normalization; Blob uses raw bytes.
60    /// Empty prefixes match all present values, including empty values; other types refuse.
61    StartsWith = 6,
62    /// Present Text or Blob ends with an exact operand of the same type.
63    /// Empty suffixes match all present values; text is not normalized.
64    EndsWith = 7,
65    /// A present list or set contains an equal scalar member, or a present Text
66    /// or Blob contains the exact byte sequence of the same type.
67    /// Empty substring needles match every present Text/Blob. Text uses UTF-8 without normalization.
68    Contains = 8,
69}
70
71impl Comparison {
72    fn is_relational(self) -> bool {
73        matches!(
74            self,
75            Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge
76        )
77    }
78
79    fn supports_scalar(self, field: FieldType) -> bool {
80        self.is_relational()
81            || matches!(
82                key::operand_type(field),
83                FieldType::Text { .. } | FieldType::Blob { .. }
84            )
85    }
86
87    fn admit(self, field: FieldType, optional: bool, value: IndexValue<'_>) -> Result<(), Error> {
88        value.admit(field, optional)?;
89        if !self.supports_scalar(field) {
90            return Err(Error::InvalidQuery);
91        }
92        if value == IndexValue::Absent && !matches!(self, Self::Eq | Self::Ne) {
93            return Err(Error::InvalidOperand);
94        }
95        Ok(())
96    }
97
98    fn accepts(self, actual: Option<&[u8]>, operand: Option<&[u8]>, optional: bool) -> bool {
99        if actual.is_none() {
100            return self.accepts_absent(operand.is_none());
101        }
102        match self {
103            Self::Eq => actual == operand,
104            Self::Ne => actual != operand,
105            Self::StartsWith | Self::EndsWith | Self::Contains => {
106                // Compare escaped content, never the presence byte or terminator.
107                // In particular, optional empty text must not match suffix U+0001.
108                fn content(key: &[u8], optional: bool) -> Option<&[u8]> {
109                    key.get(usize::from(optional)..)?.strip_suffix(&[0, 0])
110                }
111                actual
112                    .and_then(|key| content(key, optional))
113                    .zip(operand.and_then(|key| content(key, optional)))
114                    .is_some_and(|(actual, operand)| match self {
115                        // Prefixes start at a component boundary: escaping each
116                        // byte preserves prefix identity for Text and Blob alike.
117                        Self::StartsWith => actual.starts_with(operand),
118                        // A suffix starting after 00 starts inside an escaped zero
119                        // (00 FF), not at a raw-byte boundary. This matters for Blob
120                        // operands beginning FF; valid UTF-8 cannot begin there.
121                        Self::EndsWith => actual
122                            .strip_suffix(operand)
123                            .is_some_and(|prefix| prefix.last() != Some(&0)),
124                        _ => contains_component(actual, operand),
125                    })
126            }
127            _ if actual.is_none() || operand.is_none() => false,
128            Self::Lt => actual < operand,
129            Self::Le => actual <= operand,
130            Self::Gt => actual > operand,
131            Self::Ge => actual >= operand,
132        }
133    }
134
135    fn accepts_length(self, actual: Option<u32>, threshold: u32) -> bool {
136        let encoded = actual.map(u32::to_be_bytes);
137
138        self.accepts(
139            encoded.as_ref().map(|v| v.as_slice()),
140            Some(&threshold.to_be_bytes()),
141            false,
142        )
143    }
144
145    // One side is absent. Equality/inequality are symmetric; execution,
146    // presence-only filters and sparse membership share this rule.
147    fn accepts_absent(self, other_absent: bool) -> bool {
148        match self {
149            Self::Eq => other_absent,
150            Self::Ne => !other_absent,
151            _ => false,
152        }
153    }
154}
155
156// Both slices are validated component contents with presence/terminator removed.
157fn contains_component(actual: &[u8], needle: &[u8]) -> bool {
158    let Some(start) = memchr::memmem::find(actual, needle) else {
159        return false;
160    };
161    if start == 0 || actual[start - 1] != 0 {
162        return true;
163    }
164    // Only a Blob needle starting FF can match inside an escaped zero (00 FF).
165    // A valid overlapping match may follow. One raw search avoids repeatedly
166    // scanning long prefixes. Each temporary is bounded by the row byte limit.
167    fn raw(content: &[u8]) -> Vec<u8> {
168        let mut bytes = Vec::with_capacity(content.len().min(crate::codec::MAX_ROW_BYTES));
169        let mut encoded = content.iter();
170        while let Some(&byte) = encoded.next() {
171            bytes.push(byte);
172            if byte == 0 {
173                encoded.next();
174            }
175        }
176        bytes
177    }
178    memchr::memmem::find(&raw(actual), &raw(needle)).is_some()
179}
180
181/// A bounded logical position, bound to database, schema, query and direction.
182/// It is not an authorization token or a snapshot. Callers may choose positions;
183/// the database revalidates all claims and retains no trusted progress counters.
184#[derive(Clone, Debug, PartialEq, Eq)]
185pub struct QueryCursor {
186    binding: [u8; 32],
187    position: Vec<u8>,
188    inclusive: bool,
189}
190impl QueryCursor {
191    pub(super) const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
192
193    /// Encode the bounded continuation for an application's transport.
194    #[must_use]
195    pub fn to_bytes(&self) -> Vec<u8> {
196        let mut bytes = vec![1, u8::from(self.inclusive)];
197        bytes.extend(self.binding);
198        bytes.extend(&self.position);
199        bytes
200    }
201
202    /// Decode framing; execution additionally checks query identity and key shape.
203    /// # Errors
204    /// Refuses unsupported versions, flags and oversized or incomplete frames.
205    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
206        if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 || bytes[1] > 1 {
207            return Err(Error::InvalidCursor);
208        }
209        Ok(Self {
210            binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
211            position: bytes[34..].to_vec(),
212            inclusive: bytes[1] == 1,
213        })
214    }
215}
216
217/// A bounded page. Empty rows do not mean completion when `next` is present.
218/// Ordinary queries are live; maintenance source pages read frozen input.
219#[derive(Debug)]
220pub struct QueryPage<T> {
221    /// Matching results in the selected total order.
222    pub rows: Vec<T>,
223    /// Resume position; only None establishes completion.
224    pub next: Option<QueryCursor>,
225    /// Examined primary/index candidates, including residual nonmatches and retries.
226    pub examined: usize,
227    /// Rows fetched; tracked separately from index candidates.
228    pub fetched: usize,
229    /// Sum of returned encoded entity/projected-record bytes, excluding transport overhead.
230    pub output_bytes: usize,
231}
232
233impl QueryPage<Vec<u8>> {
234    #[inline(never)]
235    pub(super) fn decode_entities<E: Entity>(self) -> Result<QueryPage<E>, Error> {
236        Ok(QueryPage {
237            rows: self
238                .rows
239                .iter()
240                .map(|bytes| E::decode(bytes))
241                .collect::<Result<_, _>>()?,
242            next: self.next,
243            examined: self.examined,
244            fetched: self.fetched,
245            output_bytes: self.output_bytes,
246        })
247    }
248
249    #[inline(never)]
250    fn decode_projection<R: Value>(self) -> Result<QueryPage<R>, Error> {
251        Ok(QueryPage {
252            rows: self
253                .rows
254                .iter()
255                .map(|bytes| {
256                    let mut reader = Decoder::new(bytes)?;
257                    // Output records replace the entity root, not an extra nested value.
258                    let row = R::decode_from(&mut reader)?;
259                    reader.finish()?;
260                    Ok(row)
261                })
262                .collect::<Result<_, Error>>()?,
263            next: self.next,
264            examined: self.examined,
265            fetched: self.fetched,
266            output_bytes: self.output_bytes,
267        })
268    }
269}
270
271/// A literal, row field or length threshold in a fluent predicate.
272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
273pub enum QueryOperand<'a> {
274    /// Compare with this exact typed value.
275    Literal(IndexValue<'a>),
276    /// Compare the field's byte length (Text/Blob) or item count (list/set/map).
277    Length(u32),
278    /// Compare with another top-level field on the same row.
279    Field(&'a str),
280}
281
282struct Predicate<'a> {
283    field: &'a str,
284    comparison: Comparison,
285    operand: QueryOperand<'a>,
286    // Consecutive alternatives form one clause; clauses are ANDed.
287    or_next: bool,
288}
289struct Request<'a> {
290    groups: aggregate::GroupRequest<'a>,
291    predicates: Vec<Predicate<'a>>,
292    index: Option<(&'a str, Vec<IndexValue<'a>>)>,
293    order: Option<Vec<&'a str>>,
294    order_descending: u8,
295    descending: bool,
296    distinct: bool,
297    rows: usize,
298    work: usize,
299    bytes: usize,
300    cursor: Option<&'a QueryCursor>,
301    over_limit: bool,
302}
303
304impl Default for Request<'_> {
305    fn default() -> Self {
306        Self {
307            groups: aggregate::GroupRequest::default(),
308            predicates: Vec::new(),
309            index: None,
310            order: None,
311            order_descending: 0,
312            descending: false,
313            distinct: false,
314            rows: 32,
315            work: 128,
316            bytes: MAX_OUTPUT,
317            cursor: None,
318            over_limit: false,
319        }
320    }
321}
322
323// Request construction depends on operand shapes, not the entity's Rust type.
324// Keep allocation and clause loops out of every typed builder instantiation.
325impl<'a> Request<'a> {
326    fn clauses(&self) -> impl Iterator<Item = &[Predicate<'a>]> {
327        self.predicates.split_inclusive(|p| !p.or_next)
328    }
329
330    #[inline(never)]
331    fn filter(&mut self, field: &'a str, comparison: Comparison, operand: QueryOperand<'a>) {
332        if self.predicates.len() == MAX_TERMS {
333            self.over_limit = true;
334        } else {
335            self.predicates.push(Predicate {
336                field,
337                comparison,
338                operand,
339                or_next: false,
340            });
341        }
342    }
343
344    #[inline(never)]
345    fn or_clause(
346        &mut self,
347        alternatives: impl ExactSizeIterator<Item = (&'a str, Comparison, QueryOperand<'a>)>,
348    ) {
349        let count = alternatives.len();
350        if count == 0 || count > MAX_TERMS - self.predicates.len() {
351            self.over_limit = true;
352        } else {
353            self.predicates.extend(alternatives.enumerate().map(
354                |(i, (field, comparison, operand))| Predicate {
355                    field,
356                    comparison,
357                    operand,
358                    or_next: i + 1 < count,
359                },
360            ));
361        }
362    }
363
364    #[inline(never)]
365    fn filter_not_in(
366        &mut self,
367        field: &'a str,
368        values: impl ExactSizeIterator<Item = IndexValue<'a>>,
369    ) {
370        if values.len() == 0 || values.len() > MAX_TERMS - self.predicates.len() {
371            self.over_limit = true;
372            return;
373        }
374        for value in values {
375            self.filter(field, Comparison::Ne, QueryOperand::Literal(value));
376        }
377    }
378
379    #[inline(never)]
380    fn using_index(&mut self, name: &'a str, values: &[IndexValue<'a>]) {
381        if values.len() > 4 {
382            self.over_limit = true;
383        } else {
384            self.index = Some((name, values.to_vec()));
385        }
386    }
387
388    #[inline(never)]
389    fn order_by(&mut self, fields: &[&'a str]) {
390        self.order_descending = 0;
391        if fields.len() > 4 {
392            self.over_limit = true;
393        } else {
394            self.order = Some(fields.to_vec());
395        }
396    }
397
398    #[inline(never)]
399    fn order_by_each(&mut self, fields: &[(&'a str, SortDirection)]) {
400        if fields.len() > 4 {
401            self.over_limit = true;
402            return;
403        }
404        self.order = Some(Vec::with_capacity(fields.len()));
405        self.order_descending = 0;
406        for &(field, direction) in fields {
407            self.append_order(field, direction);
408        }
409    }
410
411    fn append_order(&mut self, field: &'a str, direction: SortDirection) {
412        let fields = self.order.get_or_insert_with(Vec::new);
413        if fields.len() == 4 {
414            self.over_limit = true;
415            return;
416        }
417        if direction == SortDirection::Descending {
418            self.order_descending |= 1 << fields.len();
419        }
420        fields.push(field);
421    }
422
423    fn primary_descending(&self, entity: &EntitySchema) -> bool {
424        self.order_descending != 0
425            && self.order.as_ref().is_some_and(|fields| {
426                fields.last() == Some(&entity.primary_key)
427                    && self.order_descending & (1 << (fields.len() - 1)) != 0
428            })
429    }
430}
431
432// Maintenance gets only bounded primary traversal, not a second query frontend.
433pub(super) fn source_page<M: Memory>(
434    map: &Map<M>,
435    entity: &EntitySchema,
436    binding: [u8; 32],
437    incarnation: [u8; 16],
438    cursor: Option<&QueryCursor>,
439    rows: usize,
440    bytes: usize,
441) -> Result<QueryPage<Vec<u8>>, Error> {
442    let request = Request {
443        rows,
444        work: rows,
445        bytes,
446        cursor,
447        ..Request::default()
448    };
449    let plan = Plan::admit(
450        entity,
451        &request,
452        binding,
453        incarnation,
454        None,
455        PlanOutput::Rows,
456    )?;
457    execute(map, entity, &request, &plan, None)
458}
459
460enum QuerySource<'a, M: Memory> {
461    Direct(&'a Database<M>),
462    Session(Rc<RefCell<Database<M>>>),
463}
464
465enum QueryRead<'a, M: Memory> {
466    Direct(&'a Database<M>),
467    Session(Ref<'a, Database<M>>),
468}
469
470impl<M: Memory> Deref for QueryRead<'_, M> {
471    type Target = Database<M>;
472
473    fn deref(&self) -> &Self::Target {
474        match self {
475            Self::Direct(db) => db,
476            Self::Session(db) => db,
477        }
478    }
479}
480
481impl<M: Memory> QuerySource<'_, M> {
482    fn read(&self) -> Result<QueryRead<'_, M>, Error> {
483        match self {
484            Self::Direct(db) => Ok(QueryRead::Direct(db)),
485            Self::Session(db) => db
486                .try_borrow()
487                .map(QueryRead::Session)
488                .map_err(|_| Error::BorrowConflict),
489        }
490    }
491}
492
493/// Fluent exact predicates over one entity. No callback executor is generated.
494/// Ordering uses primary order, an explicit index, a proven automatic path or
495/// bounded complete sorting. Work exhaustion never returns a sorted prefix.
496pub struct Query<'a, E, M: Memory> {
497    db: QuerySource<'a, M>,
498    request: Request<'a>,
499    entity: PhantomData<E>,
500}
501impl<M: Memory> Database<M> {
502    /// Begin a live primary-key-ordered query. Admission occurs on `fetch`.
503    #[must_use]
504    pub fn query<E: Entity>(&self) -> Query<'_, E, M> {
505        Query {
506            db: QuerySource::Direct(self),
507            entity: PhantomData,
508            request: Request::default(),
509        }
510    }
511}
512impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
513    pub(crate) fn from_session(db: Rc<RefCell<Database<M>>>) -> Self {
514        Self {
515            db: QuerySource::Session(db),
516            request: Request::default(),
517            entity: PhantomData,
518        }
519    }
520
521    /// Remove duplicate output records. Proven leading index tuples use live
522    /// pages. Projecting the primary key or the varying fields of a unique key covering every match
523    /// needs no duplicate tracking. Other projections scan to
524    /// completion in one call, retaining at most 32 tuples within 128 KiB.
525    /// That fallback preserves first-match traversal order, refuses cursors and
526    /// returns `Limit` if work, result count or combined bytes cannot fit; it
527    /// never returns a partial result. An individually oversized row returns
528    /// `RowTooLarge`. Comparison keys are bounded to 4096 bytes.
529    /// Non-identity sorted DISTINCT retains the best `limit` distinct tuples. Its order
530    /// must lead with all varying projected fields. A mandatory literal equality
531    /// fixes a field. Remove duplicates before applying `limit` and output bytes.
532    #[must_use]
533    pub fn distinct(mut self) -> Self {
534        self.request.distinct = true;
535        self
536    }
537
538    /// Add an AND term over a top-level field. Lists and sets support exact scalar membership with `Contains`.
539    /// Eq/Ne with `IndexValue::Absent` also accept any optional stored field,
540    /// including blobs and containers. Empty values are present, not absent.
541    /// All operands are admitted before storage reads, including contradictory terms.
542    /// On a primary traversal, mandatory Eq/Lt/Le/Gt/Ge primary-key comparisons
543    /// narrow the scanned range. On an index path, those comparisons can narrow
544    /// its first field after the admitted fixed prefix. Only examined rows
545    /// undergo integrity checks; oversized derived bounds remain residual filters.
546    /// Indexed StartsWith can seek that field's exact encoded Text/Blob prefix too.
547    #[must_use]
548    pub fn filter(
549        mut self,
550        field: &'a str,
551        comparison: Comparison,
552        value: impl Into<IndexValue<'a>>,
553    ) -> Self {
554        self.request
555            .filter(field, comparison, QueryOperand::Literal(value.into()));
556        self
557    }
558
559    /// Require an exact field value. Equivalent to `filter(field, Comparison::Eq, value)`.
560    #[must_use]
561    pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
562        self.filter(field, Comparison::Eq, value)
563    }
564
565    /// Require a different value, including absent versus present.
566    #[must_use]
567    pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
568        self.filter(field, Comparison::Ne, value)
569    }
570
571    /// Require a present field strictly below the supplied value.
572    #[must_use]
573    pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
574        self.filter(field, Comparison::Lt, value)
575    }
576
577    /// Require a present field at or below the supplied value.
578    #[must_use]
579    pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
580        self.filter(field, Comparison::Le, value)
581    }
582
583    /// Require a present field strictly above the supplied value.
584    #[must_use]
585    pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
586        self.filter(field, Comparison::Gt, value)
587    }
588
589    /// Require a present field at or above the supplied value.
590    #[must_use]
591    pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
592        self.filter(field, Comparison::Ge, value)
593    }
594
595    /// Compare two top-level fields on the same row. Lists and sets support Contains
596    /// with a present scalar field of the element type. Text and Blob also
597    /// support StartsWith, EndsWith and Contains with a present right-hand field.
598    /// Types must match; Text and Blob bounds may differ within their respective families.
599    /// Two absent values are equal. An ordered comparison requires two present values.
600    #[must_use]
601    pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
602        self.request
603            .filter(left, comparison, QueryOperand::Field(right));
604        self
605    }
606
607    /// Compare UTF-8 bytes for Text, raw bytes for Blob, or the item count for a
608    /// list, set or map. Accepts Eq, Ne, Lt, Le, Gt and Ge. An absent field
609    /// matches Ne only; use Gt(0) for a present, nonempty value.
610    #[must_use]
611    pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
612        self.request
613            .filter(field, comparison, QueryOperand::Length(length));
614        self
615    }
616
617    /// Match rows whose optional field has a value, including an empty value.
618    /// Required and unknown fields return `InvalidQuery` at admission.
619    #[must_use]
620    pub fn filter_present(self, field: &'a str) -> Self {
621        self.filter(field, Comparison::Ne, IndexValue::Absent)
622    }
623
624    /// Match rows whose optional field has no value.
625    /// Required and unknown fields return `InvalidQuery` at admission.
626    #[must_use]
627    pub fn filter_absent(self, field: &'a str) -> Self {
628        self.filter(field, Comparison::Eq, IndexValue::Absent)
629    }
630
631    /// Match a present field inside an inclusive range, ANDed with other filters.
632    /// Equivalent to `filter(field, Comparison::Ge, lower)` followed by
633    /// `filter(field, Comparison::Le, upper)`, including cursor/job identity.
634    /// Both exact operands are admitted and consume two of the eight comparisons.
635    /// Absent operands refuse; absent fields never match. Reversed bounds produce
636    /// no matches, without skipping admission of either operand or other filters.
637    #[must_use]
638    pub fn filter_between(
639        self,
640        field: &'a str,
641        lower: impl Into<IndexValue<'a>>,
642        upper: impl Into<IndexValue<'a>>,
643    ) -> Self {
644        self.filter(field, Comparison::Ge, lower)
645            .filter(field, Comparison::Le, upper)
646    }
647
648    /// Match a present field strictly outside an inclusive range.
649    /// Equivalent to one `filter_any` clause containing `Lt lower` then `Gt upper`,
650    /// including cursor/job identity. Both exact operands consume filter terms.
651    /// Absent operands refuse and absent fields never match; this is not a general
652    /// negation of `filter_between`. Equal bounds exclude that value; reversed
653    /// bounds match every present value, once. Uses the existing single traversal
654    /// and work budget, without seeking separate ranges for the two alternatives.
655    #[must_use]
656    pub fn filter_not_between(
657        self,
658        field: &'a str,
659        lower: impl Into<IndexValue<'a>>,
660        upper: impl Into<IndexValue<'a>>,
661    ) -> Self {
662        self.filter_any(&[
663            (field, Comparison::Lt, lower.into()),
664            (field, Comparison::Gt, upper.into()),
665        ])
666    }
667
668    /// Match `lower <= field && field <= upper` using three top-level fields of the row.
669    /// Both comparisons require present values of compatible types. Equal endpoints
670    /// are inclusive. Uses the same two comparison terms and continuation as the
671    /// equivalent chained `filter_fields` calls.
672    #[must_use]
673    pub fn filter_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
674        self.filter_fields(field, Comparison::Ge, lower)
675            .filter_fields(field, Comparison::Le, upper)
676    }
677
678    /// Match `field < lower || field > upper` using fields of the same row.
679    /// A missing bound makes only its own comparison false. A missing tested field
680    /// never matches. Uses one OR clause and the same two comparison terms and
681    /// continuation as the equivalent `filter_any_operands` call.
682    #[must_use]
683    pub fn filter_not_between_fields(self, field: &'a str, lower: &'a str, upper: &'a str) -> Self {
684        self.filter_any_operands(&[
685            (field, Comparison::Lt, QueryOperand::Field(lower)),
686            (field, Comparison::Gt, QueryOperand::Field(upper)),
687        ])
688    }
689
690    /// Add an OR clause of exact top-level comparisons, ANDed with other filters.
691    /// Each clause must contain at least one comparison; all filters together
692    /// may contain at most eight. Empty/oversized clauses refuse with `Error::Limit`
693    /// at execution. Every operand is admitted, even if another alternative matches.
694    /// Uses one ordered traversal, without union scans or duplicate rows. Alternatives
695    /// do not establish fixed index prefixes; a one-term clause behaves like `filter`.
696    #[must_use]
697    pub fn filter_any(mut self, alternatives: &[(&'a str, Comparison, IndexValue<'a>)]) -> Self {
698        self.request.or_clause(
699            alternatives
700                .iter()
701                .map(|&(field, op, value)| (field, op, QueryOperand::Literal(value))),
702        );
703        self
704    }
705
706    /// Add one OR clause of literal, field-to-field or length comparisons.
707    /// Each alternative follows its corresponding single-filter admission rules.
708    /// All alternatives share the eight-comparison budget with the other filters.
709    /// Literal-only clauses have the same cursor and job identity as `filter_any`.
710    #[must_use]
711    pub fn filter_any_operands(
712        mut self,
713        alternatives: &[(&'a str, Comparison, QueryOperand<'a>)],
714    ) -> Self {
715        self.request.or_clause(alternatives.iter().copied());
716        self
717    }
718
719    /// Match a field against any supplied exact value, ANDed with other filters.
720    /// Equivalent to `filter_any` with equality comparisons in the supplied order.
721    /// Include `None` in a slice of optional values to match an absent field.
722    /// When the field is the next traversal key component, seek between the smallest
723    /// and largest member, including all tied owners. Interior candidates still consume work.
724    /// Repeated members never repeat rows, but each counts toward the shared
725    /// eight-comparison limit. Empty or oversized lists refuse with `Error::Limit`.
726    /// Every member is admitted before reading; there is no coercion, sorting or
727    /// deduplication of operands. Reordering members changes cursor/job identity.
728    #[must_use]
729    pub fn filter_in(
730        mut self,
731        field: &'a str,
732        values: &[impl Copy + Into<IndexValue<'a>>],
733    ) -> Self {
734        self.request.or_clause(
735            values
736                .iter()
737                .copied()
738                .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
739        );
740        self
741    }
742
743    /// Exclude every supplied exact value, ANDed with other filters.
744    /// Equivalent to consecutive `filter(field, Comparison::Ne, value)` calls
745    /// in the supplied order. Absent fields match unless absence is explicitly
746    /// excluded. Empty lists refuse; all members, including duplicates, count
747    /// toward the shared eight-comparison budget. Every operand is admitted.
748    /// The equivalent inequality chain shares cursor/job identity; reordering
749    /// the list changes that identity. No coercion or deduplication is performed.
750    #[must_use]
751    pub fn filter_not_in(
752        mut self,
753        field: &'a str,
754        values: &[impl Copy + Into<IndexValue<'a>>],
755    ) -> Self {
756        self.request
757            .filter_not_in(field, values.iter().copied().map(Into::into));
758        self
759    }
760
761    /// Select index order and exact leading components (at most four).
762    /// All rows matching this prefix are considered. Sparse indexes require
763    /// every optional indexed component to be proven present by the prefix or
764    /// filters. Every alternative in a proving OR clause must reject absence.
765    #[must_use]
766    pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
767        self.request.using_index(name, values);
768        self
769    }
770
771    /// Append an ascending sort field. Earlier fields take precedence.
772    /// The same field, work and continuation rules as [`Self::order_by_each`] apply.
773    #[must_use]
774    pub fn order_asc(mut self, field: &'a str) -> Self {
775        self.request.append_order(field, SortDirection::Ascending);
776        self
777    }
778
779    /// Append a descending sort field. An implicit primary-key tie-breaker
780    /// stays ascending; append the primary key explicitly to choose its direction.
781    #[must_use]
782    pub fn order_desc(mut self, field: &'a str) -> Self {
783        self.request.append_order(field, SortDirection::Descending);
784        self
785    }
786
787    /// Replace the current order with 1..=4 distinct top-level ordered fields, then the primary key.
788    /// An explicitly listed primary key must be last. All fields share one
789    /// direction, reversed by `descending`. Prefer a complete ordered path.
790    /// Otherwise scan to completion while retaining the best `limit` rows within
791    /// 128 KiB of key/output buffers, then sort them. Non-identity DISTINCT retains
792    /// the best `limit` distinct tuples. Work exhaustion refuses; no
793    /// cursor is supported by this fallback. DISTINCT requires an identity result
794    /// or an order led by all varying projected fields. Equality terms may fix
795    /// leading index components. With `using_index`, require that path's order.
796    #[must_use]
797    pub fn order_by(mut self, fields: &[&'a str]) -> Self {
798        self.request.order_by(fields);
799        self
800    }
801
802    /// Replace the order with 1..=4 fields and their individual directions.
803    /// An explicit primary key must be last; otherwise append it ascending.
804    /// `descending()` reverses every direction, including that tie-breaker.
805    /// The same path proof and complete-sort bounds as `order_by` apply.
806    #[must_use]
807    pub fn order_by_each(mut self, fields: &[(&'a str, SortDirection)]) -> Self {
808        self.request.order_by_each(fields);
809        self
810    }
811
812    /// Reverse the complete result order, including its unique tie-breaker.
813    #[must_use]
814    pub fn descending(mut self) -> Self {
815        self.request.descending = true;
816        self
817    }
818
819    /// Return at most 1..=32 matching rows in this page.
820    /// Complete-collection DISTINCT refuses if the full result exceeds this cap.
821    /// Complete sorting applies this cap after examining the entire input; it
822    /// never relaxes the separate 32-matching-row retention bound.
823    /// For grouped aggregates, cap the complete selected result instead; use
824    /// `group_page` to set a retained grouped response's page size separately.
825    #[must_use]
826    pub fn limit(mut self, rows: usize) -> Self {
827        self.request.rows = rows;
828        self
829    }
830
831    /// Examine at most 1..=512 candidates, independently of the returned row limit.
832    #[must_use]
833    pub fn work_limit(mut self, candidates: usize) -> Self {
834        self.request.work = candidates;
835        self
836    }
837
838    /// Exercise output exhaustion with a small response in qualification fixtures.
839    #[cfg(feature = "test-support")]
840    #[doc(hidden)]
841    #[must_use]
842    pub fn test_output_limit(mut self, bytes: usize) -> Self {
843        self.request.bytes = bytes;
844        self
845    }
846
847    /// Continue this query; page resource limits may change between calls.
848    #[must_use]
849    pub fn after(mut self, cursor: &'a QueryCursor) -> Self {
850        self.request.cursor = Some(cursor);
851        self
852    }
853
854    /// Admit and execute one page, then decode only its matching output rows.
855    /// # Errors
856    /// Refuses unsupported shapes, inexact operands, limits, invalid cursors and corruption.
857    /// A selected output row larger than the whole byte allowance returns `RowTooLarge`.
858    /// # Panics
859    /// Supplier corruption traps without repair, as for direct record reads.
860    pub fn fetch(self) -> Result<QueryPage<E>, Error> {
861        fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_entities()
862    }
863
864    /// Return the first matching entity in query order, or `None` on a proven miss.
865    /// Uses a one-row page. For partial pages with resumable progress use `fetch`.
866    /// # Errors
867    /// Returns the same admission and storage errors as `fetch`. Returns `Limit`
868    /// if the work budget ends before a match or exhaustion is established.
869    pub fn first(self) -> Result<Option<E>, Error> {
870        let mut page = self.probe_matches(1)?;
871        match page.rows.pop() {
872            None if page.next.is_some() => Err(Error::Limit),
873            result => Ok(result),
874        }
875    }
876
877    /// Return the only match, or `None` when the query is exhausted without one.
878    /// A valid row limit is overridden to probe for two matches. Applies to the
879    /// whole query, so a continuation is refused.
880    /// # Errors
881    /// Returns `MultipleMatches` on a second match and `Limit` if the page is
882    /// incomplete before cardinality is known. Ordinary fetch errors apply.
883    pub fn try_one(self) -> Result<Option<E>, Error> {
884        if self.request.cursor.is_some() {
885            return Err(Error::InvalidQuery);
886        }
887        let mut page = self.probe_matches(2)?;
888        if page.rows.len() == 2 {
889            return Err(Error::MultipleMatches);
890        }
891        if page.next.is_some() {
892            return Err(Error::Limit);
893        }
894        Ok(page.rows.pop())
895    }
896
897    fn probe_matches(self, rows: usize) -> Result<QueryPage<E>, Error> {
898        if !(1..=32).contains(&self.request.rows) {
899            return Err(Error::Limit);
900        }
901        self.limit(rows).fetch()
902    }
903
904    /// Project matching top-level fields into an existing `#[record]` type.
905    /// Names, optionality and complete value definitions must match exactly.
906    /// The record is an output shape, not a new stored entity or schema entry.
907    /// Byte limits count projected bytes; all source fields still undergo validation.
908    /// # Errors
909    /// Refuses non-record/empty or incompatible output shapes, and the same failures
910    /// as `fetch`. A continuation must use the same selected field shape.
911    /// # Panics
912    /// Supplier corruption traps without repair, as for direct record reads.
913    pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
914        let raw = fetch_rows(
915            &*self.db.read()?,
916            E::SCHEMA,
917            self.request,
918            Some(R::definition()),
919        )?;
920        raw.decode_projection()
921    }
922}
923
924// Reuse named-record metadata/codecs rather than a second value tree or a
925// generic executor per output shape. The full transitive graph matters: named
926// links compare by identity, which alone cannot establish codec compatibility.
927fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u16, Error> {
928    let TypeBody::Record(fields) = &output.body else {
929        return Err(Error::InvalidQuery);
930    };
931    if fields.is_empty()
932        || fields.len() > crate::schema::MAX_FIELDS
933        || fields.windows(2).any(|w| w[0].name >= w[1].name)
934    {
935        return Err(Error::InvalidQuery);
936    }
937    let mut source = TypeGraph::default();
938    let mut target = TypeGraph::default();
939    let mut mask = 0;
940    for field in *fields {
941        let position = entity
942            .field_position(field.name)
943            .ok_or(Error::InvalidQuery)?;
944        let stored = &entity.fields[position];
945        if stored.value != field.value || stored.optional != field.optional {
946            return Err(Error::InvalidQuery);
947        }
948        source
949            .include(stored.value)
950            .map_err(|_| Error::InvalidQuery)?;
951        target
952            .include(field.value)
953            .map_err(|_| Error::InvalidQuery)?;
954        mask |= 1 << position;
955    }
956    if !source.contains(&target) {
957        return Err(Error::InvalidQuery);
958    }
959    Ok(mask)
960}
961
962struct Term {
963    position: usize,
964    comparison: Comparison,
965    operand: TermOperand,
966    or_next: bool,
967}
968
969enum TermOperand {
970    Literal {
971        bytes: Vec<u8>,
972        absent: bool,
973    },
974    Member {
975        item: FieldType,
976        needle: MemberNeedle,
977    },
978    Field(usize),
979    Length(u32),
980}
981
982enum MemberNeedle {
983    Literal(Vec<u8>),
984    Field(usize),
985}
986
987fn member_type(field: FieldType) -> Option<FieldType> {
988    match key::operand_type(field) {
989        FieldType::List { item, .. } => Some(*item),
990        FieldType::Named(link) => match (link.definition)().body {
991            TypeBody::Set { item, .. } => Some(item),
992            _ => None,
993        },
994        _ => None,
995    }
996}
997
998// inspect_fields has already validated every item, including the tail after a match.
999fn contains_member(
1000    span: &[u8],
1001    optional: bool,
1002    item: FieldType,
1003    needle: &[u8],
1004    scratch: &mut Vec<u8>,
1005) -> Result<bool, Error> {
1006    let mut reader = Decoder::new(span)?;
1007    if optional && !reader.boolean()? {
1008        return Ok(false);
1009    }
1010    for _ in 0..reader.nat32()? {
1011        scratch.clear();
1012        IndexValue::read(&mut reader, item)?.append_component(false, scratch);
1013        if scratch.as_slice() == needle {
1014            return Ok(true);
1015        }
1016    }
1017    Ok(false)
1018}
1019
1020fn admit_ordered_fields(entity: &EntitySchema, mask: u16) -> Result<(), Error> {
1021    for (i, field) in entity.fields.iter().enumerate() {
1022        if mask & (1 << i) != 0 && !key::supports(field.value) {
1023            return Err(Error::InvalidQuery);
1024        }
1025    }
1026    Ok(())
1027}
1028
1029// Grouping, distinct counts and collected DISTINCT share exact tuple equality.
1030fn comparison_key(
1031    entity: &EntitySchema,
1032    mask: u16,
1033    values: &[IndexValue<'_>],
1034) -> Result<Vec<u8>, Error> {
1035    let mut key = Vec::new();
1036    for (i, field) in entity.fields.iter().enumerate() {
1037        if mask & (1 << i) != 0 {
1038            values[i].append_component(field.optional, &mut key);
1039            if key.len() > MAX_COMPARISON_KEY {
1040                return Err(Error::Limit);
1041            }
1042        }
1043    }
1044    Ok(key)
1045}
1046
1047fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1048    if size > limit {
1049        return Err(Error::RowTooLarge);
1050    }
1051    if size > limit - *used {
1052        return Err(Error::Limit);
1053    }
1054    *used += size;
1055    Ok(())
1056}
1057
1058// Size and copy already validated projection spans using the same field mask.
1059fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1060    spans
1061        .iter()
1062        .enumerate()
1063        .filter(|(i, _)| mask & (1 << i) != 0)
1064        .map(|(_, (start, end))| usize::from(end - start))
1065        .sum()
1066}
1067
1068fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1069    let mut output = Vec::with_capacity(size);
1070    for (i, &(start, end)) in spans.iter().enumerate() {
1071        if mask & (1 << i) != 0 {
1072            output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1073        }
1074    }
1075    output
1076}
1077#[derive(Clone, Copy)]
1078enum PlanOutput {
1079    Rows,
1080    Aggregate { grouped: bool },
1081}
1082
1083struct Plan<'a> {
1084    primary: usize,
1085    index: Option<&'a IndexSchema>,
1086    prefix: Vec<u8>,
1087    fixed_components: usize,
1088    terms: Vec<Term>,
1089    selected: u16,
1090    // Non-orderable fields need only their validated optional tags, never key slots.
1091    span_fields: u16,
1092    binding: [u8; 32],
1093    projection: Option<u16>,
1094    distinct: distinct::Strategy,
1095    sort: Option<Vec<(usize, bool)>>,
1096    descending: bool,
1097}
1098impl<'a> Plan<'a> {
1099    fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1100        self.terms.split_inclusive(|term| !term.or_next)
1101    }
1102
1103    fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1104        self.index = Some(path.index);
1105        self.prefix = path.prefix;
1106        self.fixed_components = path.fixed;
1107        self.selected |= entity.key_fields();
1108    }
1109
1110    fn admit(
1111        entity: &'a EntitySchema,
1112        request: &Request<'_>,
1113        schema: [u8; 32],
1114        incarnation: [u8; 16],
1115        projection: Option<&TypeSchema>,
1116        output: PlanOutput,
1117    ) -> Result<Self, Error> {
1118        if request.over_limit
1119            || !(1..=32).contains(&request.rows)
1120            || !(1..=MAX_WORK).contains(&request.work)
1121            || !(1..=MAX_OUTPUT).contains(&request.bytes)
1122        {
1123            return Err(Error::Limit);
1124        }
1125        if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1126        {
1127            return Err(Error::InvalidQuery);
1128        }
1129        // Bound literal encoding even when a declaration's maximum exceeds one row.
1130        for value in request
1131            .predicates
1132            .iter()
1133            .filter_map(|p| match &p.operand {
1134                QueryOperand::Literal(value) => Some(value),
1135                QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1136            })
1137            .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1138        {
1139            if match value {
1140                IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1141                IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1142                _ => false,
1143            } {
1144                return Err(Error::Limit);
1145            }
1146        }
1147        let primary = entity
1148            .field_position(entity.primary_key)
1149            .filter(|&i| !entity.fields[i].optional)
1150            .ok_or(Error::InvalidQuery)?;
1151        let mut plan = Self {
1152            primary,
1153            index: None,
1154            prefix: prefix(2, entity.id),
1155            fixed_components: 0,
1156            terms: Vec::new(),
1157            selected: 1 << primary,
1158            span_fields: 0,
1159            binding: [0; 32],
1160            projection: projection
1161                .map(|output| admit_projection(entity, output))
1162                .transpose()?,
1163            distinct: distinct::Strategy::Identity,
1164            sort: None,
1165            descending: request.descending ^ request.primary_descending(entity),
1166        };
1167        for predicate in &request.predicates {
1168            let position = entity
1169                .field_position(predicate.field)
1170                .ok_or(Error::InvalidQuery)?;
1171            let field = &entity.fields[position];
1172            let member = if predicate.comparison == Comparison::Contains {
1173                member_type(field.value)
1174            } else {
1175                None
1176            };
1177            let operand = match predicate.operand {
1178                QueryOperand::Length(length) => {
1179                    let supported = match key::operand_type(field.value) {
1180                        FieldType::Text { .. }
1181                        | FieldType::Blob { .. }
1182                        | FieldType::List { .. } => true,
1183                        FieldType::Named(link) => matches!(
1184                            (link.definition)().body,
1185                            TypeBody::Map { .. } | TypeBody::Set { .. }
1186                        ),
1187                        _ => false,
1188                    };
1189                    if !supported || !predicate.comparison.is_relational() {
1190                        return Err(Error::InvalidQuery);
1191                    }
1192                    plan.span_fields |= 1 << position;
1193                    TermOperand::Length(length)
1194                }
1195                QueryOperand::Field(name) => {
1196                    let right = entity.field_position(name).ok_or(Error::InvalidQuery)?;
1197                    let right_type = entity.fields[right].value;
1198                    let left_type = member.unwrap_or(field.value);
1199                    let compatible = left_type == right_type
1200                        || matches!(
1201                            (left_type, right_type),
1202                            (FieldType::Text { .. }, FieldType::Text { .. })
1203                                | (FieldType::Blob { .. }, FieldType::Blob { .. })
1204                        );
1205                    if !compatible
1206                        || !key::supports(left_type)
1207                        || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1208                    {
1209                        return Err(Error::InvalidQuery);
1210                    }
1211                    plan.selected |= 1 << right;
1212                    if let Some(item) = member {
1213                        plan.span_fields |= 1 << position;
1214                        TermOperand::Member {
1215                            item,
1216                            needle: MemberNeedle::Field(right),
1217                        }
1218                    } else {
1219                        plan.selected |= 1 << position;
1220                        TermOperand::Field(right)
1221                    }
1222                }
1223                QueryOperand::Literal(value) => {
1224                    if let Some(item) = member {
1225                        if !key::supports(item) {
1226                            return Err(Error::InvalidQuery);
1227                        }
1228                        value.admit(item, false)?;
1229                        let mut bytes = Vec::new();
1230                        value.append_component(false, &mut bytes);
1231                        plan.span_fields |= 1 << position;
1232                        TermOperand::Member {
1233                            item,
1234                            needle: MemberNeedle::Literal(bytes),
1235                        }
1236                    } else {
1237                        let absent = value == IndexValue::Absent;
1238                        if key::supports(field.value) {
1239                            plan.selected |= 1 << position;
1240                        } else if absent
1241                            && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1242                        {
1243                            plan.span_fields |= 1 << position;
1244                        } else {
1245                            return Err(Error::InvalidQuery);
1246                        }
1247                        predicate
1248                            .comparison
1249                            .admit(field.value, field.optional, value)?;
1250                        let mut bytes = Vec::new();
1251                        value.append_component(field.optional, &mut bytes);
1252                        TermOperand::Literal { bytes, absent }
1253                    }
1254                }
1255            };
1256            plan.terms.push(Term {
1257                position,
1258                comparison: predicate.comparison,
1259                operand,
1260                or_next: predicate.or_next,
1261            });
1262        }
1263        // Admit every operand before selecting a path, even for empty or
1264        // contradictory queries. The scanner consumes this one proven choice.
1265        match order::select(entity, request, output)? {
1266            order::Path::Primary => {}
1267            order::Path::Index(path) => plan.use_index(entity, path),
1268            order::Path::Sort(fields) => {
1269                for &(position, _) in &fields {
1270                    plan.selected |= 1 << position;
1271                }
1272                plan.sort = Some(fields);
1273            }
1274        }
1275        if request.distinct {
1276            plan.distinct = distinct::admit(
1277                entity,
1278                request,
1279                plan.projection,
1280                plan.index,
1281                plan.fixed_components,
1282                plan.sort.is_some(),
1283            )?;
1284            if plan.distinct == distinct::Strategy::Complete {
1285                plan.selected |= plan.projection.ok_or(Error::InvalidQuery)?;
1286            }
1287        }
1288        let mut hash = Sha256::new();
1289        hash.update(b"ic-db:query:v1\0");
1290        hash.update(schema);
1291        hash.update(incarnation);
1292        hash.update([u8::from(request.descending)]);
1293        hash.update((plan.prefix.len() as u32).to_le_bytes());
1294        hash.update(&plan.prefix);
1295        for term in &plan.terms {
1296            hash.update([term.position as u8, term.comparison as u8]);
1297            match &term.operand {
1298                TermOperand::Literal { bytes, .. }
1299                | TermOperand::Member {
1300                    needle: MemberNeedle::Literal(bytes),
1301                    ..
1302                } => {
1303                    hash.update((bytes.len() as u32).to_le_bytes());
1304                    hash.update(bytes);
1305                }
1306                TermOperand::Length(length) => {
1307                    hash.update((u32::MAX - 1).to_le_bytes());
1308                    hash.update(length.to_le_bytes());
1309                }
1310                TermOperand::Field(right)
1311                | TermOperand::Member {
1312                    needle: MemberNeedle::Field(right),
1313                    ..
1314                } => {
1315                    // Outside the bounded literal length domain.
1316                    hash.update(u32::MAX.to_le_bytes());
1317                    hash.update([*right as u8]);
1318                }
1319            }
1320        }
1321        // Keep existing conjunction identities unchanged. A bounded clause mask
1322        // distinguishes OR grouping without persisting another predicate model.
1323        let clauses = plan
1324            .terms
1325            .iter()
1326            .enumerate()
1327            .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1328        if clauses != 0 {
1329            hash.update(b"or-clauses\0");
1330            hash.update([clauses]);
1331        }
1332        if let Some(order) = &request.order {
1333            hash.update(b"order\0");
1334            hash.update([order.len() as u8]);
1335            for name in order {
1336                // Field names were admitted by order selection above.
1337                hash.update([entity.field_position(name).ok_or(Error::InvalidQuery)? as u8]);
1338            }
1339        }
1340        if request.order_descending != 0 {
1341            hash.update(b"order-directions\0");
1342            hash.update([request.order_descending]);
1343        }
1344        // Preserve existing entity-result cursors. Projected shapes add a
1345        // domain-separated suffix; output Rust names do not change semantics.
1346        if let Some(mask) = plan.projection {
1347            hash.update(b"projection\0");
1348            hash.update(mask.to_le_bytes());
1349        }
1350        if request.distinct {
1351            hash.update(b"distinct\0");
1352        }
1353        plan.binding = hash.finalize().into();
1354        if let Some(cursor) = request.cursor {
1355            if cursor.binding != plan.binding {
1356                return Err(Error::InvalidCursor);
1357            }
1358            plan.validate_position(entity, &cursor.position)
1359                .map_err(|_| Error::InvalidCursor)?;
1360        }
1361        Ok(plan)
1362    }
1363
1364    fn validate_position(&self, entity: &EntitySchema, bytes: &[u8]) -> Result<(), Error> {
1365        if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1366            return Err(Error::InvalidCursor);
1367        }
1368        if let Some(index) = self.index {
1369            let mut remaining = bytes.get(9..).ok_or(Error::InvalidCursor)?;
1370            for name in index.fields {
1371                consume_index_component(entity, index, name, &mut remaining)?;
1372            }
1373            if !index.unique {
1374                key::consume(&mut remaining, entity.key_type()?)?;
1375            }
1376            if !remaining.is_empty() {
1377                return Err(Error::InvalidCursor);
1378            }
1379        } else {
1380            RowKey::decode(
1381                bytes.get(5..).ok_or(Error::InvalidCursor)?,
1382                entity.key_type()?,
1383            )?;
1384        }
1385        Ok(())
1386    }
1387
1388    fn cursor(&self, position: &[u8], inclusive: bool) -> QueryCursor {
1389        QueryCursor {
1390            binding: self.binding,
1391            position: position.to_vec(),
1392            inclusive,
1393        }
1394    }
1395}
1396
1397// Cursor framing and DISTINCT equivalence boundaries use the same key decoder.
1398fn consume_index_component(
1399    entity: &EntitySchema,
1400    index: &IndexSchema,
1401    name: &str,
1402    remaining: &mut &[u8],
1403) -> Result<(), Error> {
1404    let field = entity
1405        .fields
1406        .iter()
1407        .find(|f| f.name == name)
1408        .ok_or(Error::InvalidQuery)?;
1409    if field.optional {
1410        let (&presence, rest) = remaining.split_first().ok_or(Error::InvalidCursor)?;
1411        *remaining = rest;
1412        match presence {
1413            0 if !index.present_only => return Ok(()),
1414            1 => {}
1415            _ => return Err(Error::InvalidCursor),
1416        }
1417    }
1418    key::consume(remaining, field.value)
1419}
1420
1421// Admission, execution and request cleanup share one entity-independent boundary.
1422// Only conversion of the returned bytes remains in the typed public terminals.
1423#[inline(never)]
1424#[expect(
1425    clippy::needless_pass_by_value,
1426    reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1427)]
1428fn fetch_rows<M: Memory>(
1429    db: &Database<M>,
1430    entity: &EntitySchema,
1431    request: Request<'_>,
1432    projection: Option<&TypeSchema>,
1433) -> Result<QueryPage<Vec<u8>>, Error> {
1434    db.schema.admits(entity)?;
1435    let plan = Plan::admit(
1436        entity,
1437        &request,
1438        db.schema.fingerprint(),
1439        db.incarnation,
1440        projection,
1441        PlanOutput::Rows,
1442    )?;
1443    execute(&db.map, entity, &request, &plan, None)
1444}
1445
1446fn execute<M: Memory>(
1447    map: &Map<M>,
1448    entity: &EntitySchema,
1449    request: &Request<'_>,
1450    plan: &Plan<'_>,
1451    mut aggregate: Option<aggregate::Accumulator<'_>>,
1452) -> Result<QueryPage<Vec<u8>>, Error> {
1453    execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
1454}
1455
1456// Retained aggregates use the same traversal, but checkpoint at a work boundary.
1457// Reserve a maximum candidate before the next fetch, including index/owner keys.
1458const STEP_INPUT_BYTES: usize = 64 * 1024;
1459const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1460
1461fn execute_inner<M: Memory>(
1462    map: &Map<M>,
1463    entity: &EntitySchema,
1464    request: &Request<'_>,
1465    plan: &Plan<'_>,
1466    mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1467    mut input_bytes: Option<&mut usize>,
1468) -> Result<QueryPage<Vec<u8>>, Error> {
1469    let mut page = QueryPage {
1470        rows: Vec::new(),
1471        next: None,
1472        examined: 0,
1473        fetched: 0,
1474        output_bytes: 0,
1475    };
1476    let Some(bounds) = range::bounds(entity, request, plan)? else {
1477        return Ok(page);
1478    };
1479    let terminal = range::terminal_key(&bounds, plan.descending);
1480    let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1481    let mut collected = if plan.distinct == distinct::Strategy::Complete {
1482        Some(distinct::Collection::new(
1483            plan.projection.ok_or(Error::InvalidQuery)?,
1484        ))
1485    } else {
1486        None
1487    };
1488    let mut sorted = plan
1489        .sort
1490        .as_ref()
1491        .map(|_| sort::Collection::new(request, plan.distinct));
1492    let mut component = Vec::new();
1493    let mut right_component = Vec::new();
1494    // Each processed equivalence class is either wholly rejected or already
1495    // emitted. Inclusive byte retries point at an unreturned class instead.
1496    let mut previous = if let Some(cursor) = request.cursor.filter(|c| !c.inclusive) {
1497        distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1498    } else {
1499        None
1500    };
1501    let primary_type = entity.fields[plan.primary].value;
1502    while let Some(entry) = if plan.descending {
1503        entries.next_back()
1504    } else {
1505        entries.next()
1506    } {
1507        // Retained jobs may have consumed their lifetime candidate allowance.
1508        // An empty range can still establish completion; refuse a next candidate
1509        // before reading its value or touching the accumulator.
1510        if request.work == 0 {
1511            return Err(Error::Limit);
1512        }
1513        page.examined += 1;
1514        let stored_key = entry.key();
1515        let mut read_bytes = stored_key.len();
1516        let (owner, bytes) = if plan.index.is_some() {
1517            let owner_bytes = entry.value();
1518            read_bytes += owner_bytes.len();
1519            let owner = RowKey::decode(&owner_bytes, primary_type)?;
1520            let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1521            (owner, bytes)
1522        } else {
1523            (
1524                RowKey::decode(&stored_key[5..], primary_type)?,
1525                entry.value(),
1526            )
1527        };
1528        if let Some(used) = input_bytes.as_deref_mut() {
1529            read_bytes += bytes.len();
1530            if read_bytes > CANDIDATE_BYTES {
1531                return Err(Error::Corrupt);
1532            }
1533            *used += read_bytes;
1534        }
1535        page.fetched += 1;
1536        let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1537        let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1538        entity.inspect_fields(
1539            &bytes,
1540            plan.selected,
1541            &mut values,
1542            (plan.span_fields != 0
1543                || plan.projection.is_some()
1544                || aggregate.as_ref().is_some_and(|a| a.needs_spans()))
1545            .then_some(&mut spans),
1546        )?;
1547        if RowKey::from_index(values[plan.primary])? != owner {
1548            return Err(Error::Corrupt);
1549        }
1550        if plan.index.is_some() {
1551            validate_index_entry(entity, &entity.row_info(&values)?, owner, stored_key)?;
1552        }
1553        let mut accepts = |term: &Term| -> Result<bool, Error> {
1554            let value = values[term.position];
1555            component.clear();
1556            let (operand, optional) = match &term.operand {
1557                TermOperand::Literal { absent: true, .. }
1558                    if plan.span_fields & (1 << term.position) != 0 =>
1559                {
1560                    let absent = bytes[usize::from(spans[term.position].0)] == 0;
1561                    return Ok(term.comparison.accepts_absent(absent));
1562                }
1563                TermOperand::Member { item, needle } => {
1564                    let needle = match needle {
1565                        MemberNeedle::Literal(bytes) => bytes.as_slice(),
1566                        MemberNeedle::Field(right) => {
1567                            let value = values[*right];
1568                            if value == IndexValue::Absent {
1569                                return Ok(false);
1570                            }
1571                            right_component.clear();
1572                            value.append_component(false, &mut right_component);
1573                            &right_component
1574                        }
1575                    };
1576                    let (start, end) = spans[term.position];
1577                    return contains_member(
1578                        &bytes[usize::from(start)..usize::from(end)],
1579                        entity.fields[term.position].optional,
1580                        *item,
1581                        needle,
1582                        &mut component,
1583                    );
1584                }
1585                TermOperand::Length(length) => {
1586                    let (start, end) = spans[term.position];
1587                    let span = &bytes[usize::from(start)..usize::from(end)];
1588                    let actual =
1589                        crate::codec::validated_length(span, entity.fields[term.position].optional);
1590
1591                    return Ok(term.comparison.accepts_length(actual, *length));
1592                }
1593                TermOperand::Literal { bytes, absent } => (
1594                    (!absent).then_some(bytes.as_slice()),
1595                    entity.fields[term.position].optional,
1596                ),
1597                TermOperand::Field(right) => {
1598                    let rhs = values[*right];
1599                    right_component.clear();
1600                    rhs.append_component(false, &mut right_component);
1601                    (
1602                        (rhs != IndexValue::Absent).then_some(right_component.as_slice()),
1603                        false,
1604                    )
1605                }
1606            };
1607            value.append_component(optional, &mut component);
1608            Ok(term.comparison.accepts(
1609                (value != IndexValue::Absent).then_some(component.as_slice()),
1610                operand,
1611                optional,
1612            ))
1613        };
1614        let matches = 'matches: {
1615            'clause: for clause in plan.clauses() {
1616                for term in clause {
1617                    if accepts(term)? {
1618                        continue 'clause;
1619                    }
1620                }
1621                break 'matches false;
1622            }
1623            true
1624        };
1625        let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
1626        let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
1627        if matches && let Some(accumulator) = aggregate.as_mut() {
1628            accumulator.push(entity, &values, &bytes, &spans)?;
1629            if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
1630                // One validated match proves existence, even at the work boundary.
1631                return Ok(page);
1632            }
1633        } else if matches && let Some(collection) = collected.as_mut() {
1634            collection.push(entity, request, &values, &bytes, &spans)?;
1635        } else if matches && let Some(collection) = sorted.as_mut() {
1636            collection.push(entity, plan, &values, &bytes, &spans)?;
1637        } else if matches && !duplicate {
1638            let size = plan
1639                .projection
1640                .map_or(bytes.len(), |mask| projection_size(&spans, mask));
1641            if size > request.bytes {
1642                return Err(Error::RowTooLarge);
1643            }
1644            if size > request.bytes - page.output_bytes {
1645                page.next = Some(plan.cursor(stored_key, true));
1646                return Ok(page);
1647            }
1648            page.output_bytes += size;
1649            if let Some(mask) = plan.projection {
1650                page.rows.push(copy_projection(&bytes, &spans, mask, size));
1651            } else {
1652                page.rows.push(bytes);
1653            }
1654            if let Some(boundary) = boundary {
1655                previous = Some(boundary.to_vec());
1656            }
1657        }
1658        if page.rows.len() == request.rows
1659            || page.examined == request.work
1660            || input_bytes
1661                .as_deref()
1662                .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
1663        {
1664            if terminal == Some(stored_key) {
1665                break;
1666            }
1667            if (aggregate.is_some() && input_bytes.is_none())
1668                || collected.is_some()
1669                || sorted.is_some()
1670            {
1671                // Completion has not been observed. Never expose partial reductions;
1672                // an exact-boundary scan may conservatively require more budget.
1673                return Err(Error::Limit);
1674            }
1675            page.next = Some(plan.cursor(stored_key, false));
1676            return Ok(page);
1677        }
1678    }
1679    if let Some(collection) = collected {
1680        page.output_bytes = collection.output_bytes;
1681        page.rows = collection.rows;
1682    }
1683    if let Some(collection) = sorted {
1684        collection.finish(request.bytes, &mut page)?;
1685    }
1686    Ok(page)
1687}