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