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