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