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