Skip to main content

kevy_window/
text.rs

1//! The text index's cold half on one shard: the per-bucket frozen
2//! segments a windowed table's out-of-window documents move into, the
3//! staleness shadow (bloom + per-segment tombstones), and the
4//! query-side contributions — corpus statistics for pass 1 and scored
5//! hits for pass 2, both on the injected-stats scale so cold and hot
6//! scores are comparable by construction.
7//!
8//! A tombstone is exact, not approximate: each frozen document also
9//! carries a NUL-prefixed forward record (`\0` ++ row key — tokens
10//! never start with NUL, so the namespaces cannot collide), and a
11//! staling write reads it back to withdraw that document's n_docs,
12//! total_len and per-term df from the segment's contribution. Pass-1
13//! statistics therefore stay equal to a never-windowed control's
14//! through rewrites, deletes and revivals. Shadows are per (row,
15//! segment): a revived row that later re-freezes into a NEW segment
16//! is live there while its stale entries stay dead.
17//!
18//! Cold text segments are derived spill (indexes rebuild on boot):
19//! a restart drops the previous run's set and re-freezes.
20
21use std::collections::{HashMap, HashSet};
22use std::path::Path;
23
24use kevy_index::ColdBloom;
25use kevy_text::TextSegment;
26use kevy_text::cold::decode_fwd;
27
28/// The manifest meta tag prefix cold text segments register under:
29/// `txtcold:<index-name>:<n_docs>:<total_len>`.
30const TXT_TAG: &[u8] = b"txtcold:";
31
32/// One open cold segment with its LIVE corpus contribution — the
33/// frozen numbers minus every tombstoned document's exact share.
34pub(super) struct ColdSeg {
35    pub(super) seg: kevy_seg::Seg,
36    pub(super) seq: u32,
37    pub(super) n_docs: u64,
38    pub(super) total_len: u64,
39}
40
41#[path = "text_query.rs"]
42mod query;
43pub use query::{ColdHit, ColdPage, ColdPageQuery};
44
45/// The frozen text segments for one windowed full-text index on one
46/// shard, plus the bloom and tombstones that let a query skip or correct
47/// them without opening a file.
48pub struct TextColdDir {
49    pub(super) segs: Vec<ColdSeg>,
50    seq: u32,
51    cleaned: bool,
52    bloom: ColdBloom,
53    /// row key → segment seqs whose frozen entries for it are dead.
54    pub(super) tombs: HashMap<Vec<u8>, HashSet<u32>>,
55    /// term → tombstoned document count, summed across segments; the
56    /// pass-1 df correction (header df is freeze-time truth).
57    pub(super) df_dead: HashMap<Vec<u8>, u32>,
58}
59
60impl Default for TextColdDir {
61    fn default() -> Self {
62        Self::new()
63    }
64}
65
66impl TextColdDir {
67    /// An empty directory: no segments, a fresh bloom, no tombstones.
68    pub fn new() -> Self {
69        Self {
70            segs: Vec::new(),
71            seq: 0,
72            cleaned: false,
73            bloom: ColdBloom::new(4096),
74            tombs: HashMap::new(),
75            df_dead: HashMap::new(),
76        }
77    }
78
79    /// Whether any segment has been sealed. `false` lets a query stay
80    /// entirely in the live index.
81    pub fn has_cold(&self) -> bool {
82        !self.segs.is_empty()
83    }
84
85    /// The write path saw this row change: shadow its frozen entries
86    /// and withdraw its statistics, exactly, in every segment that
87    /// holds it (its forward record says which, and what to subtract).
88    pub fn on_row_write(&mut self, row_key: &[u8]) {
89        if !self.bloom.contains(row_key) {
90            return;
91        }
92        let mut fwd_key = vec![0u8];
93        fwd_key.extend_from_slice(row_key);
94        for cs in &mut self.segs {
95            let shadowed = self.tombs.get(row_key).is_some_and(|s| s.contains(&cs.seq));
96            if shadowed {
97                continue;
98            }
99            let Ok(Some(payload)) = cs.seg.get(&fwd_key) else { continue };
100            let Some(rec) = decode_fwd(&payload) else { continue };
101            cs.n_docs = cs.n_docs.saturating_sub(1);
102            cs.total_len = cs.total_len.saturating_sub(u64::from(rec.dl));
103            for t in rec.terms {
104                *self.df_dead.entry(t).or_insert(0) += 1;
105            }
106            self.tombs.entry(row_key.to_vec()).or_default().insert(cs.seq);
107        }
108    }
109
110    /// Freeze `keys` out of the hot text segment into one sealed
111    /// bucket segment. Failure leaves the hot segment SHRUNK but the
112    /// batch unfrozen on disk — acceptable for derived spill (the
113    /// entries are rebuildable from rows), reported to the caller.
114    pub fn freeze_batch(
115        &mut self,
116        ts: &mut TextSegment,
117        index_name: &[u8],
118        keys: &[Vec<u8>],
119        segs_dir: &Path,
120    ) -> Result<bool, String> {
121        if !self.cleaned {
122            clean_stale(index_name, segs_dir)?;
123            self.cleaned = true;
124        }
125        let Some(bucket) = ts.freeze_docs(keys) else { return Ok(false) };
126        std::fs::create_dir_all(segs_dir).map_err(|e| e.to_string())?;
127        let file = format!("txt-{}-{}.seg", hex_stem(index_name), self.seq);
128        let seq = self.seq;
129        self.seq += 1;
130        let path = segs_dir.join(&file);
131        write_seg_file(&path, &bucket).inspect_err(|_| {
132            let _ = std::fs::remove_file(&path);
133        })?;
134        let mut m = kevy_seg::Manifest::open(segs_dir).map_err(|e| e.to_string())?;
135        let mut meta = TXT_TAG.to_vec();
136        meta.extend_from_slice(index_name);
137        meta.extend_from_slice(format!(":{}:{}", bucket.n_docs, bucket.total_len).as_bytes());
138        m.add(kevy_seg::ManifestEntry {
139            file: file.clone(),
140            meta,
141            min_key: bucket.fwd.keys().next().cloned().unwrap_or_default(),
142            max_key: bucket.terms.keys().next_back().cloned().unwrap_or_default(),
143            records: (bucket.fwd.len() + bucket.terms.len()) as u64,
144        })
145        .map_err(|e| e.to_string())?;
146        let seg = kevy_seg::Seg::open(&path).map_err(|e| format!("reopen {file}: {e}"))?;
147        self.segs.push(ColdSeg { seg, seq, n_docs: bucket.n_docs, total_len: bucket.total_len });
148        for k in keys {
149            self.bloom.insert(k);
150        }
151        Ok(true)
152    }
153}
154
155/// Write one bucket to disk: forward records first (`\0`-prefixed row
156/// keys sort before every token), then the term postings — the
157/// builder's ascending-key contract holds across the seam.
158fn write_seg_file(path: &Path, bucket: &kevy_text::cold::FrozenBucket) -> Result<(), String> {
159    let mut b = kevy_seg::SegBuilder::create(path).map_err(|e| e.to_string())?;
160    for (row_key, payload) in &bucket.fwd {
161        let mut k = vec![0u8];
162        k.extend_from_slice(row_key);
163        b.push(&k, payload).map_err(|e| e.to_string())?;
164    }
165    for (term, payload) in &bucket.terms {
166        b.push(term, payload).map_err(|e| e.to_string())?;
167    }
168    b.finish().map(|_| ()).map_err(|e| e.to_string())
169}
170
171/// Drop a previous run's cold text segments for `index_name` (derived
172/// spill: the rebuilt hot index holds everything again).
173fn clean_stale(index_name: &[u8], segs_dir: &Path) -> Result<(), String> {
174    if !segs_dir.exists() {
175        return Ok(());
176    }
177    let mut m = kevy_seg::Manifest::open(segs_dir).map_err(|e| e.to_string())?;
178    let mut tag = TXT_TAG.to_vec();
179    tag.extend_from_slice(index_name);
180    tag.push(b':');
181    let stale: Vec<String> =
182        m.live().filter(|e| e.meta.starts_with(&tag)).map(|e| e.file.clone()).collect();
183    for f in stale {
184        m.drop_seg(&f).map_err(|e| e.to_string())?;
185        let _ = std::fs::remove_file(segs_dir.join(&f));
186    }
187    Ok(())
188}
189
190fn hex_stem(name: &[u8]) -> String {
191    name.iter().map(|b| format!("{b:02x}")).collect()
192}