Skip to main content

ic_db/store/query/
mod.rs

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