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