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