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