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