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