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