Skip to main content

kevy_window/
text_query.rs

1//! The cold directory's query face — what the two MATCH passes read
2//! out of the frozen buckets. Pass 1 takes the live corpus counters;
3//! pass 2 takes a whole clause-faithful page: bare terms and phrases
4//! accumulate (the hot engine's exact clause semantics, over the
5//! frozen postings), FILTER prunes on the frozen stored values,
6//! FACET counts the filtered match set, and selection runs in the
7//! page's own order — score order, or `sorted_order` under SORT, the
8//! same rule the hot top-K and the cross-shard merge use.
9//!
10//! A child module of [`super`] (`#[path]`), so it reaches the cold
11//! directory's private shape.
12
13use std::collections::HashMap;
14
15use kevy_text::cold::{decode_fwd, posting_df, score_cold, score_cold_phrase};
16use kevy_text::{CorpusStats, sorted_order};
17
18use super::TextColdDir;
19
20/// Everything pass 2 asks of the cold directory.
21pub struct ColdPageQuery<'a> {
22    /// Bare terms, sorted and deduplicated (the hot engine's rule).
23    pub bare: Vec<Vec<u8>>,
24    /// Each phrase's token sequence.
25    pub phrases: Vec<Vec<Vec<u8>>>,
26    /// The injected global statistics both passes score with.
27    pub stats: &'a CorpusStats,
28    /// `FILTER` predicates, ANDed, over the frozen stored values.
29    pub filter: &'a [kevy_text::Filter<'a>],
30    /// `SORT`: the page order is the sort key's, not the score's.
31    pub sort: Option<&'a kevy_text::Sort<'a>>,
32    /// `DISTINCT`: collapse to the best hit per value identity.
33    pub distinct: Option<&'a kevy_text::Distinct<'a>>,
34    /// `FACET` fields to count over the (filtered) match set.
35    pub facets: &'a [kevy_text::Facet<'a>],
36    /// How deep a page the merge needs (LIMIT + OFFSET).
37    pub fetch: usize,
38}
39
40/// One cold hit: its page-order ingredients, ready to merge.
41pub struct ColdHit {
42    /// The row key this hit points at.
43    pub key: Vec<u8>,
44    /// Its BM25 relevance. Comparable across segments because the
45    /// document-frequency corrections are applied before the merge, not
46    /// after — a per-segment score would not be.
47    pub score: f64,
48    /// The sort key, when the query sorts by a stored value.
49    pub okey: Option<Vec<u8>>,
50}
51
52/// The cold half of one shard's pass-2 answer.
53pub struct ColdPage {
54    /// Best `fetch` cold hits in the page's order.
55    pub hits: Vec<ColdHit>,
56    /// The returned hits' frozen stored values — what the merge reads
57    /// for sort/distinct identities and the origin's okeys/dkeys.
58    pub values: HashMap<Vec<u8>, Vec<Option<Vec<u8>>>>,
59    /// Per requested facet field, (identity, label, count) over the
60    /// filtered cold match set.
61    pub facets: Vec<Vec<kevy_text::Bucket>>,
62}
63
64impl TextColdDir {
65    /// Pass-1 contribution: summed LIVE docs/length plus per-token
66    /// live df across every cold segment (one fence descent per token
67    /// per segment; the doc/length halves are in-memory numbers, no
68    /// I/O at all).
69    pub fn cold_stats(&self, tokens: &[Vec<u8>]) -> (u64, u64, Vec<(Vec<u8>, u32)>) {
70        let n_docs: u64 = self.segs.iter().map(|c| c.n_docs).sum();
71        let total_len: u64 = self.segs.iter().map(|c| c.total_len).sum();
72        let df = tokens
73            .iter()
74            .map(|t| {
75                let frozen: u32 = self
76                    .segs
77                    .iter()
78                    .filter_map(|c| c.seg.get(t).ok().flatten())
79                    .filter_map(|p| posting_df(&p))
80                    .sum();
81                let dead = self.df_dead.get(t).copied().unwrap_or(0);
82                (t.clone(), frozen.saturating_sub(dead))
83            })
84            .collect();
85        (n_docs, total_len, df)
86    }
87
88    /// Pass-2 contribution: the clause-faithful cold page (see the
89    /// module doc for what each clause does here).
90    pub fn cold_page(&self, q: &ColdPageQuery) -> ColdPage {
91        let acc = self.accumulate(q);
92        let need_values = !q.filter.is_empty()
93            || q.sort.is_some()
94            || q.distinct.is_some()
95            || !q.facets.is_empty();
96        let mut values: HashMap<Vec<u8>, Vec<Option<Vec<u8>>>> = HashMap::new();
97        let mut cands: Vec<ColdHit> = Vec::new();
98        for (key, score) in acc {
99            let vals = if need_values {
100                let Some(v) = self.frozen_values(&key) else { continue };
101                if !passes(&v, q.filter) {
102                    continue;
103                }
104                Some(v)
105            } else {
106                None
107            };
108            let okey = q.sort.and_then(|s| vals.as_ref()?.get(s.field)?.as_deref().and_then(s.key));
109            if let Some(v) = vals {
110                values.insert(key.clone(), v);
111            }
112            cands.push(ColdHit { key, score, okey });
113        }
114        let facets = self.count_facets(q, &cands, &values);
115        order_page(&mut cands, q.sort.is_some(), q.sort.is_some_and(|s| s.desc));
116        if let Some(d) = q.distinct {
117            collapse(&mut cands, d, &values);
118        }
119        cands.truncate(q.fetch);
120        values.retain(|k, _| cands.iter().any(|c| &c.key == k));
121        ColdPage { hits: cands, values, facets }
122    }
123
124    /// Every clause's accumulated cold score, keyed by row key — the
125    /// mirror of the hot `accumulate_clauses` over the frozen postings.
126    fn accumulate(&self, q: &ColdPageQuery) -> HashMap<Vec<u8>, f64> {
127        let mut acc = HashMap::new();
128        for cs in &self.segs {
129            let dead = |k: &[u8]| self.tombs.get(k).is_some_and(|s| s.contains(&cs.seq));
130            for t in &q.bare {
131                if let Ok(Some(payload)) = cs.seg.get(t) {
132                    let _ = score_cold(&payload, t, q.stats, &dead, &mut acc);
133                }
134            }
135            for phrase in &q.phrases {
136                let payloads: Option<Vec<Vec<u8>>> =
137                    phrase.iter().map(|t| cs.seg.get(t).ok().flatten()).collect();
138                // A phrase token absent from this segment = the phrase
139                // matches nothing here (the rarest-anchor None mirror).
140                if let Some(payloads) = payloads {
141                    let _ = score_cold_phrase(&payloads, phrase, q.stats, &dead, &mut acc);
142                }
143            }
144        }
145        acc
146    }
147
148    /// One live cold document's frozen stored values, from whichever
149    /// segment holds its un-shadowed copy.
150    fn frozen_values(&self, key: &[u8]) -> Option<Vec<Option<Vec<u8>>>> {
151        let mut fwd_key = vec![0u8];
152        fwd_key.extend_from_slice(key);
153        for cs in &self.segs {
154            if self.tombs.get(key).is_some_and(|s| s.contains(&cs.seq)) {
155                continue;
156            }
157            if let Ok(Some(payload)) = cs.seg.get(&fwd_key) {
158                return decode_fwd(&payload).map(|r| r.values);
159            }
160        }
161        None
162    }
163
164    /// The cold half of each facet's count — the hot `count_facet`'s
165    /// rules (filter applies, top-K and DISTINCT do not), ordered the
166    /// same way; the shard merge sums it with the hot half.
167    fn count_facets(
168        &self,
169        q: &ColdPageQuery,
170        cands: &[ColdHit],
171        values: &HashMap<Vec<u8>, Vec<Option<Vec<u8>>>>,
172    ) -> Vec<Vec<kevy_text::Bucket>> {
173        q.facets
174            .iter()
175            .map(|f| {
176                let mut counts: HashMap<Vec<u8>, (Vec<u8>, u64)> = HashMap::new();
177                for c in cands {
178                    let Some(raw) =
179                        values.get(&c.key).and_then(|v| v.get(f.field)).and_then(Option::as_deref)
180                    else {
181                        continue;
182                    };
183                    let Some(k) = (f.key)(raw) else { continue };
184                    counts.entry(k).or_insert_with(|| (raw.to_vec(), 0)).1 += 1;
185                }
186                let mut out: Vec<kevy_text::Bucket> =
187                    counts.into_iter().map(|(k, (label, n))| (k, label, n)).collect();
188                out.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| a.1.cmp(&b.1)));
189                out
190            })
191            .collect()
192    }
193}
194
195/// Order candidates by the page's rule: `sorted_order` under SORT
196/// (a document WITH a value outranks one without, in both
197/// directions), else score-descending with the row key as tiebreak.
198fn order_page(cands: &mut [ColdHit], sorted: bool, desc: bool) {
199    if sorted {
200        cands.sort_by(|a, b| {
201            sorted_order((a.okey.as_deref(), &a.key), (b.okey.as_deref(), &b.key), desc)
202        });
203    } else {
204        cands.sort_by(|a, b| {
205            b.score
206                .partial_cmp(&a.score)
207                .unwrap_or(std::cmp::Ordering::Equal)
208                .then_with(|| a.key.cmp(&b.key))
209        });
210    }
211}
212
213/// Collapse an ordered candidate list to the best hit per distinct
214/// identity. A document with no value for the field is its own group
215/// (the hot rule: it has not been shown to share anything).
216fn collapse(
217    cands: &mut Vec<ColdHit>,
218    d: &kevy_text::Distinct,
219    values: &HashMap<Vec<u8>, Vec<Option<Vec<u8>>>>,
220) {
221    let mut seen: std::collections::HashSet<Vec<u8>> = std::collections::HashSet::new();
222    cands.retain(|c| {
223        let identity = values
224            .get(&c.key)
225            .and_then(|v| v.get(d.field))
226            .and_then(Option::as_deref)
227            .and_then(d.key);
228        match identity {
229            None => true,
230            Some(id) => seen.insert(id),
231        }
232    });
233}
234
235/// The hot `passes` mirror over frozen values: every predicate must
236/// pass, and an absent value never does.
237fn passes(values: &[Option<Vec<u8>>], filter: &[kevy_text::Filter]) -> bool {
238    filter
239        .iter()
240        .all(|f| values.get(f.field).and_then(Option::as_deref).is_some_and(|v| (f.test)(v)))
241}