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