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