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