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    build_comparison_key(entity, mask, |i, _| Ok(values[i]))
1125}
1126
1127fn build_comparison_key<'a>(
1128    entity: &EntitySchema,
1129    mask: u16,
1130    mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1131) -> Result<Vec<u8>, Error> {
1132    let mut key = Vec::new();
1133    for (i, field) in entity.fields.iter().enumerate() {
1134        if mask & (1 << i) != 0 {
1135            value(i, field)?.append_component(field.optional, &mut key);
1136            if key.len() > MAX_COMPARISON_KEY {
1137                return Err(Error::Limit);
1138            }
1139        }
1140    }
1141
1142    Ok(key)
1143}
1144
1145fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1146    if size > limit {
1147        return Err(Error::RowTooLarge);
1148    }
1149    if size > limit - *used {
1150        return Err(Error::Limit);
1151    }
1152    *used += size;
1153
1154    Ok(())
1155}
1156
1157// Size and copy already validated projection spans using the same field mask.
1158fn projection_size(spans: &[(u16, u16)], mask: u16) -> usize {
1159    spans
1160        .iter()
1161        .enumerate()
1162        .filter(|(i, _)| mask & (1 << i) != 0)
1163        .map(|(_, (start, end))| usize::from(end - start))
1164        .sum()
1165}
1166
1167fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u16, size: usize) -> Vec<u8> {
1168    let mut output = Vec::with_capacity(size);
1169    for (i, &(start, end)) in spans.iter().enumerate() {
1170        if mask & (1 << i) != 0 {
1171            output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1172        }
1173    }
1174
1175    output
1176}
1177#[derive(Clone, Copy)]
1178enum PlanOutput {
1179    Rows,
1180    Aggregate { grouped: bool },
1181}
1182
1183struct Plan<'a> {
1184    primary: usize,
1185    index: Option<&'a IndexSchema>,
1186    prefix: Vec<u8>,
1187    fixed_components: usize,
1188    terms: Vec<Term>,
1189    selected: u16,
1190    // Non-orderable fields need only their validated optional tags, never key slots.
1191    span_fields: u16,
1192    binding: [u8; 32],
1193    projection: Option<u16>,
1194    distinct: distinct::Strategy,
1195    sort: Option<Vec<(usize, bool)>>,
1196    descending: bool,
1197}
1198impl<'a> Plan<'a> {
1199    fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1200        self.terms.split_inclusive(|term| !term.or_next)
1201    }
1202
1203    fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1204        self.index = Some(path.index);
1205        self.prefix = path.prefix;
1206        self.fixed_components = path.fixed;
1207        self.selected |= entity.key_fields();
1208    }
1209
1210    fn admit(
1211        entity: &'a EntitySchema,
1212        request: &Request<'_>,
1213        schema: [u8; 32],
1214        incarnation: [u8; 16],
1215        projection: Option<&TypeSchema>,
1216        output: PlanOutput,
1217    ) -> Result<Self, Error> {
1218        if request.over_limit
1219            || !(1..=32).contains(&request.rows)
1220            || !(1..=MAX_WORK).contains(&request.work)
1221            || !(1..=MAX_OUTPUT).contains(&request.bytes)
1222        {
1223            return Err(Error::Limit);
1224        }
1225        if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1226        {
1227            return Err(Error::InvalidQuery);
1228        }
1229        // Bound literal encoding even when a declaration's maximum exceeds one row.
1230        for value in request
1231            .predicates
1232            .iter()
1233            .filter_map(|p| match &p.operand {
1234                QueryOperand::Literal(value) => Some(value),
1235                QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1236            })
1237            .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1238        {
1239            if match value {
1240                IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
1241                IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
1242                _ => false,
1243            } {
1244                return Err(Error::Limit);
1245            }
1246        }
1247        let primary = entity
1248            .field_position(entity.primary_key)
1249            .filter(|&i| !entity.fields[i].optional)
1250            .ok_or(Error::InvalidQuery)?;
1251        let mut plan = Self {
1252            primary,
1253            index: None,
1254            prefix: prefix(2, entity.id),
1255            fixed_components: 0,
1256            terms: Vec::new(),
1257            selected: 1 << primary,
1258            span_fields: 0,
1259            binding: [0; 32],
1260            projection: projection
1261                .map(|output| admit_projection(entity, output))
1262                .transpose()?,
1263            distinct: distinct::Strategy::Identity,
1264            sort: None,
1265            descending: request.descending ^ request.primary_descending(entity),
1266        };
1267        for predicate in &request.predicates {
1268            let position = entity
1269                .field_position(predicate.field)
1270                .ok_or(Error::InvalidQuery)?;
1271            let field = &entity.fields[position];
1272            let member = if predicate.comparison == Comparison::Contains {
1273                member_type(field.value)
1274            } else {
1275                None
1276            };
1277            let operand = match predicate.operand {
1278                QueryOperand::Length(length) => {
1279                    let supported = match key::operand_type(field.value) {
1280                        FieldType::Text { .. }
1281                        | FieldType::Blob { .. }
1282                        | FieldType::List { .. } => true,
1283                        FieldType::Named(link) => matches!(
1284                            (link.definition)().body,
1285                            TypeBody::Map { .. } | TypeBody::Set { .. }
1286                        ),
1287                        _ => false,
1288                    };
1289                    if !supported || !predicate.comparison.is_relational() {
1290                        return Err(Error::InvalidQuery);
1291                    }
1292                    plan.span_fields |= 1 << position;
1293
1294                    TermOperand::Length(length)
1295                }
1296                QueryOperand::Field(name) => {
1297                    let right = entity.field_position(name).ok_or(Error::InvalidQuery)?;
1298                    let right_type = entity.fields[right].value;
1299                    let left_type = member.unwrap_or(field.value);
1300                    let compatible = left_type == right_type
1301                        || matches!(
1302                            (left_type, right_type),
1303                            (FieldType::Text { .. }, FieldType::Text { .. })
1304                                | (FieldType::Blob { .. }, FieldType::Blob { .. })
1305                        );
1306                    if !compatible
1307                        || !key::supports(left_type)
1308                        || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1309                    {
1310                        return Err(Error::InvalidQuery);
1311                    }
1312                    plan.selected |= 1 << right;
1313
1314                    if let Some(item) = member {
1315                        plan.span_fields |= 1 << position;
1316
1317                        TermOperand::Member {
1318                            item,
1319                            needle: MemberNeedle::Field(right),
1320                        }
1321                    } else {
1322                        plan.selected |= 1 << position;
1323
1324                        TermOperand::Field(right)
1325                    }
1326                }
1327                QueryOperand::Literal(value) => {
1328                    if let Some(item) = member {
1329                        if !key::supports(item) {
1330                            return Err(Error::InvalidQuery);
1331                        }
1332                        value.admit(item, false)?;
1333                        let mut bytes = Vec::new();
1334                        value.append_component(false, &mut bytes);
1335                        plan.span_fields |= 1 << position;
1336
1337                        TermOperand::Member {
1338                            item,
1339                            needle: MemberNeedle::Literal(bytes),
1340                        }
1341                    } else {
1342                        let absent = value == IndexValue::Absent;
1343                        if key::supports(field.value) {
1344                            plan.selected |= 1 << position;
1345                        } else if absent
1346                            && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1347                        {
1348                            plan.span_fields |= 1 << position;
1349                        } else {
1350                            return Err(Error::InvalidQuery);
1351                        }
1352                        predicate
1353                            .comparison
1354                            .admit(field.value, field.optional, value)?;
1355                        let mut bytes = Vec::new();
1356                        value.append_component(field.optional, &mut bytes);
1357
1358                        TermOperand::Literal { bytes, absent }
1359                    }
1360                }
1361            };
1362            plan.terms.push(Term {
1363                position,
1364                comparison: predicate.comparison,
1365                operand,
1366                or_next: predicate.or_next,
1367            });
1368        }
1369        // Admit every operand before selecting a path, even for empty or
1370        // contradictory queries. The scanner consumes this one proven choice.
1371        match order::select(entity, request, output)? {
1372            order::Path::Primary => {}
1373            order::Path::Index(path) => plan.use_index(entity, path),
1374            order::Path::Sort(fields) => {
1375                for &(position, _) in &fields {
1376                    plan.selected |= 1 << position;
1377                }
1378                plan.sort = Some(fields);
1379            }
1380        }
1381        if request.distinct {
1382            plan.distinct = distinct::admit(
1383                entity,
1384                request,
1385                plan.projection,
1386                plan.index,
1387                plan.fixed_components,
1388                plan.sort.is_some(),
1389            )?;
1390            if plan.distinct == distinct::Strategy::Complete {
1391                plan.selected |= plan.projection.ok_or(Error::InvalidQuery)?;
1392            }
1393        }
1394        let mut hash = Sha256::new();
1395        hash.update(b"ic-db:query:v1\0");
1396        hash.update(schema);
1397        hash.update(incarnation);
1398        hash.update([u8::from(request.descending)]);
1399        hash.update((plan.prefix.len() as u32).to_le_bytes());
1400        hash.update(&plan.prefix);
1401        for term in &plan.terms {
1402            hash.update([term.position as u8, term.comparison as u8]);
1403
1404            match &term.operand {
1405                TermOperand::Literal { bytes, .. }
1406                | TermOperand::Member {
1407                    needle: MemberNeedle::Literal(bytes),
1408                    ..
1409                } => {
1410                    hash.update((bytes.len() as u32).to_le_bytes());
1411                    hash.update(bytes);
1412                }
1413                TermOperand::Length(length) => {
1414                    hash.update((u32::MAX - 1).to_le_bytes());
1415                    hash.update(length.to_le_bytes());
1416                }
1417                TermOperand::Field(right)
1418                | TermOperand::Member {
1419                    needle: MemberNeedle::Field(right),
1420                    ..
1421                } => {
1422                    // Outside the bounded literal length domain.
1423                    hash.update(u32::MAX.to_le_bytes());
1424                    hash.update([*right as u8]);
1425                }
1426            }
1427        }
1428        // Keep existing conjunction identities unchanged. A bounded clause mask
1429        // distinguishes OR grouping without persisting another predicate model.
1430        let clauses = plan
1431            .terms
1432            .iter()
1433            .enumerate()
1434            .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
1435        if clauses != 0 {
1436            hash.update(b"or-clauses\0");
1437            hash.update([clauses]);
1438        }
1439        if let Some(order) = &request.order {
1440            hash.update(b"order\0");
1441            hash.update([order.len() as u8]);
1442            for name in order {
1443                // Field names were admitted by order selection above.
1444                hash.update([entity.field_position(name).ok_or(Error::InvalidQuery)? as u8]);
1445            }
1446        }
1447        if request.order_descending != 0 {
1448            hash.update(b"order-directions\0");
1449            hash.update([request.order_descending]);
1450        }
1451        // Preserve existing entity-result cursors. Projected shapes add a
1452        // domain-separated suffix; output Rust names do not change semantics.
1453        if let Some(mask) = plan.projection {
1454            hash.update(b"projection\0");
1455            hash.update(mask.to_le_bytes());
1456        }
1457        if request.distinct {
1458            hash.update(b"distinct\0");
1459        }
1460        plan.binding = hash.finalize().into();
1461        if let Some(cursor) = request.cursor {
1462            if cursor.binding != plan.binding {
1463                return Err(Error::InvalidCursor);
1464            }
1465            plan.validate_position(entity, cursor)
1466                .map_err(|_| Error::InvalidCursor)?;
1467        }
1468
1469        Ok(plan)
1470    }
1471
1472    fn validate_position(&self, entity: &EntitySchema, cursor: &QueryCursor) -> Result<(), Error> {
1473        if cursor.resume == Resume::AfterUnemittedClass
1474            && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
1475        {
1476            return Err(Error::InvalidCursor);
1477        }
1478        let bytes = cursor.position.as_slice();
1479        if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
1480            return Err(Error::InvalidCursor);
1481        }
1482        if let Some(index) = self.index {
1483            let mut remaining = bytes
1484                .get(INDEX_PREFIX_BYTES..)
1485                .ok_or(Error::InvalidCursor)?;
1486            for name in index.fields {
1487                consume_index_component(entity, index, name, &mut remaining)?;
1488            }
1489            if !index.unique {
1490                key::consume(&mut remaining, entity.key_type()?)?;
1491            }
1492            if !remaining.is_empty() {
1493                return Err(Error::InvalidCursor);
1494            }
1495        } else {
1496            RowKey::decode(
1497                bytes
1498                    .get(ENTITY_PREFIX_BYTES..)
1499                    .ok_or(Error::InvalidCursor)?,
1500                entity.key_type()?,
1501            )?;
1502        }
1503
1504        Ok(())
1505    }
1506
1507    fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
1508        QueryCursor {
1509            binding: self.binding,
1510            position: position.to_vec(),
1511            resume,
1512        }
1513    }
1514}
1515
1516// Cursor framing and DISTINCT equivalence boundaries use the same key decoder.
1517fn consume_index_component(
1518    entity: &EntitySchema,
1519    index: &IndexSchema,
1520    name: &str,
1521    remaining: &mut &[u8],
1522) -> Result<(), Error> {
1523    let field = entity.field_by_name(name).ok_or(Error::InvalidQuery)?;
1524
1525    key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1526}
1527
1528// Admission, execution and request cleanup share one entity-independent boundary.
1529// Only conversion of the returned bytes remains in the typed public terminals.
1530#[inline(never)]
1531#[expect(
1532    clippy::needless_pass_by_value,
1533    reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1534)]
1535fn fetch_rows<M: Memory>(
1536    db: &Database<M>,
1537    entity: &EntitySchema,
1538    request: Request<'_>,
1539    projection: Option<&TypeSchema>,
1540) -> Result<QueryPage<Vec<u8>>, Error> {
1541    db.schema.admits(entity)?;
1542    let plan = Plan::admit(
1543        entity,
1544        &request,
1545        db.schema.fingerprint(),
1546        db.incarnation,
1547        projection,
1548        PlanOutput::Rows,
1549    )?;
1550
1551    execute(&db.map, entity, &request, &plan, None)
1552}
1553
1554fn execute<M: Memory>(
1555    map: &Map<M>,
1556    entity: &EntitySchema,
1557    request: &Request<'_>,
1558    plan: &Plan<'_>,
1559    mut aggregate: Option<aggregate::Accumulator<'_>>,
1560) -> Result<QueryPage<Vec<u8>>, Error> {
1561    execute_inner(map, entity, request, plan, aggregate.as_mut(), None)
1562}
1563
1564// Retained aggregates use the same traversal, but checkpoint at a work boundary.
1565// Reserve a maximum candidate before the next fetch, including index/owner keys.
1566const STEP_INPUT_BYTES: usize = 64 * 1024;
1567const CANDIDATE_BYTES: usize = crate::codec::MAX_ROW_BYTES + 2 * crate::MAX_INDEX_KEY_BYTES;
1568
1569fn execute_inner<M: Memory>(
1570    map: &Map<M>,
1571    entity: &EntitySchema,
1572    request: &Request<'_>,
1573    plan: &Plan<'_>,
1574    mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1575    mut input_bytes: Option<&mut usize>,
1576) -> Result<QueryPage<Vec<u8>>, Error> {
1577    let mut page = QueryPage {
1578        rows: Vec::new(),
1579        next: None,
1580        examined: 0,
1581        fetched: 0,
1582        output_bytes: 0,
1583    };
1584    let Some(bounds) = range::bounds(entity, request, plan)? else {
1585        return Ok(page);
1586    };
1587    let terminal = range::terminal_key(&bounds, plan.descending);
1588    let mut entries = map.range((bounds.0.as_ref(), bounds.1.as_ref()));
1589    let mut collected = if plan.distinct == distinct::Strategy::Complete {
1590        Some(distinct::Collection::new(
1591            plan.projection.ok_or(Error::InvalidQuery)?,
1592        ))
1593    } else {
1594        None
1595    };
1596    let mut sorted = plan
1597        .sort
1598        .as_ref()
1599        .map(|_| sort::Collection::new(request, plan.distinct));
1600    let mut component = Vec::new();
1601    let mut right_component = Vec::new();
1602    // Only suppress a class already emitted by this traversal.
1603    let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1604        distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1605    } else {
1606        None
1607    };
1608    let primary_type = entity.fields[plan.primary].value;
1609    while let Some(entry) = if plan.descending {
1610        entries.next_back()
1611    } else {
1612        entries.next()
1613    } {
1614        // Retained jobs may have consumed their lifetime candidate allowance.
1615        // An empty range can still establish completion; refuse a next candidate
1616        // before reading its value or touching the accumulator.
1617        if request.work == 0 {
1618            return Err(Error::Limit);
1619        }
1620        page.examined += 1;
1621        let stored_key = entry.key();
1622        let mut read_bytes = stored_key.len();
1623        let (owner, bytes) = if plan.index.is_some() {
1624            let owner_bytes = entry.value();
1625            read_bytes += owner_bytes.len();
1626            let owner = RowKey::decode(&owner_bytes, primary_type)?;
1627            let bytes = map.get(&row_key(entity.id, owner)).ok_or(Error::Corrupt)?;
1628
1629            (owner, bytes)
1630        } else {
1631            (
1632                RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
1633                entry.value(),
1634            )
1635        };
1636        if let Some(used) = input_bytes.as_deref_mut() {
1637            read_bytes += bytes.len();
1638            if read_bytes > CANDIDATE_BYTES {
1639                return Err(Error::Corrupt);
1640            }
1641            *used += read_bytes;
1642        }
1643        page.fetched += 1;
1644        let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1645        let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1646        entity.inspect_fields(
1647            &bytes,
1648            plan.selected,
1649            &mut values,
1650            (plan.span_fields != 0
1651                || plan.projection.is_some()
1652                || aggregate.as_ref().is_some_and(|a| a.needs_spans()))
1653            .then_some(&mut spans),
1654        )?;
1655        if RowKey::from_index(values[plan.primary])? != owner {
1656            return Err(Error::Corrupt);
1657        }
1658        if plan.index.is_some() {
1659            validate_index_entry(entity, &entity.row_info(&values)?, owner, stored_key)?;
1660        }
1661        let mut accepts = |term: &Term| -> Result<bool, Error> {
1662            let value = values[term.position];
1663            component.clear();
1664            let (operand, optional) = match &term.operand {
1665                TermOperand::Literal { absent: true, .. }
1666                    if plan.span_fields & (1 << term.position) != 0 =>
1667                {
1668                    let absent = bytes[usize::from(spans[term.position].0)] == 0;
1669
1670                    return Ok(term.comparison.accepts_absent(absent));
1671                }
1672                TermOperand::Member { item, needle } => {
1673                    let needle = match needle {
1674                        MemberNeedle::Literal(bytes) => bytes.as_slice(),
1675                        MemberNeedle::Field(right) => {
1676                            let value = values[*right];
1677                            if value == IndexValue::Absent {
1678                                return Ok(false);
1679                            }
1680                            right_component.clear();
1681                            value.append_component(false, &mut right_component);
1682
1683                            &right_component
1684                        }
1685                    };
1686                    let (start, end) = spans[term.position];
1687
1688                    return contains_member(
1689                        &bytes[usize::from(start)..usize::from(end)],
1690                        entity.fields[term.position].optional,
1691                        *item,
1692                        needle,
1693                        &mut component,
1694                    );
1695                }
1696                TermOperand::Length(length) => {
1697                    let (start, end) = spans[term.position];
1698                    let span = &bytes[usize::from(start)..usize::from(end)];
1699                    let actual =
1700                        crate::codec::validated_length(span, entity.fields[term.position].optional);
1701
1702                    return Ok(term.comparison.accepts_length(actual, *length));
1703                }
1704                TermOperand::Literal { bytes, absent } => (
1705                    (!absent).then_some(bytes.as_slice()),
1706                    entity.fields[term.position].optional,
1707                ),
1708                TermOperand::Field(right) => {
1709                    let rhs = values[*right];
1710                    right_component.clear();
1711                    rhs.append_component(false, &mut right_component);
1712
1713                    (
1714                        (rhs != IndexValue::Absent).then_some(right_component.as_slice()),
1715                        false,
1716                    )
1717                }
1718            };
1719            value.append_component(optional, &mut component);
1720
1721            Ok(term.comparison.accepts(
1722                (value != IndexValue::Absent).then_some(component.as_slice()),
1723                operand,
1724                optional,
1725            ))
1726        };
1727        let matches = 'matches: {
1728            'clause: for clause in plan.clauses() {
1729                for term in clause {
1730                    if accepts(term)? {
1731                        continue 'clause;
1732                    }
1733                }
1734                break 'matches false;
1735            }
1736
1737            true
1738        };
1739        let boundary = distinct::boundary(entity, plan.index, plan.distinct, stored_key)?;
1740        let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
1741        if matches && let Some(accumulator) = aggregate.as_mut() {
1742            accumulator.push(entity, &values, &bytes, &spans)?;
1743            if matches!(accumulator, aggregate::Accumulator::Exists(_)) {
1744                // One validated match proves existence, even at the work boundary.
1745                return Ok(page);
1746            }
1747        } else if matches && let Some(collection) = collected.as_mut() {
1748            collection.push(entity, request, &values, &bytes, &spans)?;
1749            // This path emits first occurrences in traversal order. A single-result
1750            // terminal has its answer after one class (first) or two (non-unique).
1751            if request.single_result_probe && collection.rows.len() == request.rows {
1752                break;
1753            }
1754        } else if matches && let Some(collection) = sorted.as_mut() {
1755            collection.push(entity, plan, &values, &bytes, &spans)?;
1756        } else if matches && !duplicate {
1757            let size = plan
1758                .projection
1759                .map_or(bytes.len(), |mask| projection_size(&spans, mask));
1760            if size > request.bytes {
1761                return Err(Error::RowTooLarge);
1762            }
1763            if size > request.bytes - page.output_bytes {
1764                page.next = Some(plan.cursor(stored_key, Resume::Retry));
1765
1766                return Ok(page);
1767            }
1768            page.output_bytes += size;
1769            if let Some(mask) = plan.projection {
1770                page.rows.push(copy_projection(&bytes, &spans, mask, size));
1771            } else {
1772                page.rows.push(bytes);
1773            }
1774            if plan.distinct == distinct::Strategy::FirstMatch {
1775                return Ok(page);
1776            }
1777            if let Some(boundary) = boundary {
1778                previous = Some(boundary.to_vec());
1779            }
1780        }
1781        if page.rows.len() == request.rows
1782            || page.examined == request.work
1783            || input_bytes
1784                .as_deref()
1785                .is_some_and(|used| *used > STEP_INPUT_BYTES - CANDIDATE_BYTES)
1786        {
1787            if terminal == Some(stored_key) {
1788                break;
1789            }
1790            if (aggregate.is_some() && input_bytes.is_none())
1791                || collected.is_some()
1792                || sorted.is_some()
1793            {
1794                // Completion has not been observed. Never expose partial reductions;
1795                // an exact-boundary scan may conservatively require more budget.
1796                return Err(Error::Limit);
1797            }
1798            let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
1799                Resume::AfterUnemittedClass
1800            } else {
1801                Resume::After
1802            };
1803            page.next = Some(plan.cursor(stored_key, resume));
1804
1805            return Ok(page);
1806        }
1807    }
1808    if let Some(collection) = collected {
1809        page.output_bytes = collection.output_bytes;
1810        page.rows = collection.rows;
1811    }
1812    if let Some(collection) = sorted {
1813        collection.finish(request.bytes, &mut page)?;
1814    }
1815
1816    Ok(page)
1817}