Skip to main content

kevy_embedded/
ops_index_claused.rs

1//! The clause-carrying scalar query for the embedded API — `FILTER` /
2//! `SORT` / `DISTINCT` / `FACET` / `OFFSET` on Range/Unique indexes
3//! (the capacity arc's G1), plus [`ValueFilter`], the predicate shape
4//! this surface shares with the text MATCH clauses. A `#[path]` child
5//! of `ops_index.rs`, feature-independent of `text`.
6
7use kevy_index::{
8    Cursor, FacetBucket, IndexSpec, IndexValue, ScalarClauses, ScalarHit, ValType, ValueTest,
9    fold_facets, merge_claused, sort_facets,
10};
11
12use super::sync_segs;
13use crate::store::{Store, lock_write};
14use crate::{KevyError, KevyResult};
15
16/// One `FILTER` predicate: which stored value field it reads, and the
17/// test on it — the wire's `RANGE` / `EQ` shapes, in-process.
18///
19/// The bounds are raw bytes and are coerced with the type the field was
20/// DECLARED as, so a numeric range compares numerically rather than
21/// lexicographically.
22#[derive(Clone, Copy)]
23pub enum ValueFilter<'a> {
24    /// `field` between `min` and `max`, both inclusive.
25    Range {
26        /// The declared value field to read.
27        field: &'a [u8],
28        /// Lower bound, inclusive.
29        min: &'a [u8],
30        /// Upper bound, inclusive.
31        max: &'a [u8],
32    },
33    /// `field` exactly `value`.
34    Eq {
35        /// The declared value field to read.
36        field: &'a [u8],
37        /// The value to match.
38        value: &'a [u8],
39    },
40}
41
42impl ValueFilter<'_> {
43    pub(crate) fn field(&self) -> &[u8] {
44        match self {
45            ValueFilter::Range { field, .. } | ValueFilter::Eq { field, .. } => field,
46        }
47    }
48}
49
50/// One `FILTER` predicate resolved against the spec: the stored-value
51/// position it reads, and the test built with that field's DECLARED type.
52pub(crate) fn value_test(
53    spec: &IndexSpec,
54    f: &ValueFilter<'_>,
55) -> KevyResult<(usize, ValueTest)> {
56    let stored: Vec<&[u8]> = spec.values.iter().map(|v| v.name.as_slice()).collect();
57    let pos = spec
58        .values
59        .iter()
60        .position(|v| v.name == f.field())
61        .ok_or_else(|| unknown_field("FILTER", f.field(), "store", &stored))?;
62    let ty = spec.values[pos].ty;
63    // FILTER bounds speak the `@` time expressions on i64 fields —
64    // one grammar across both faces (and, through this shared
65    // resolver, the embedded Rust API too).
66    let now = (kevy_store::now_unix_ms() / 1000) as i64;
67    let (test, raw) = match f {
68        ValueFilter::Range { min, max, .. } => (ValueTest::range_at(ty, min, max, now), *min),
69        ValueFilter::Eq { value, .. } => (ValueTest::eq_at(ty, value, now), *value),
70    };
71    let test = test.ok_or_else(|| {
72        KevyError::InvalidInput(format!(
73            "FILTER bound '{}' is not a valid {}, which is how this index declares '{}'",
74            String::from_utf8_lossy(raw),
75            ty.tag(),
76            String::from_utf8_lossy(f.field()),
77        ))
78    })?;
79    Ok((pos, test))
80}
81
82/// The first clause field the spec does not store — the advise-log
83/// derivation for a refused [`resolve`]. Checked in the clause order
84/// [`resolve`] resolves in, so it names the same field the error does.
85fn unstored_field(spec: &IndexSpec, opts: &ScalarQueryOpts<'_>) -> Option<Vec<u8>> {
86    let stored = |f: &[u8]| spec.values.iter().any(|v| v.name == f);
87    for f in opts.filters {
88        if !stored(f.field()) {
89            return Some(f.field().to_vec());
90        }
91    }
92    if let Some((f, _)) = opts.sort
93        && !stored(f)
94    {
95        return Some(f.to_vec());
96    }
97    if let Some(f) = opts.distinct
98        && !stored(f)
99    {
100        return Some(f.to_vec());
101    }
102    opts.facets.iter().find(|f| !stored(f)).cloned()
103}
104
105/// A clause naming a field the index does not offer, saying what it does.
106pub(crate) fn unknown_field(clause: &str, bad: &[u8], verb: &str, offered: &[&[u8]]) -> KevyError {
107    let names: Vec<String> =
108        offered.iter().map(|n| String::from_utf8_lossy(n).into_owned()).collect();
109    KevyError::InvalidInput(format!(
110        "{clause} names field '{}', which this index does not {verb} — it {verb}es: {}",
111        String::from_utf8_lossy(bad),
112        names.join(", ")
113    ))
114}
115
116/// Everything a scalar RANGE/EQ query carries beyond its bounds and
117/// limit — the embedded twin of the wire's optional clauses.
118/// [`ScalarQueryOpts::default`] is the plain query.
119#[derive(Clone, Copy, Default)]
120pub struct ScalarQueryOpts<'a> {
121    /// `FILTER …`: non-scoring predicates over stored values, ANDed. A
122    /// row without the stored value fails — absent is not a value.
123    pub filters: &'a [ValueFilter<'a>],
124    /// `SORT <field> ASC|DESC`: order the page by a stored value; a row
125    /// with no usable value sorts last in both directions.
126    pub sort: Option<(&'a [u8], bool)>,
127    /// `DISTINCT <field>`: at most one row per coerced value; a row
128    /// with no value is its own group.
129    pub distinct: Option<&'a [u8]>,
130    /// `FACET <field…>`: count each field's values over the whole match
131    /// set (FILTER reduces the counts; DISTINCT does not).
132    pub facets: &'a [Vec<u8>],
133    /// `OFFSET n`: rows to skip before `limit` takes effect.
134    pub offset: usize,
135}
136
137impl ScalarQueryOpts<'_> {
138    /// Whether any clause reshapes the selection (the cursor-refusing
139    /// set — `FILTER` alone pages fine).
140    pub(crate) fn selects(&self) -> bool {
141        self.sort.is_some()
142            || self.distinct.is_some()
143            || !self.facets.is_empty()
144            || self.offset > 0
145    }
146}
147
148/// A clause-carrying query's answer: the page, per requested `FACET`
149/// field its `(value, count)` buckets, and — on the FILTER-with-cursor
150/// path — the cursor to resume from.
151#[derive(Debug)]
152pub struct ScalarPage {
153    /// The selected rows, in the page's order.
154    pub rows: Vec<(Vec<u8>, IndexValue)>,
155    /// One entry per requested facet field, most frequent first.
156    pub facets: Vec<Vec<(Vec<u8>, u64)>>,
157    /// Resume cursor (`None` under any selection clause, which refuses
158    /// cursors at the wire and pages nothing here either).
159    pub cursor: Option<Cursor>,
160}
161
162/// The unmerged union of the shards' pages plus the folded facet
163/// partials (the payload slot is `()` — the wire's hydration rides only
164/// the server's chunks).
165type GatheredPages = (Vec<(ScalarHit, ())>, Vec<Vec<FacetBucket>>);
166
167/// What the spec-dependent clauses resolve to.
168struct Resolved {
169    filters: Vec<(usize, ValueTest)>,
170    sort: Option<(usize, bool, ValType)>,
171    distinct: Option<(usize, ValType)>,
172    facets: Vec<(usize, ValType)>,
173}
174
175/// A clause's named stored-value field position + declared type.
176fn value_field(
177    spec: &IndexSpec,
178    clause: &str,
179    field: &[u8],
180) -> KevyResult<(usize, ValType)> {
181    let stored: Vec<&[u8]> = spec.values.iter().map(|v| v.name.as_slice()).collect();
182    let pos = spec
183        .values
184        .iter()
185        .position(|v| v.name == field)
186        .ok_or_else(|| unknown_field(clause, field, "store", &stored))?;
187    Ok((pos, spec.values[pos].ty))
188}
189
190fn resolve(spec: &IndexSpec, opts: &ScalarQueryOpts<'_>) -> KevyResult<Resolved> {
191    let filters =
192        opts.filters.iter().map(|f| value_test(spec, f)).collect::<KevyResult<Vec<_>>>()?;
193    let sort = match opts.sort {
194        Some((field, desc)) => {
195            let (pos, ty) = value_field(spec, "SORT", field)?;
196            Some((pos, desc, ty))
197        }
198        None => None,
199    };
200    let distinct = match opts.distinct {
201        Some(field) => Some(value_field(spec, "DISTINCT", field)?),
202        None => None,
203    };
204    let facets = opts
205        .facets
206        .iter()
207        .map(|f| value_field(spec, "FACET", f))
208        .collect::<KevyResult<Vec<_>>>()?;
209    Ok(Resolved { filters, sort, distinct, facets })
210}
211
212impl Store {
213    /// [`Store::idx_create`] with declared stored `VALUES` columns —
214    /// the scalar kinds' G1 capability (the catalog refuses the
215    /// declaration on kinds that carry no stored-value column).
216    pub fn idx_create_with_values(
217        &self,
218        name: &[u8],
219        prefix: &[u8],
220        field: &[u8],
221        ty: ValType,
222        kind: kevy_index::IndexKind,
223        values: &[(&[u8], ValType)],
224    ) -> KevyResult<()> {
225        if prefix.is_empty() {
226            return Err(KevyError::InvalidInput("empty prefix".into()));
227        }
228        let spec = IndexSpec {
229            name: name.to_vec(),
230            prefix: prefix.to_vec(),
231            fields: vec![kevy_index::FieldSpec::new(field.to_vec())],
232            ty,
233            kind,
234            max_bytes: 0,
235            ann: None,
236            group_by: None,
237            with_positions: false,
238            values: values
239                .iter()
240                .map(|(n, t)| kevy_index::ValueSpec { name: n.to_vec(), ty: *t })
241                .collect(),
242            composite: None,
243        };
244        self.register_spec(spec)
245    }
246
247    /// [`Store::idx_query`] with the stored-value clauses — the scalar
248    /// twin of [`Store::idx_match_faceted`]'s clause surface. Semantics
249    /// are the wire's: each shard selects with the clauses applied, the
250    /// union merges in the page's own order, `DISTINCT` re-collapses,
251    /// `OFFSET` drains after the merge, facet counts sum by coerced
252    /// identity. Only `FILTER` (with no other clause) is cursor-paged.
253    pub fn idx_query_claused(
254        &self,
255        name: &[u8],
256        min: &IndexValue,
257        max: &IndexValue,
258        cursor: Option<&Cursor>,
259        limit: usize,
260        opts: ScalarQueryOpts<'_>,
261    ) -> KevyResult<ScalarPage> {
262        let limit = limit.clamp(1, 100_000);
263        let offset = opts.offset.min(10_000);
264        let spec = self.claused_spec(name)?;
265        let r = self.claused_resolve(name, &spec, &opts)?;
266        let clauses = ScalarClauses {
267            filters: &r.filters,
268            sort: r.sort,
269            distinct: r.distinct,
270            facets: &r.facets,
271            fetch: limit + offset,
272        };
273        let (all, mut facets) = self.gather_claused(name, min, max, cursor, &clauses)?;
274        let sort_desc = r.sort.map(|(_, desc, _)| desc);
275        let all = merge_claused(all, sort_desc, r.distinct.is_some(), offset, limit);
276        sort_facets(&mut facets);
277        let next = (!opts.selects() && all.len() == limit)
278            .then(|| all.last().map(|(h, ())| Cursor { value: h.value.clone(), key: h.key.clone() }))
279            .flatten();
280        self.observe_hit(name);
281        Ok(ScalarPage {
282            rows: all.into_iter().map(|(h, ())| (h.key, h.value)).collect(),
283            facets: facets
284                .into_iter()
285                .map(|f| f.into_iter().map(|(_, label, n)| (label, n)).collect())
286                .collect(),
287            cursor: next,
288        })
289    }
290
291    /// [`Store::idx_count`] with `FILTER` applied — the total a
292    /// claused query's pages would reach, materializing nothing. The
293    /// consumer shape this closes: counting a filtered axis used to
294    /// mean fetching every page and taking its length.
295    pub fn idx_count_claused(
296        &self,
297        name: &[u8],
298        min: &IndexValue,
299        max: &IndexValue,
300        filters: &[ValueFilter<'_>],
301    ) -> KevyResult<u64> {
302        let spec = self.claused_spec(name)?;
303        let opts = ScalarQueryOpts { filters, ..ScalarQueryOpts::default() };
304        let r = self.claused_resolve(name, &spec, &opts)?;
305        let mut total = 0u64;
306        #[cfg(not(target_arch = "wasm32"))]
307        let probe = self.usage_cell(name);
308        self.for_each_segment_windowed(name, |spec, seg, win| {
309            total += seg.count_claused(min, max, &r.filters);
310            #[cfg(not(target_arch = "wasm32"))]
311            if let Some(w) = win {
312                crate::ops_index::advise::probe_window(&probe, w, min);
313            }
314            // The evicted half counts from the cold payloads — same
315            // predicates, frozen values; a corrupt segment refuses.
316            #[cfg(not(target_arch = "wasm32"))]
317            if let Some(w) = win.filter(|w| w.has_cold()) {
318                total += w
319                    .cold_claused_count(spec.ty, min, max, &r.filters)
320                    .map_err(|e| KevyError::Io(std::io::Error::other(e)))?;
321            }
322            #[cfg(target_arch = "wasm32")]
323            let _ = (spec, win);
324            Ok(())
325        })?;
326        self.observe_hit(name);
327        Ok(total)
328    }
329
330    /// The named index's spec, feeding the advise log (a Range
331    /// family) when the name is not declared.
332    fn claused_spec(&self, name: &[u8]) -> KevyResult<IndexSpec> {
333        let spec = {
334            let g = self.indexes.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner);
335            g.1.get(name).map(|(s, _)| s.clone())
336        };
337        spec.ok_or_else(|| {
338            self.observe_refused(name, kevy_index::AdviseShape::Range);
339            KevyError::NotFound("no such index".into())
340        })
341    }
342
343    /// [`resolve`], feeding the advise log when a clause named a
344    /// field the index does not store.
345    fn claused_resolve(
346        &self,
347        name: &[u8],
348        spec: &IndexSpec,
349        opts: &ScalarQueryOpts<'_>,
350    ) -> KevyResult<Resolved> {
351        resolve(spec, opts).inspect_err(|_| {
352            if let Some(f) = unstored_field(spec, opts) {
353                self.observe_refused(name, kevy_index::AdviseShape::Filter(f));
354            }
355        })
356    }
357
358    /// Every shard's claused page, unmerged, with the facet buckets
359    /// folded by identity as the shards report them.
360    fn gather_claused(
361        &self,
362        name: &[u8],
363        min: &IndexValue,
364        max: &IndexValue,
365        cursor: Option<&Cursor>,
366        clauses: &ScalarClauses<'_>,
367    ) -> KevyResult<GatheredPages> {
368        let mut all: Vec<(ScalarHit, ())> = Vec::new();
369        let mut facets: Vec<Vec<FacetBucket>> = vec![Vec::new(); clauses.facets.len()];
370        let mut found = false;
371        #[cfg(not(target_arch = "wasm32"))]
372        let probe = self.usage_cell(name);
373        for shard in self.shards.iter() {
374            let mut g = lock_write(shard);
375            let inner = &mut *g;
376            sync_segs(&self.indexes, &mut inner.idx_segs, &mut inner.store);
377            if let Some((_spec, seg)) = inner.idx_segs.segs.iter().find(|(s, _)| s.name == name) {
378                found = true;
379                #[cfg(not(target_arch = "wasm32"))]
380                if let Some(w) = inner.idx_segs.window_of(name) {
381                    crate::ops_index::advise::probe_window(&probe, w, min);
382                }
383                let page = seg.query_claused(min, max, cursor, clauses);
384                all.extend(page.hits.into_iter().map(|h| (h, ())));
385                fold_facets(&mut facets, page.facets);
386                // The shard's evicted half joins the union — the
387                // origin merge below re-orders, re-collapses and
388                // truncates the lot, so cold hits need no shard-level
389                // pre-merge here.
390                #[cfg(not(target_arch = "wasm32"))]
391                if let Some(w) = inner.idx_segs.window_of(name).filter(|w| w.has_cold()) {
392                    let (chits, cfacets) = w
393                        .cold_claused(_spec.ty, min, max, cursor, clauses)
394                        .map_err(|e| KevyError::Io(std::io::Error::other(e)))?;
395                    all.extend(chits.into_iter().map(|h| (h, ())));
396                    fold_facets(&mut facets, cfacets);
397                }
398            }
399        }
400        if !found {
401            return Err(KevyError::NotFound("no such index".into()));
402        }
403        Ok((all, facets))
404    }
405}