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