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