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