Skip to main content

ic_db/store/query/
mod.rs

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