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