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