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    // Keep construction, filter and order_by out of the caller. These builders
851    // can share Wasm across entities since none of them reads E::SCHEMA.
852    #[inline(never)]
853    fn new(db: QuerySource<'a, M>) -> Self {
854        Self {
855            db,
856            request: Request::default(),
857            entity: PhantomData,
858        }
859    }
860
861    /// Remove duplicate output records. Proven leading index tuples use live
862    /// pages. Projecting the primary key or the varying fields of a unique key covering every match
863    /// needs no duplicate tracking. Other projections scan to
864    /// completion in one call, retaining at most 32 tuples within 128 KiB.
865    /// That fallback preserves first-match traversal order, refuses cursors and
866    /// returns `Limit` if work, result count or combined bytes cannot fit; it
867    /// never returns a partial result. An individually oversized row returns
868    /// `RowTooLarge`. Comparison keys are bounded to 4096 bytes.
869    /// For enumeration across calls, [`Self::start_distinct`] and [`Self::resume_distinct`]
870    /// retain up to 255 tuples within a 16 KiB job frame, then page the completed result.
871    /// Non-identity sorted DISTINCT retains the best `limit` distinct tuples. Its order
872    /// must lead with all varying projected fields. A mandatory literal equality
873    /// fixes a field. Remove duplicates before applying `limit` and output bytes.
874    #[must_use]
875    pub fn distinct(mut self) -> Self {
876        self.request.distinct = true;
877
878        self
879    }
880
881    /// Add an AND term. A top-level list or set supports exact scalar membership with `Contains`.
882    /// A direct scalar record member selected by [`crate::field_path!`] accepts
883    /// Eq, Ne, Lt, Le, Gt and Ge against a literal. Text and Blob members
884    /// also accept `StartsWith` and `EndsWith` with an operand of the same type.
885    /// Eq/Ne with `IndexValue::Absent` also accept any optional stored field,
886    /// including blobs and containers. Empty values are present, not absent.
887    /// All operands are admitted before storage reads, including contradictory terms.
888    /// On a primary traversal, mandatory Eq/Lt/Le/Gt/Ge primary-key comparisons
889    /// narrow the scanned range. On an index path, those comparisons can narrow
890    /// its first field after the admitted fixed prefix. Only examined rows
891    /// undergo integrity checks; oversized derived bounds remain residual filters.
892    /// Indexed StartsWith can seek that field's exact encoded Text/Blob prefix too.
893    #[must_use]
894    #[inline(never)]
895    pub fn filter(
896        mut self,
897        field: &'a str,
898        comparison: Comparison,
899        value: impl Into<IndexValue<'a>>,
900    ) -> Self {
901        self.request
902            .filter(field, comparison, QueryOperand::Literal(value.into()));
903
904        self
905    }
906
907    /// Restrict this query to the entity's primary key. Accepts a raw key or its entity-typed ID.
908    #[must_use]
909    pub fn by_id(self, id: impl Into<crate::Id<E>>) -> Self {
910        self.eq(
911            E::SCHEMA.primary_key,
912            id.into().key().into_row_key().index_value(),
913        )
914    }
915
916    /// Require an exact field value. Equivalent to `filter(field, Comparison::Eq, value)`.
917    #[must_use]
918    pub fn eq(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
919        self.filter(field, Comparison::Eq, value)
920    }
921
922    /// Apply equality when the caller supplies a filter value. `None` adds no predicate.
923    /// To select rows whose stored field is absent, use [`Self::filter_absent`].
924    #[must_use]
925    pub fn eq_if_some(self, field: &'a str, value: Option<impl Into<IndexValue<'a>>>) -> Self {
926        match value {
927            Some(value) => self.eq(field, value),
928            None => self,
929        }
930    }
931
932    /// Require a different value, including absent versus present.
933    #[must_use]
934    pub fn ne(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
935        self.filter(field, Comparison::Ne, value)
936    }
937
938    /// Require a present field strictly below the supplied value.
939    #[must_use]
940    pub fn lt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
941        self.filter(field, Comparison::Lt, value)
942    }
943
944    /// Require a present field at or below the supplied value.
945    #[must_use]
946    pub fn lte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
947        self.filter(field, Comparison::Le, value)
948    }
949
950    /// Require a present field strictly above the supplied value.
951    #[must_use]
952    pub fn gt(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
953        self.filter(field, Comparison::Gt, value)
954    }
955
956    /// Require a present field at or above the supplied value.
957    #[must_use]
958    pub fn gte(self, field: &'a str, value: impl Into<IndexValue<'a>>) -> Self {
959        self.filter(field, Comparison::Ge, value)
960    }
961
962    /// Compare fields on the same row. Eq, Ne, Lt, Le, Gt and Ge also accept
963    /// direct scalar record members on either side, as do StartsWith and EndsWith for Text and Blob.
964    /// Top-level lists and sets support Contains
965    /// with a present scalar field or direct record member of the element type. Text and Blob also
966    /// support StartsWith, EndsWith and Contains with a present right-hand field.
967    /// Types must match; Text and Blob bounds may differ within their respective families.
968    /// Two absent values are equal. An ordered comparison requires two present values.
969    #[must_use]
970    pub fn filter_fields(mut self, left: &'a str, comparison: Comparison, right: &'a str) -> Self {
971        self.request
972            .filter(left, comparison, QueryOperand::Field(right));
973
974        self
975    }
976
977    /// Compare UTF-8 bytes for Text, raw bytes for Blob, or the item count for a
978    /// list, set or map. A direct Text or Blob record member also supports byte
979    /// length through [`crate::field_path!`]. Accepts Eq, Ne, Lt, Le, Gt and Ge. An absent field
980    /// matches Ne only; use Gt(0) for a present, nonempty value.
981    #[must_use]
982    pub fn filter_length(mut self, field: &'a str, comparison: Comparison, length: u32) -> Self {
983        self.request
984            .filter(field, comparison, QueryOperand::Length(length));
985
986        self
987    }
988
989    /// Match rows whose optional field has a value, including an empty value.
990    /// Required and unknown fields return `InvalidQuery` at admission.
991    #[must_use]
992    pub fn filter_present(self, field: &'a str) -> Self {
993        self.filter(field, Comparison::Ne, IndexValue::Absent)
994    }
995
996    /// Match rows whose optional field has no value.
997    /// Required and unknown fields return `InvalidQuery` at admission.
998    #[must_use]
999    pub fn filter_absent(self, field: &'a str) -> Self {
1000        self.filter(field, Comparison::Eq, IndexValue::Absent)
1001    }
1002
1003    /// Match a present field within a Rust half-open range, including the start and excluding the end.
1004    /// Uses the same two predicate terms and cursor identity as `gte(field, start).lt(field, end)`.
1005    /// Empty and reversed ranges match no rows. Both bounds undergo ordinary operand admission.
1006    #[must_use]
1007    pub fn filter_range<T: Into<IndexValue<'a>>>(
1008        self,
1009        field: &'a str,
1010        range: std::ops::Range<T>,
1011    ) -> Self {
1012        self.gte(field, range.start).lt(field, range.end)
1013    }
1014
1015    /// Match present ULIDs whose embedded timestamp lies in the half-open time range.
1016    /// Uses two ordinary key comparisons, including for empty or out-of-domain ranges.
1017    /// The embedded time can differ from the row's managed creation time.
1018    #[must_use]
1019    pub fn filter_ulid_time(
1020        self,
1021        field: &'a str,
1022        range: std::ops::Range<crate::Timestamp>,
1023    ) -> Self {
1024        let (first, last) =
1025            crate::Ulid::time_bounds(range).unwrap_or((crate::Ulid::MAX, crate::Ulid::MIN));
1026        self.filter_between(field, first, last)
1027    }
1028
1029    /// Match a present field inside an inclusive range, ANDed with other filters.
1030    /// Equivalent to `filter(field, Comparison::Ge, lower)` followed by
1031    /// `filter(field, Comparison::Le, upper)`, including cursor/job identity.
1032    /// Both exact operands are admitted and consume two of the eight comparisons.
1033    /// Absent operands refuse; absent fields never match. Reversed bounds produce
1034    /// no matches, without skipping admission of either operand or other filters.
1035    #[must_use]
1036    pub fn filter_between(
1037        self,
1038        field: &'a str,
1039        lower: impl Into<IndexValue<'a>>,
1040        upper: impl Into<IndexValue<'a>>,
1041    ) -> Self {
1042        self.filter(field, Comparison::Ge, lower)
1043            .filter(field, Comparison::Le, upper)
1044    }
1045
1046    /// Match a present field strictly outside an inclusive range.
1047    /// Equivalent to one `filter_any` clause containing `Lt lower` then `Gt upper`,
1048    /// including cursor/job identity. Both exact operands consume filter terms.
1049    /// Absent operands refuse and absent fields never match; this is not a general
1050    /// negation of `filter_between`. Equal bounds exclude that value; reversed
1051    /// bounds match every present value, once. Uses the existing single traversal
1052    /// and work budget, without seeking separate ranges for the two alternatives.
1053    #[must_use]
1054    pub fn filter_not_between(
1055        self,
1056        field: &'a str,
1057        lower: impl Into<IndexValue<'a>>,
1058        upper: impl Into<IndexValue<'a>>,
1059    ) -> Self {
1060        self.filter_any(&[
1061            (field, Comparison::Lt, lower.into()),
1062            (field, Comparison::Gt, upper.into()),
1063        ])
1064    }
1065
1066    /// Add one OR clause, ANDed with other filters. Pass raw values of one type,
1067    /// `IndexValue` for mixed literal types, or `QueryOperand` to include field and length comparisons.
1068    /// Alternatives may compare different direct scalar members of a record.
1069    /// Each clause must contain at least one comparison; all filters together
1070    /// may contain at most eight. Empty/oversized clauses refuse with `Error::Limit`
1071    /// at execution. Every operand is admitted, even if another alternative matches.
1072    /// Uses one ordered traversal, without union scans or duplicate rows. Alternatives
1073    /// do not establish fixed index prefixes; a one-term clause behaves like `filter`.
1074    #[must_use]
1075    pub fn filter_any<T: Copy + Into<QueryOperand<'a>>>(
1076        mut self,
1077        alternatives: &[(&'a str, Comparison, T)],
1078    ) -> Self {
1079        self.request.or_clause(
1080            alternatives
1081                .iter()
1082                .map(|&(field, op, value)| (field, op, value.into())),
1083        );
1084        self
1085    }
1086
1087    /// Match a field against any supplied exact value, ANDed with other filters.
1088    /// Equivalent to `filter_any` with equality comparisons in the supplied order.
1089    /// Include `None` in a slice of optional values to match an absent field.
1090    /// When the field is the next traversal key component, seek between the smallest
1091    /// and largest member, including all tied owners. Interior candidates still consume work.
1092    /// Repeated members never repeat rows, but each counts toward the shared
1093    /// eight-comparison limit. Empty or oversized lists refuse with `Error::Limit`.
1094    /// Every member is admitted before reading; there is no coercion, sorting or
1095    /// deduplication of operands. Reordering members changes cursor/job identity.
1096    #[must_use]
1097    pub fn filter_in(
1098        mut self,
1099        field: &'a str,
1100        values: &[impl Copy + Into<IndexValue<'a>>],
1101    ) -> Self {
1102        self.request.or_clause(
1103            values
1104                .iter()
1105                .copied()
1106                .map(|value| (field, Comparison::Eq, QueryOperand::Literal(value.into()))),
1107        );
1108
1109        self
1110    }
1111
1112    /// Exclude every supplied exact value, ANDed with other filters.
1113    /// Equivalent to consecutive `filter(field, Comparison::Ne, value)` calls
1114    /// in the supplied order. Absent fields match unless absence is explicitly
1115    /// excluded. Empty lists refuse; all members, including duplicates, count
1116    /// toward the shared eight-comparison budget. Every operand is admitted.
1117    /// The equivalent inequality chain shares cursor/job identity; reordering
1118    /// the list changes that identity. No coercion or deduplication is performed.
1119    #[must_use]
1120    pub fn filter_not_in(
1121        mut self,
1122        field: &'a str,
1123        values: &[impl Copy + Into<IndexValue<'a>>],
1124    ) -> Self {
1125        self.request
1126            .filter_not_in(field, values.iter().copied().map(Into::into));
1127
1128        self
1129    }
1130
1131    /// Select index order and exact leading components (at most four).
1132    /// All rows matching this prefix are considered. Sparse indexes require
1133    /// every optional indexed component to be proven present by the prefix or
1134    /// filters. Every alternative in a proving OR clause must reject absence.
1135    #[must_use]
1136    pub fn using_index(mut self, name: &'a str, values: &[IndexValue<'a>]) -> Self {
1137        self.request.using_index(name, values);
1138
1139        self
1140    }
1141
1142    /// Append an ascending sort field. Earlier fields take precedence.
1143    /// The same field, work and continuation rules as [`Self::order_by`] apply.
1144    #[must_use]
1145    pub fn order_asc(mut self, field: &'a str) -> Self {
1146        self.request.append_order(field, SortDirection::Ascending);
1147
1148        self
1149    }
1150
1151    /// Append a descending sort field. An implicit primary-key tie-breaker
1152    /// stays ascending; append the primary key explicitly to choose its direction.
1153    #[must_use]
1154    pub fn order_desc(mut self, field: &'a str) -> Self {
1155        self.request.append_order(field, SortDirection::Descending);
1156
1157        self
1158    }
1159
1160    /// Replace the current order with 1..=4 distinct ordered scalar fields, then the primary key.
1161    /// A direct record member can be selected with [`crate::field_path!`].
1162    /// An explicitly listed primary key must be last. Bare names sort ascending. Pass (field, SortDirection) pairs for mixed directions.
1163    /// An empty slice needs an element type, e.g. `&[] as &[&str]`, and refuses at execution.
1164    /// `descending` reverses the entire order. Prefer a complete ordered path.
1165    /// Otherwise scan to completion while retaining the best `limit` rows within
1166    /// 128 KiB of key/output buffers, then sort them. Non-identity DISTINCT retains
1167    /// the best `limit` distinct tuples. Work exhaustion refuses; no
1168    /// cursor is supported by this fallback. DISTINCT requires an identity result
1169    /// or an order led by all varying projected fields. Equality terms may fix
1170    /// leading index components. With `using_index`, require that path's order.
1171    #[must_use]
1172    #[inline(never)]
1173    pub fn order_by(mut self, fields: &[impl Copy + Into<OrderTerm<'a>>]) -> Self {
1174        self.request.order_by(fields);
1175
1176        self
1177    }
1178
1179    /// Reverse the complete result order, including its unique tie-breaker.
1180    #[must_use]
1181    pub fn descending(mut self) -> Self {
1182        self.request.descending = true;
1183
1184        self
1185    }
1186
1187    /// Return at most 1..=32 matching rows in this page.
1188    /// Complete-collection DISTINCT refuses if the full result exceeds this cap.
1189    /// Complete sorting examines the entire admitted input and retains at most
1190    /// the requested number of winners, even when many more rows match.
1191    /// For grouped aggregates, cap the complete selected result instead; use
1192    /// `group_page` to set a retained grouped response's page size separately.
1193    #[must_use]
1194    pub fn limit(mut self, rows: usize) -> Self {
1195        self.request.rows = rows;
1196
1197        self
1198    }
1199
1200    /// Examine at most 1..=512 candidates, independently of the returned row limit.
1201    #[must_use]
1202    pub fn work_limit(mut self, candidates: usize) -> Self {
1203        self.request.work = candidates;
1204
1205        self
1206    }
1207
1208    /// Exercise output exhaustion with a small response in qualification fixtures.
1209    #[cfg(feature = "test-support")]
1210    #[doc(hidden)]
1211    #[must_use]
1212    pub fn test_output_limit(mut self, bytes: usize) -> Self {
1213        self.request.bytes = bytes;
1214
1215        self
1216    }
1217
1218    /// Continue from a borrowed cursor or pass `None` for the first page.
1219    /// Page resource limits may change between calls.
1220    #[must_use]
1221    pub fn after(mut self, cursor: impl Into<Option<&'a QueryCursor>>) -> Self {
1222        self.request.cursor = cursor.into();
1223
1224        self
1225    }
1226
1227    /// Admit and execute one page, then decode only its matching output rows.
1228    /// # Errors
1229    /// Refuses unsupported shapes, inexact operands, limits, invalid cursors and corruption.
1230    /// A selected output row larger than the whole byte allowance returns `RowTooLarge`.
1231    /// # Panics
1232    /// Supplier corruption traps without repair, as for direct record reads.
1233    pub fn fetch(self) -> Result<QueryPage<E>, Error> {
1234        observe!(query, { self.entity_page() })
1235    }
1236
1237    fn entity_page(self) -> Result<QueryPage<E>, Error> {
1238        fetch_rows(&*self.db.read()?, E::SCHEMA, self.request, None)?.decode_rows(E::decode)
1239    }
1240
1241    /// Return the first matching entity in query order, or `None` on a proven miss.
1242    /// Uses a one-row page. For partial pages with resumable progress use `fetch`.
1243    /// # Errors
1244    /// Returns the same admission and storage errors as `fetch`. Returns `Limit`
1245    /// if the work budget ends before a match or exhaustion is established.
1246    pub fn first(self) -> Result<Option<E>, Error> {
1247        self.single_with(SingleResult::First, Self::entity_page)
1248    }
1249
1250    /// Return the first projected record in query order.
1251    /// # Errors
1252    /// Applies the projection checks of [`Self::fetch_as`] and the work bound of [`Self::first`].
1253    pub fn first_as<R: Value>(self) -> Result<Option<R>, Error> {
1254        self.single_with(SingleResult::First, Self::projected_page::<R>)
1255    }
1256
1257    /// Return the only match, or `None` when the query is exhausted without one.
1258    /// A valid row limit is overridden to probe for two matches. Applies to the
1259    /// whole query, so a continuation is refused.
1260    /// # Errors
1261    /// Returns `MultipleMatches` on a second match and `Limit` if the page is
1262    /// incomplete before cardinality is known. Ordinary fetch errors apply.
1263    pub fn try_one(self) -> Result<Option<E>, Error> {
1264        self.single_with(SingleResult::Only, Self::entity_page)
1265    }
1266
1267    /// Return the sole projected result, or `None` on a proven miss.
1268    /// With DISTINCT, a literal equality or fixed index prefix covering every
1269    /// projected field lets an ordered traversal finish at the first match.
1270    /// # Errors
1271    /// Applies the projection checks of [`Self::fetch_as`] and the cardinality checks of [`Self::try_one`].
1272    pub fn try_one_as<R: Value>(self) -> Result<Option<R>, Error> {
1273        self.single_with(SingleResult::Only, Self::projected_page::<R>)
1274    }
1275
1276    fn single_with<R>(
1277        mut self,
1278        probe: SingleResult,
1279        fetch: impl FnOnce(Self) -> Result<QueryPage<R>, Error>,
1280    ) -> Result<Option<R>, Error> {
1281        observe!(query, {
1282            if probe == SingleResult::Only && self.request.cursor.is_some() {
1283                return Err(Error::InvalidQuery);
1284            }
1285            if !(1..=32).contains(&self.request.rows) {
1286                return Err(Error::Limit);
1287            }
1288            self.request.single_result_probe = Some(probe);
1289            fetch(self.limit(match probe {
1290                SingleResult::First => 1,
1291                SingleResult::Only => 2,
1292            }))
1293        })
1294        .map(|mut page| page.rows.pop())
1295    }
1296
1297    /// Project matching top-level fields into an existing `#[record]` type.
1298    /// Names, optionality and complete value definitions must match exactly.
1299    /// The record is an output shape, not a new stored entity or schema entry.
1300    /// Byte limits count projected bytes; all source fields still undergo validation.
1301    /// # Errors
1302    /// Refuses non-record/empty or incompatible output shapes, and the same failures
1303    /// as `fetch`. A continuation must use the same selected field shape.
1304    /// # Panics
1305    /// Supplier corruption traps without repair, as for direct record reads.
1306    pub fn fetch_as<R: Value>(self) -> Result<QueryPage<R>, Error> {
1307        observe!(query, { self.projected_page() })
1308    }
1309
1310    fn projected_page<R: Value>(self) -> Result<QueryPage<R>, Error> {
1311        let raw = fetch_rows(
1312            &*self.db.read()?,
1313            E::SCHEMA,
1314            self.request,
1315            Some(Projection::Record(R::definition())),
1316        )?;
1317
1318        raw.decode_rows(decode_record)
1319    }
1320}
1321
1322#[derive(Clone, Copy)]
1323enum Projection<'a> {
1324    Record(&'a TypeSchema),
1325    Columns(&'a [u8]),
1326}
1327
1328impl Projection<'_> {
1329    fn mask(self, entity: &EntitySchema) -> Result<u32, Error> {
1330        match self {
1331            Self::Record(record) => admit_projection(entity, record),
1332            Self::Columns(columns) => {
1333                let mut mask = 0;
1334                for &column in columns {
1335                    if usize::from(column) >= entity.fields.len() || mask & (1 << column) != 0 {
1336                        return Err(Error::InvalidQuery);
1337                    }
1338                    mask |= 1 << column;
1339                }
1340                Ok(mask)
1341            }
1342        }
1343    }
1344}
1345
1346// Reuse named-record metadata/codecs rather than a second value tree or a
1347// generic executor per output shape. The full transitive graph matters: named
1348// links compare by identity, which alone cannot establish codec compatibility.
1349fn admit_projection(entity: &EntitySchema, output: &TypeSchema) -> Result<u32, Error> {
1350    let TypeBody::Record(fields) = &output.body else {
1351        return Err(Error::InvalidQuery);
1352    };
1353    if fields.is_empty()
1354        || fields.len() > crate::schema::MAX_FIELDS
1355        || fields.windows(2).any(|w| w[0].name >= w[1].name)
1356    {
1357        return Err(Error::InvalidQuery);
1358    }
1359    let mut source = TypeGraph::default();
1360    let mut target = TypeGraph::default();
1361    let mut mask = 0;
1362    for field in *fields {
1363        let position = entity
1364            .field_position(field.name)
1365            .ok_or(Error::InvalidQuery)?;
1366        let stored = &entity.fields[position];
1367        if stored.value != field.value || stored.optional != field.optional {
1368            return Err(Error::InvalidQuery);
1369        }
1370        source
1371            .include(stored.value)
1372            .map_err(|_| Error::InvalidQuery)?;
1373        target
1374            .include(field.value)
1375            .map_err(|_| Error::InvalidQuery)?;
1376        mask |= 1 << position;
1377    }
1378    if !source.contains(&target) {
1379        return Err(Error::InvalidQuery);
1380    }
1381
1382    Ok(mask)
1383}
1384
1385struct Term {
1386    tests_presence: bool,
1387    position: usize,
1388    comparison: Comparison,
1389    operand: TermOperand,
1390    or_next: bool,
1391}
1392
1393enum TermOperand {
1394    Literal {
1395        bytes: Vec<u8>,
1396        absent: bool,
1397    },
1398    Member {
1399        item: FieldType,
1400        needle: MemberNeedle,
1401    },
1402    Nested {
1403        member: crate::member::RecordMember,
1404        literal: Vec<u8>,
1405        absent: bool,
1406    },
1407    Field {
1408        right: usize,
1409        left_member: Option<crate::member::RecordMember>,
1410        right_member: Option<crate::member::RecordMember>,
1411    },
1412    Length {
1413        member: Option<crate::member::RecordMember>,
1414        threshold: u32,
1415    },
1416}
1417
1418enum MemberNeedle {
1419    Literal(Vec<u8>),
1420    Field(usize, Option<crate::member::RecordMember>),
1421}
1422
1423// Operands have already been type-checked. Text and Blob literals carry their
1424// original bytes, before the durable key codec escapes embedded zeros.
1425fn admit_literal_size(value: &IndexValue<'_>) -> Result<(), Error> {
1426    let size = match value {
1427        IndexValue::Text(text) => text.len(),
1428        IndexValue::Blob(bytes) => bytes.len(),
1429        _ => return Ok(()),
1430    };
1431    if size > crate::codec::MAX_ROW_BYTES {
1432        return Err(Error::Limit);
1433    }
1434    Ok(())
1435}
1436
1437fn scalar_bytes(value: IndexValue<'_>) -> Option<&[u8]> {
1438    match value {
1439        IndexValue::Text(text) => Some(text.as_bytes()),
1440        IndexValue::Blob(bytes) => Some(bytes),
1441        _ => None,
1442    }
1443}
1444
1445fn consecutive_values(low: IndexValue<'_>, high: IndexValue<'_>) -> bool {
1446    low.discrete_successor()
1447        .is_some_and(|next| equal_values(next, high))
1448}
1449
1450fn equal_values(left: IndexValue<'_>, right: IndexValue<'_>) -> bool {
1451    // Admission already checked both enum contracts.
1452    match (left, right) {
1453        (IndexValue::UnitEnum { ordinal: a, .. }, IndexValue::UnitEnum { ordinal: b, .. }) => {
1454            a == b
1455        }
1456        _ => left == right,
1457    }
1458}
1459
1460fn length_limit(field: FieldType) -> Option<u32> {
1461    match key::operand_type(field) {
1462        FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => Some(max_bytes),
1463        FieldType::List { max_items, .. } => Some(max_items),
1464        FieldType::Named(link) => match (link.definition)().body {
1465            TypeBody::Map { max_items, .. } | TypeBody::Set { max_items, .. } => Some(max_items),
1466            _ => None,
1467        },
1468        _ => None,
1469    }
1470}
1471
1472fn member_type(field: FieldType) -> Option<FieldType> {
1473    match key::operand_type(field) {
1474        FieldType::List { item, .. } => Some(*item),
1475        FieldType::Named(link) => match (link.definition)().body {
1476            TypeBody::Set { item, .. } => Some(item),
1477            _ => None,
1478        },
1479        _ => None,
1480    }
1481}
1482
1483// inspect_fields has already validated every item, including the tail after a match.
1484fn contains_member(
1485    span: &[u8],
1486    optional: bool,
1487    item: FieldType,
1488    needle: IndexValue<'_>,
1489) -> Result<bool, Error> {
1490    let mut reader = Decoder::new(span)?;
1491    if optional && !reader.boolean()? {
1492        return Ok(false);
1493    }
1494    for _ in 0..reader.nat32()? {
1495        let value = IndexValue::read(&mut reader, item)?;
1496        if equal_values(value, needle) {
1497            return Ok(true);
1498        }
1499    }
1500
1501    Ok(false)
1502}
1503
1504// Ascending positions preserve projection field order and bulk lookup slot order.
1505pub(super) fn set_bit_positions(mut mask: u32) -> impl Iterator<Item = usize> {
1506    std::iter::from_fn(move || {
1507        if mask == 0 {
1508            return None;
1509        }
1510        let position = mask.trailing_zeros() as usize;
1511        mask &= mask - 1;
1512        Some(position)
1513    })
1514}
1515
1516fn admit_ordered_fields(entity: &EntitySchema, mask: u32) -> Result<(), Error> {
1517    for i in set_bit_positions(mask) {
1518        if !key::supports(entity.fields[i].value) {
1519            return Err(Error::InvalidQuery);
1520        }
1521    }
1522
1523    Ok(())
1524}
1525
1526// Grouping, distinct counts and collected DISTINCT share exact tuple equality.
1527fn comparison_key(
1528    entity: &EntitySchema,
1529    mask: u32,
1530    values: &[IndexValue<'_>],
1531    scratch: &mut Vec<u8>,
1532) -> Result<(), Error> {
1533    build_comparison_key(entity, mask, scratch, |i, _| Ok(values[i]))
1534}
1535
1536fn build_comparison_key<'a>(
1537    entity: &EntitySchema,
1538    mask: u32,
1539    key: &mut Vec<u8>,
1540    mut value: impl FnMut(usize, &crate::FieldSchema) -> Result<IndexValue<'a>, Error>,
1541) -> Result<(), Error> {
1542    key.clear();
1543    for i in set_bit_positions(mask) {
1544        let field = &entity.fields[i];
1545        value(i, field)?.append_component(field.optional, key);
1546        if key.len() > MAX_COMPARISON_KEY {
1547            return Err(Error::Limit);
1548        }
1549    }
1550
1551    Ok(())
1552}
1553
1554fn admit_output(size: usize, limit: usize, used: &mut usize) -> Result<(), Error> {
1555    if size > limit {
1556        return Err(Error::RowTooLarge);
1557    }
1558    if size > limit - *used {
1559        return Err(Error::Limit);
1560    }
1561    *used += size;
1562
1563    Ok(())
1564}
1565
1566// Size and copy already validated projection spans using the same field mask.
1567fn projection_size(spans: &[(u16, u16)], mask: u32) -> usize {
1568    set_bit_positions(mask)
1569        .map(|i| {
1570            let (start, end) = spans[i];
1571            usize::from(end - start)
1572        })
1573        .sum()
1574}
1575
1576fn copy_projection(bytes: &[u8], spans: &[(u16, u16)], mask: u32, size: usize) -> Vec<u8> {
1577    let mut output = Vec::with_capacity(size);
1578    for i in set_bit_positions(mask) {
1579        let (start, end) = spans[i];
1580        output.extend_from_slice(&bytes[usize::from(start)..usize::from(end)]);
1581    }
1582
1583    output
1584}
1585#[derive(Clone, Copy)]
1586enum PlanOutput {
1587    Rows,
1588    Aggregate { grouped: bool },
1589    ImmediateCount,
1590}
1591
1592struct Plan<'a> {
1593    primary: usize,
1594    index: Option<&'a IndexSchema>,
1595    prefix: Vec<u8>,
1596    // Bind cursors to the admitted path before filter equalities extend its seek.
1597    cursor_prefix_len: usize,
1598    fixed_components: usize,
1599    terms: Vec<Term>,
1600    selected: u32,
1601    // Non-orderable fields need only their validated optional tags, never key slots.
1602    span_fields: u32,
1603    binding: [u8; 32],
1604    projection: Option<u32>,
1605    distinct: distinct::Strategy,
1606    sort: Option<Vec<order::SortField>>,
1607    descending: bool,
1608}
1609impl<'a> Plan<'a> {
1610    fn clauses(&self) -> impl Iterator<Item = &[Term]> {
1611        self.terms.split_inclusive(|term| !term.or_next)
1612    }
1613
1614    fn use_index(&mut self, entity: &EntitySchema, path: order::IndexPath<'a>) {
1615        self.index = Some(path.index);
1616        self.cursor_prefix_len = path.prefix.len();
1617        self.prefix = path.prefix;
1618        self.fixed_components = path.fixed;
1619        self.selected |= entity.key_fields();
1620    }
1621
1622    fn admit(
1623        entity: &'a EntitySchema,
1624        request: &Request<'_>,
1625        schema: [u8; 32],
1626        incarnation: [u8; 16],
1627        projection: Option<Projection<'_>>,
1628        output: PlanOutput,
1629    ) -> Result<Self, Error> {
1630        if !request.within_limits() {
1631            return Err(Error::Limit);
1632        }
1633        if !matches!(output, PlanOutput::Aggregate { grouped: true }) && !request.groups.is_empty()
1634        {
1635            return Err(Error::InvalidQuery);
1636        }
1637        // Bound literal encoding even when a declaration's maximum exceeds one row.
1638        for value in request
1639            .predicates
1640            .iter()
1641            .filter_map(|p| match &p.operand {
1642                QueryOperand::Literal(value) => Some(value),
1643                QueryOperand::Field(_) | QueryOperand::Length(_) => None,
1644            })
1645            .chain(request.index.iter().flat_map(|(_, values)| values.iter()))
1646        {
1647            admit_literal_size(value)?;
1648        }
1649        let primary = entity
1650            .primary_position()
1651            .filter(|&i| !entity.fields[i].optional)
1652            .ok_or(Error::InvalidQuery)?;
1653        let mut plan = Self {
1654            primary,
1655            index: None,
1656            prefix: prefix(2, entity.id, &[]),
1657            cursor_prefix_len: ENTITY_PREFIX_BYTES,
1658            fixed_components: 0,
1659            terms: Vec::new(),
1660            selected: 1 << primary,
1661            span_fields: 0,
1662            binding: [0; 32],
1663            projection: projection.map(|output| output.mask(entity)).transpose()?,
1664            distinct: distinct::Strategy::Identity,
1665            sort: None,
1666            descending: request.descending ^ request.primary_descending(entity),
1667        };
1668        for predicate in &request.predicates {
1669            let (position, record_member) = crate::member::resolve_field(entity, predicate.field)?;
1670            let field = &entity.fields[position];
1671            let member = if predicate.comparison == Comparison::Contains {
1672                member_type(field.value)
1673            } else {
1674                None
1675            };
1676            let operand = match (predicate.operand, record_member) {
1677                (QueryOperand::Literal(value), Some(member)) => {
1678                    if !predicate.comparison.supports_record_member() {
1679                        return Err(Error::InvalidQuery);
1680                    }
1681                    let leaf = member.field();
1682                    predicate.comparison.admit(
1683                        leaf.value,
1684                        field.optional || leaf.optional,
1685                        value,
1686                    )?;
1687                    let literal = value.component(field.optional || leaf.optional);
1688                    plan.span_fields |= 1 << position;
1689                    TermOperand::Nested {
1690                        member,
1691                        literal,
1692                        absent: value == IndexValue::Absent,
1693                    }
1694                }
1695                (QueryOperand::Length(length), member) => {
1696                    let selected = member.map_or(field.value, |m| m.field().value);
1697                    if length_limit(selected).is_none() || !predicate.comparison.is_relational() {
1698                        return Err(Error::InvalidQuery);
1699                    }
1700                    plan.span_fields |= 1 << position;
1701
1702                    TermOperand::Length {
1703                        member,
1704                        threshold: length,
1705                    }
1706                }
1707                (QueryOperand::Field(name), left_member) => {
1708                    let (right, right_member) = crate::member::resolve_field(entity, name)?;
1709                    if (left_member.is_some() || right_member.is_some())
1710                        && member.is_none()
1711                        && !predicate.comparison.supports_record_member()
1712                    {
1713                        return Err(Error::InvalidQuery);
1714                    }
1715                    let right_type =
1716                        right_member.map_or(entity.fields[right].value, |m| m.field().value);
1717                    let left_type =
1718                        left_member.map_or(member.unwrap_or(field.value), |m| m.field().value);
1719                    let compatible = left_type == right_type
1720                        || matches!(
1721                            (left_type, right_type),
1722                            (FieldType::Text { .. }, FieldType::Text { .. })
1723                                | (FieldType::Blob { .. }, FieldType::Blob { .. })
1724                        );
1725                    if !compatible
1726                        || !key::supports(left_type)
1727                        || (member.is_none() && !predicate.comparison.supports_scalar(left_type))
1728                    {
1729                        return Err(Error::InvalidQuery);
1730                    }
1731                    if right_member.is_some() {
1732                        plan.span_fields |= 1 << right;
1733                    } else {
1734                        plan.selected |= 1 << right;
1735                    }
1736
1737                    if let Some(item) = member {
1738                        plan.span_fields |= 1 << position;
1739
1740                        TermOperand::Member {
1741                            item,
1742                            needle: MemberNeedle::Field(right, right_member),
1743                        }
1744                    } else {
1745                        if left_member.is_some() {
1746                            plan.span_fields |= 1 << position;
1747                        } else {
1748                            plan.selected |= 1 << position;
1749                        }
1750                        TermOperand::Field {
1751                            right,
1752                            left_member,
1753                            right_member,
1754                        }
1755                    }
1756                }
1757                (QueryOperand::Literal(value), None) => {
1758                    if let Some(item) = member {
1759                        if !key::supports(item) {
1760                            return Err(Error::InvalidQuery);
1761                        }
1762                        value.admit(item, false)?;
1763                        let bytes = value.component(false);
1764                        plan.span_fields |= 1 << position;
1765
1766                        TermOperand::Member {
1767                            item,
1768                            needle: MemberNeedle::Literal(bytes),
1769                        }
1770                    } else {
1771                        let absent = value == IndexValue::Absent;
1772                        if key::supports(field.value) {
1773                            plan.selected |= 1 << position;
1774                        } else if absent
1775                            && matches!(predicate.comparison, Comparison::Eq | Comparison::Ne)
1776                        {
1777                            plan.span_fields |= 1 << position;
1778                        } else {
1779                            return Err(Error::InvalidQuery);
1780                        }
1781                        predicate
1782                            .comparison
1783                            .admit(field.value, field.optional, value)?;
1784                        let bytes = value.component(field.optional);
1785
1786                        TermOperand::Literal { bytes, absent }
1787                    }
1788                }
1789            };
1790            plan.terms.push(Term {
1791                tests_presence: predicate.tests_presence(entity, &operand),
1792                position,
1793                comparison: predicate.comparison,
1794                operand,
1795                or_next: predicate.or_next,
1796            });
1797        }
1798        // Admit every operand before selecting a path, even for empty or
1799        // contradictory queries. The scanner consumes this one proven choice.
1800        match order::select(entity, request, output)? {
1801            order::Path::Primary => {}
1802            order::Path::Index(path, descending) => {
1803                plan.use_index(entity, path);
1804                plan.descending = request.descending ^ descending;
1805            }
1806            order::Path::Filtered { sort } => {
1807                order::select_filtered_path(entity, request, &mut plan, None)?;
1808                for field in sort.iter().flatten() {
1809                    if field.member.is_some() {
1810                        plan.span_fields |= 1 << field.position;
1811                    } else {
1812                        plan.selected |= 1 << field.position;
1813                    }
1814                }
1815                plan.sort = sort;
1816            }
1817        }
1818        if request.distinct {
1819            plan.distinct = distinct::admit(entity, request, &plan)?;
1820            match plan.distinct {
1821                distinct::Strategy::FirstMatch => plan.sort = None,
1822                distinct::Strategy::Complete { key_fields } => plan.selected |= key_fields,
1823                _ => {}
1824            }
1825        }
1826        // Automatic paths already carry their leading equalities. An explicit path
1827        // can acquire more from its filters after admitting the requested order.
1828        if request.index.is_some()
1829            && !request.predicates.is_empty()
1830            && let Some(index) = plan.index
1831        {
1832            for field in &index.fields[plan.fixed_components..] {
1833                let Some(value) = order::equality(entity, request, field) else {
1834                    break;
1835                };
1836                let schema = entity.index_field(field).ok_or(Error::InvalidSchema)?;
1837                let len = plan.prefix.len();
1838                value.append_component(schema.optional, &mut plan.prefix);
1839                if plan.prefix.len() > crate::MAX_INDEX_KEY_BYTES {
1840                    plan.prefix.truncate(len);
1841                    break;
1842                }
1843                plan.fixed_components += 1;
1844            }
1845        }
1846        // Immediate counts and cursorless single-result reads have no continuation.
1847        if matches!(output, PlanOutput::ImmediateCount)
1848            || (request.single_result_probe.is_some() && request.cursor.is_none())
1849        {
1850            return Ok(plan);
1851        }
1852        plan.bind_cursor(entity, request, schema, incarnation, projection)?;
1853
1854        Ok(plan)
1855    }
1856}
1857
1858// Cursor framing and DISTINCT equivalence boundaries use the same key decoder.
1859fn consume_index_component(
1860    entity: &EntitySchema,
1861    index: &IndexSchema,
1862    name: &str,
1863    remaining: &mut &[u8],
1864) -> Result<(), Error> {
1865    let field = entity.index_field(name).ok_or(Error::InvalidQuery)?;
1866
1867    key::consume_component(remaining, field, index.present_only, Error::InvalidCursor)
1868}
1869
1870// Admission, execution and request cleanup share one entity-independent boundary.
1871// Only conversion of the returned bytes remains in the typed public terminals.
1872#[inline(never)]
1873#[expect(
1874    clippy::needless_pass_by_value,
1875    reason = "own the request so predicate cleanup stays outside entity-specialized terminals"
1876)]
1877fn fetch_rows<M: Memory>(
1878    db: &Database<M>,
1879    entity: &EntitySchema,
1880    request: Request<'_>,
1881    projection: Option<Projection<'_>>,
1882) -> Result<QueryPage<Vec<u8>>, Error> {
1883    db.schema.admits(entity)?;
1884    let plan = Plan::admit(
1885        entity,
1886        &request,
1887        db.schema.fingerprint(),
1888        db.incarnation,
1889        projection,
1890        PlanOutput::Rows,
1891    )?;
1892
1893    execute(&db.map, entity, &request, &plan, None)
1894}
1895
1896fn execute<M: Memory>(
1897    map: &Map<M>,
1898    entity: &EntitySchema,
1899    request: &Request<'_>,
1900    plan: &Plan<'_>,
1901    mut aggregate: Option<aggregate::Accumulator<'_>>,
1902) -> Result<QueryPage<Vec<u8>>, Error> {
1903    execute_inner(
1904        map,
1905        entity,
1906        request,
1907        plan,
1908        range::bounds(entity, request, plan)?,
1909        aggregate.as_mut(),
1910        None,
1911    )
1912}
1913
1914// Retained aggregates use the same traversal, but checkpoint at a work boundary.
1915// Reserve a maximum candidate before the next fetch, including index/owner keys.
1916const STEP_INPUT_BYTES: usize = 64 * 1024;
1917const fn candidate_byte_limit(row_bytes: usize) -> usize {
1918    row_bytes + 2 * crate::MAX_INDEX_KEY_BYTES
1919}
1920
1921fn execute_inner<M: Memory>(
1922    map: &Map<M>,
1923    entity: &EntitySchema,
1924    request: &Request<'_>,
1925    plan: &Plan<'_>,
1926    bounds: Option<range::Bounds>,
1927    mut aggregate: Option<&mut aggregate::Accumulator<'_>>,
1928    mut input_bytes: Option<&mut usize>,
1929) -> Result<QueryPage<Vec<u8>>, Error> {
1930    let mut page = QueryPage {
1931        rows: Vec::new(),
1932        next: None,
1933        examined: 0,
1934        fetched: 0,
1935        output_bytes: 0,
1936    };
1937    let Some(bounds) = bounds else {
1938        return Ok(page);
1939    };
1940    let terminal = range::terminal_key(&bounds, plan.descending);
1941    let mut next_entry = range::entries(map, &bounds, plan.descending);
1942    let mut collected = if let distinct::Strategy::Complete { key_fields } = plan.distinct {
1943        Some(distinct::Collection::new(
1944            plan.projection.ok_or(Error::InvalidQuery)?,
1945            key_fields,
1946        ))
1947    } else {
1948        None
1949    };
1950    let mut sorted = plan
1951        .sort
1952        .as_ref()
1953        .map(|_| sort::Collection::new(request, plan.distinct));
1954    let mut component = Vec::new();
1955    let mut right_component = Vec::new();
1956    // Only suppress a class already emitted by this traversal.
1957    let mut previous = if let Some(cursor) = request.cursor.filter(|c| c.resume == Resume::After) {
1958        distinct::boundary(entity, plan.index, plan.distinct, &cursor.position)?.map(<[u8]>::to_vec)
1959    } else {
1960        None
1961    };
1962    let candidate_bytes = candidate_byte_limit(entity.max_row_bytes);
1963    let primary_type = entity.fields[plan.primary].value;
1964    let needs_spans = plan.index.is_some()
1965        || plan.span_fields != 0
1966        || match &aggregate {
1967            Some(accumulator) => accumulator.needs_spans(),
1968            None => plan.projection.is_some(),
1969        };
1970    // Inspection overwrites every declared field's span, including absent fields.
1971    let mut spans = [(0_u16, 0_u16); crate::schema::MAX_FIELDS];
1972    let mut index_info = None;
1973    while let Some((stored_key, stored_value)) = next_entry() {
1974        // An exhausted iterator proves completion even at the candidate budget.
1975        // Refuse another candidate before inspecting its row or fetching an owner.
1976        if page.examined == request.work {
1977            return Err(Error::Limit);
1978        }
1979        page.examined += 1;
1980        let mut read_bytes = stored_key.len();
1981        let (owner, bytes) = if plan.index.is_some() {
1982            read_bytes += stored_value.len();
1983            read_index_owner(map, entity.id, primary_type, &stored_value)?
1984        } else {
1985            (
1986                RowKey::decode(&stored_key[ENTITY_PREFIX_BYTES..], primary_type)?,
1987                stored_value,
1988            )
1989        };
1990        if let Some(used) = input_bytes.as_deref_mut() {
1991            read_bytes += bytes.len();
1992            if read_bytes > candidate_bytes {
1993                return Err(Error::Corrupt);
1994            }
1995            *used += read_bytes;
1996        }
1997        page.fetched += 1;
1998        let mut values = [IndexValue::Absent; crate::schema::MAX_FIELDS];
1999        entity.inspect_fields(
2000            &bytes,
2001            plan.selected,
2002            &mut values,
2003            needs_spans.then_some(&mut spans),
2004        )?;
2005        let row_key = RowKey::from_index(values[plan.primary])?;
2006        if plan.index.is_some() {
2007            let info = index_info.get_or_insert_with(|| crate::__private::RowInfo::new(row_key));
2008            info.key = row_key;
2009            entity.fill_index_info(&values, &bytes, &spans, info)?;
2010            validate_index_entry(entity, info, owner, &stored_key)?;
2011        } else if row_key != owner {
2012            return Err(Error::Corrupt);
2013        }
2014        let matches = predicate::PredicateRow {
2015            entity,
2016            bytes: &bytes,
2017            values: &values,
2018            spans: &spans,
2019            span_fields: plan.span_fields,
2020        }
2021        .matches(
2022            &plan.terms,
2023            &request.predicates,
2024            &mut component,
2025            &mut right_component,
2026        )?;
2027        let boundary = distinct::boundary(entity, plan.index, plan.distinct, &stored_key)?;
2028        let duplicate = boundary.is_some_and(|key| previous.as_deref() == Some(key));
2029        if matches && let Some(accumulator) = aggregate.as_mut() {
2030            accumulator.push(entity, &values, &bytes, &spans, &mut component)?;
2031            if matches!(accumulator, aggregate::Accumulator::Until(remaining) if **remaining == 0) {
2032                // The last required match proves the threshold, even at the work boundary.
2033                return Ok(page);
2034            }
2035        } else if matches && let Some(collection) = collected.as_mut() {
2036            collection.push(entity, request, &values, &bytes, &spans, &mut component)?;
2037            // First occurrences follow traversal order, so first() can finish here.
2038            if request.single_result_probe == Some(SingleResult::First) {
2039                break;
2040            }
2041        } else if matches && let Some(collection) = sorted.as_mut() {
2042            collection.push(entity, plan, &values, &bytes, &spans, &mut component)?;
2043            // Later candidates can change the top two, but cannot make them one result.
2044            request.check_result_count(collection.result_count())?;
2045        } else if matches && !duplicate {
2046            request.check_result_count(page.rows.len() + 1)?;
2047            let size = plan
2048                .projection
2049                .map_or(bytes.len(), |mask| projection_size(&spans, mask));
2050            if size > request.bytes {
2051                return Err(Error::RowTooLarge);
2052            }
2053            if size > request.bytes - page.output_bytes {
2054                page.next = Some(plan.cursor(&stored_key, Resume::Retry));
2055
2056                return Ok(page);
2057            }
2058            page.output_bytes += size;
2059            if let Some(mask) = plan.projection {
2060                page.rows.push(copy_projection(&bytes, &spans, mask, size));
2061            } else {
2062                page.rows.push(bytes);
2063            }
2064            if request.single_result_probe == Some(SingleResult::First)
2065                || plan.distinct.finishes_on_match(plan.fixed_components)
2066            {
2067                return Ok(page);
2068            }
2069            if let Some(boundary) = boundary {
2070                previous = Some(boundary.to_vec());
2071            }
2072        }
2073        if page.rows.len() == request.rows
2074            || page.examined == request.work
2075            || input_bytes
2076                .as_deref()
2077                .is_some_and(|used| *used > STEP_INPUT_BYTES - candidate_bytes)
2078        {
2079            if terminal == Some(&stored_key) {
2080                break;
2081            }
2082            if request.single_result_probe.is_some()
2083                || (aggregate.is_some() && input_bytes.is_none())
2084                || collected.is_some()
2085                || sorted.is_some()
2086            {
2087                // A complete result can use the final work unit. The next iteration
2088                // either observes exhaustion or refuses the extra candidate.
2089                continue;
2090            }
2091            // A retained job can finish on a full chunk. Probe the iterator
2092            // without fetching another row or index owner. A later advance
2093            // resumes after the last processed key and visits the probed entry.
2094            if input_bytes.is_some() && next_entry().is_none() {
2095                break;
2096            }
2097            let resume = if boundary.is_some_and(|key| previous.as_deref() != Some(key)) {
2098                Resume::AfterUnemittedClass
2099            } else {
2100                Resume::After
2101            };
2102            page.next = Some(plan.cursor(&stored_key, resume));
2103
2104            return Ok(page);
2105        }
2106    }
2107    if let Some(collection) = collected {
2108        page.output_bytes = collection.output_bytes;
2109        page.rows = collection.rows;
2110    }
2111    if let Some(collection) = sorted {
2112        collection.finish(request.bytes, &mut page)?;
2113    }
2114
2115    Ok(page)
2116}