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