Skip to main content

waratah_stats/
text_seed_sketch.rs

1//! Hierarchical Count-Min sketch over the text index's seed populations.
2//!
3//! One [`TextSeedSketch`] per text index build: two directions (forward
4//! seeds over the first `seed_chars` characters — the `text_begin` field —
5//! and reversed trailing seeds — the `text_end` field), each a stack of
6//! per-depth Count-Min sketches. Level ℓ counts the populations of ℓ-char
7//! prefixes; a rebuild inserts every seed into all of its prefix levels.
8//!
9//! # Why hierarchical: prefixes are range questions, CMS is keyed
10//!
11//! A plain CMS answers point queries ("how many inserts equaled this
12//! string") — hash functions destroy lexicographic structure, so querying
13//! one CMS built over full seeds with `"win"` returns collision noise
14//! only. Maintaining one CMS per prefix depth turns the range question
15//! into an exact-key question: `"win"` is a literal key of the depth-3
16//! sketch, incremented by exactly the seeds starting `win`. The levels
17//! compose: a level-ℓ count upper-bounds every longer family inside it,
18//! so an estimate takes the MINIMUM over the pattern's available levels —
19//! each level is a valid upper bound, and the min keeps the tightest.
20//!
21//! # Fixed size, by construction
22//!
23//! Both directions are `2 × L × d × w` u32 counters — 3,648,000 bytes at
24//! the landed constants (depth 8, 3 rows, 19,000 columns), regardless of
25//! corpus scale: 10M unique strings and 1B produce the same frame. There
26//! is no threshold dial and no wire-trim machinery; the frame is a known
27//! size that fits one gRPC message under tonic's default limits.
28//!
29//! # Count semantics and error contract
30//!
31//! Counts are **document postings observed by the build walk** (the same
32//! over-count contract as the geo cell histogram): a wipe rebuild posts
33//! each distinct indexed term once — exact populations — while ordinary
34//! writes add postings on top and deletes never retract (the join drops
35//! out-of-snapshot candidates; the index is a snapshot-blind superset,
36//! and so is this sketch).
37//!
38//! The CMS one-sided guarantee carries the whole design: every counter
39//! touched by an insert over-counts that key's true population by the
40//! collision mass in its cell, so a point query NEVER under-estimates,
41//! and the minimum over rows and levels preserves the property. The
42//! additive error is bounded by ≈ (total inserts / w) per row with high
43//! probability — store-scaled, like every consumer of the estimate (the
44//! cost bid compares against a sibling domain; road choices compare
45//! against pushed counts), so a store-scaled error keeps the decision in
46//! the same regime. u32 counters saturate upward (unreachable in
47//! practice: per-cell load at 1B strings is ~150k), which can only
48//! over-count — the safe direction.
49//!
50//! # Merge and delta
51//!
52//! Shard merge sums counters cell-wise (CMS is linear) and keeps the
53//! newer epoch; an additive rebuild collects its delta through
54//! [`TextSeedSketch::record`] and folds it in with
55//! [`TextSeedSketch::merge_delta`].
56//!
57//! # Hash stability
58//!
59//! The row hashes are explicit (FNV-1a over the key, splitmix64-mixed
60//! with a per-row salt) so sketches built by different processes merge —
61//! `RandomState`-style seeding would not. Any change to the mixer bumps
62//! [`SELF_VERSION`].
63
64use crate::StatsError;
65
66/// Self-contained section version (see `serde_bin`); bumped when this
67/// section's layout or hash mixer changes.
68const SELF_VERSION: u16 = 1;
69
70/// Prefix depths per direction. The sketch's depth must not exceed the
71/// index's `seed_chars` (enforced by carrying the build's effective depth
72/// in the section and capping inserts and queries at it) so an estimate
73/// is always an upper bound on the drain the index can actually resolve.
74pub const TEXT_SEED_SKETCH_DEPTH: usize = 8;
75
76/// Hash rows per level (the CMS depth `d`; failure probability per point
77/// query ≈ e^−d, and the min over levels compounds it further).
78pub const TEXT_SEED_SKETCH_ROWS: usize = 3;
79
80/// Counters per row (the CMS width `w`; additive error ≈ inserts/w).
81/// Landed so both directions fit one gRPC frame under tonic's default
82/// 4 MiB decode limit: 2 × 8 × 3 × 19,000 × 4 B = 3,648,000.
83pub const TEXT_SEED_SKETCH_WIDTH: usize = 19_000;
84
85/// One level's Count-Min grid: `d` rows × `w` saturating u32 counters.
86/// Row `i` hashes with its own salt; a point query takes the row minimum.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct LevelCms {
89    counters: Vec<u32>,
90}
91
92impl LevelCms {
93    fn empty() -> Self {
94        Self {
95            counters: vec![0; TEXT_SEED_SKETCH_ROWS * TEXT_SEED_SKETCH_WIDTH],
96        }
97    }
98
99    /// Stable row hash: FNV-1a over the key, splitmix64-finalized with a
100    /// per-row salt. Documented in the module doc — change bumps
101    /// [`SELF_VERSION`].
102    fn row_hash(key: &str, row: usize) -> u64 {
103        let mut h = 0xcbf29ce484222325u64;
104        for byte in key.as_bytes() {
105            h ^= u64::from(*byte);
106            h = h.wrapping_mul(0x100_0000_01b3);
107        }
108        let mut z = h ^ (row as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
109        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
110        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
111        z ^ (z >> 31)
112    }
113
114    /// Column for `key` in `row`: multiply-shift (no modulo, any width).
115    fn column(key: &str, row: usize) -> usize {
116        let h = Self::row_hash(key, row);
117        ((h as u128 * TEXT_SEED_SKETCH_WIDTH as u128) >> 64) as usize
118    }
119
120    /// Add `count` to the key's cell in every row. Saturating: a saturated
121    /// cell can only over-count (the one-sided contract survives).
122    fn add(&mut self, key: &str, count: u64) {
123        for row in 0..TEXT_SEED_SKETCH_ROWS {
124            let cell = row * TEXT_SEED_SKETCH_WIDTH + Self::column(key, row);
125            self.counters[cell] = self.counters[cell].saturating_add(count as u32);
126        }
127    }
128
129    /// Point estimate: the row minimum (never under the true count).
130    fn point(&self, key: &str) -> u64 {
131        (0..TEXT_SEED_SKETCH_ROWS)
132            .map(|row| {
133                u64::from(self.counters[row * TEXT_SEED_SKETCH_WIDTH + Self::column(key, row)])
134            })
135            .min()
136            .unwrap_or(0)
137    }
138
139    /// Cell-wise saturating sum (the CMS merge — linear in the inserts).
140    fn merge_from(&mut self, other: &Self) {
141        for (mine, theirs) in self.counters.iter_mut().zip(&other.counters) {
142            *mine = mine.saturating_add(*theirs);
143        }
144    }
145}
146
147/// One direction's stack of per-depth CMSes: `levels[ℓ]` counts the
148/// populations of (ℓ+1)-character prefixes.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct DirectionSketch {
151    /// Effective prefix depth — `min(TEXT_SEED_SKETCH_DEPTH, the build's
152    /// seed_chars)` — carried in the section so inserts and queries bound
153    /// at the same depth (a sketch deeper than the index's seed width
154    /// would price resolution the drain cannot deliver, and uninserted
155    /// deep levels would under-estimate).
156    max_depth: usize,
157    levels: Vec<LevelCms>,
158}
159
160impl DirectionSketch {
161    fn empty(max_depth: usize) -> Self {
162        Self {
163            max_depth,
164            levels: (0..max_depth).map(|_| LevelCms::empty()).collect(),
165        }
166    }
167
168    /// Insert one seed's population: every prefix level up to the
169    /// effective depth.
170    fn add_seed(&mut self, seed: &str, count: u64) {
171        let depth = self.max_depth.min(seed.chars().count());
172        let mut prefix = String::new();
173        for ch in seed.chars().take(depth) {
174            prefix.push(ch);
175            let level = prefix.chars().count() - 1;
176            self.levels[level].add(&prefix, count);
177        }
178    }
179
180    /// Estimate the population of `pattern`'s family: the minimum over
181    /// the pattern's available prefix levels (each a valid upper bound —
182    /// a shorter prefix's family contains every longer one — so the min
183    /// is the tightest bound and never under-estimates).
184    fn estimate(&self, pattern: &str) -> Option<u64> {
185        if pattern.is_empty() || self.max_depth == 0 {
186            // No level applies: the caller treats this as unpriced.
187            return None;
188        }
189        let depth = self.max_depth.min(pattern.chars().count());
190        let mut prefix = String::new();
191        let mut best = u64::MAX;
192        for ch in pattern.chars().take(depth) {
193            prefix.push(ch);
194            let level = prefix.chars().count() - 1;
195            best = best.min(self.levels[level].point(&prefix));
196        }
197        Some(best)
198    }
199
200    fn merge_from(&mut self, other: &Self) {
201        // The EMPTY sketch is the merge identity in BOTH directions, not a
202        // "shallower" one: an unbuilt side (max_depth 0 — a shard without
203        // a sketch, a store that never wrote the sidecar) contributes
204        // nothing, and merging with it must keep the populated side
205        // intact. Min-truncating against depth 0 would wipe all pricing
206        // in one order and never adopt in the other — the first
207        // partially-sketchless multi-shard rollup's silent failure.
208        if other.max_depth == 0 {
209            return;
210        }
211        if self.max_depth == 0 {
212            *self = other.clone();
213            return;
214        }
215        // The shallower effective depth governs (between two POPULATED
216        // sides only): a deeper-sketch's extra levels were never inserted
217        // by the shallower build, and pricing them would under-estimate.
218        self.max_depth = self.max_depth.min(other.max_depth);
219        self.levels.truncate(self.max_depth);
220        for (mine, theirs) in self.levels.iter_mut().zip(&other.levels) {
221            mine.merge_from(theirs);
222        }
223    }
224}
225
226/// Both directions for one text index build, stamped with that build's
227/// epoch. A consumer (the planner's `candidate_estimate`) prices from
228/// this sketch only while `epoch` matches the index's trusted epoch — a
229/// stale sketch is the unpriced path, never a stale answer.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct TextSeedSketch {
232    /// The build epoch this sketch was collected at; 0 = collected for an
233    /// unstamped (untrusted) build and must not price.
234    pub epoch: u64,
235    /// Forward-seed levels (the `text_begin` field's populations).
236    pub begin: DirectionSketch,
237    /// Reversed trailing-seed levels (the `text_end` field's).
238    pub end: DirectionSketch,
239}
240
241impl Default for TextSeedSketch {
242    fn default() -> Self {
243        Self::empty()
244    }
245}
246
247impl TextSeedSketch {
248    /// The empty sketch (no levels, no epoch): prices nothing.
249    pub fn empty() -> Self {
250        Self {
251            epoch: 0,
252            begin: DirectionSketch::empty(0),
253            end: DirectionSketch::empty(0),
254        }
255    }
256
257    /// A collecting sketch for a build with `seed_chars`, no epoch yet.
258    pub fn collector(seed_chars: usize) -> Self {
259        let max_depth = TEXT_SEED_SKETCH_DEPTH.min(seed_chars);
260        Self {
261            epoch: 0,
262            begin: DirectionSketch::empty(max_depth),
263            end: DirectionSketch::empty(max_depth),
264        }
265    }
266
267    /// Whether this sketch can price at `index_epoch`: trusted (non-zero
268    /// epoch) and stamped by the same build that stamped the index.
269    pub fn prices_at(&self, index_epoch: Option<u64>) -> bool {
270        self.epoch != 0 && self.epoch == index_epoch.unwrap_or(0)
271    }
272
273    /// Candidate population estimate for a prefix pattern. A pattern
274    /// longer than the sketch's depth prices from its deepest stored
275    /// prefix — an upper bound on the drain's population (the drain
276    /// resolves at the index's full seed width), the conservative
277    /// direction for every consumer. `None` = this sketch must not price
278    /// (empty, untrusted, or epoch mismatch); the caller keeps its
279    /// unpriced stamp.
280    pub fn estimate_prefix(&self, pattern: &str, index_epoch: Option<u64>) -> Option<u64> {
281        if !self.prices_at(index_epoch) {
282            return None;
283        }
284        self.begin.estimate(pattern)
285    }
286
287    /// Candidate population estimate for a suffix pattern: the pattern is
288    /// reversed first (the `end` direction stores reversed trailing
289    /// seeds, the same convention as the index's `text_end` field — see
290    /// `waratah_text_index::doc::suffix_seed_reversed`).
291    pub fn estimate_suffix(&self, pattern: &str, index_epoch: Option<u64>) -> Option<u64> {
292        if !self.prices_at(index_epoch) {
293            return None;
294        }
295        let reversed: String = pattern.chars().rev().collect();
296        self.end.estimate(&reversed)
297    }
298
299    /// Record one indexed document's seeds (posting count 1 each; the
300    /// collection loop calls this per walked document).
301    pub fn record(&mut self, lexical: &str) {
302        if let Some(seed) = forward_seed(lexical, self.begin.max_depth) {
303            self.begin.add_seed(&seed, 1);
304        }
305        if let Some(seed) = reverse_trailing_seed(lexical, self.end.max_depth) {
306            self.end.add_seed(&seed, 1);
307        }
308    }
309
310    /// Fold a delta sketch into this one (the additive-rebuild merge):
311    /// cell-wise sums, the shallower effective depth governs.
312    pub fn merge_delta(&mut self, delta: &Self) {
313        self.begin.merge_from(&delta.begin);
314        self.end.merge_from(&delta.end);
315    }
316
317    /// The additive-finish fold policy: merge an additive rebuild's delta
318    /// into the surviving base sketch. A `None` base — the sidecar was
319    /// never written, deleted mid-write, or undecodable — folds to
320    /// `None`: the delta alone prices only the NEW documents, and stamping
321    /// that partial population with the fresh build epoch would present it
322    /// as trusted (an under-estimate for every pre-existing term that no
323    /// gate can catch, because the epoch looks current). The caller writes
324    /// nothing on `None`, leaving the store unpriced until the next full
325    /// (wipe) rebuild collects every term — the same observable state as
326    /// "never built", including a first-ever additive rebuild on a brand
327    /// new index, which the same full rebuild heals.
328    pub fn fold_delta(base: Option<Self>, delta: Self) -> Option<Self> {
329        let mut base = base?;
330        base.merge_delta(&delta);
331        Some(base)
332    }
333
334    /// Shard merge: cell-wise sums in both directions, the newer epoch
335    /// governs the freshness gate (a shard without a sketch contributes
336    /// nothing — the empty sketch is the merge identity in BOTH orders:
337    /// populated ⋈ empty keeps the accumulator intact, empty ⋈ populated
338    /// adopts it).
339    pub fn merge(&mut self, other: &Self) {
340        self.epoch = self.epoch.max(other.epoch);
341        self.begin.merge_from(&other.begin);
342        self.end.merge_from(&other.end);
343    }
344
345    /// Whether this sketch can price anything at all (an epoch was
346    /// stamped): the empty default has none.
347    pub fn is_empty(&self) -> bool {
348        self.epoch == 0
349    }
350
351    /// Encode a self-versioned section (see the geo histogram's
352    /// `encode_body` for the frame convention). Fixed size by
353    /// construction; raw little-endian counters.
354    pub fn encode_body(&self, out: &mut Vec<u8>) {
355        out.extend_from_slice(&SELF_VERSION.to_le_bytes());
356        out.extend_from_slice(&self.epoch.to_le_bytes());
357        let encode_direction = |direction: &DirectionSketch, out: &mut Vec<u8>| {
358            out.extend_from_slice(&(direction.max_depth as u16).to_le_bytes());
359            for level in &direction.levels {
360                for counter in &level.counters {
361                    out.extend_from_slice(&counter.to_le_bytes());
362                }
363            }
364        };
365        encode_direction(&self.begin, out);
366        encode_direction(&self.end, out);
367    }
368
369    /// Decode a section produced by [`Self::encode_body`]; consumes
370    /// exactly its own bytes (trailing input belongs to the caller).
371    pub fn decode_body(buf: &mut &[u8]) -> Result<Self, StatsError> {
372        let corrupt = |what: &str| StatsError::Corrupt(format!("text seed sketch: {what}"));
373        if buf.len() < 10 {
374            return Err(corrupt("truncated header"));
375        }
376        let version = u16::from_le_bytes(buf[..2].try_into().expect("2-byte slice"));
377        if version != SELF_VERSION {
378            return Err(corrupt(&format!("unsupported section version {version}")));
379        }
380        let epoch = u64::from_le_bytes(buf[2..10].try_into().expect("8-byte slice"));
381        *buf = &buf[10..];
382        let decode_direction = |buf: &mut &[u8]| -> Result<DirectionSketch, StatsError> {
383            if buf.len() < 2 {
384                return Err(corrupt("truncated direction header"));
385            }
386            let max_depth = u16::from_le_bytes(buf[..2].try_into().expect("2-byte slice")) as usize;
387            *buf = &buf[2..];
388            if max_depth > TEXT_SEED_SKETCH_DEPTH {
389                return Err(corrupt("depth over the section constant"));
390            }
391            let mut levels = Vec::with_capacity(max_depth);
392            for _ in 0..max_depth {
393                let take = TEXT_SEED_SKETCH_ROWS * TEXT_SEED_SKETCH_WIDTH;
394                if buf.len() < take * 4 {
395                    return Err(corrupt("truncated counters"));
396                }
397                let counters: Vec<u32> = buf[..take * 4]
398                    .chunks_exact(4)
399                    .map(|c| u32::from_le_bytes(c.try_into().expect("4-byte chunk")))
400                    .collect();
401                *buf = &buf[take * 4..];
402                levels.push(LevelCms { counters });
403            }
404            Ok(DirectionSketch { max_depth, levels })
405        };
406        let begin = decode_direction(buf)?;
407        let end = decode_direction(buf)?;
408        Ok(Self { epoch, begin, end })
409    }
410}
411
412/// The first `depth` characters of `lexical` (the index's `text_begin`
413/// seed derivation, reproduced here so collection needs no text crates).
414fn forward_seed(lexical: &str, depth: usize) -> Option<String> {
415    let prefix: String = lexical.chars().take(depth).collect();
416    (prefix.chars().next().is_some()).then_some(prefix)
417}
418
419/// The last `depth` characters of `lexical`, reversed (the index's
420/// `text_end` convention — see `waratah_text_index::doc::suffix_seed_reversed`).
421fn reverse_trailing_seed(lexical: &str, depth: usize) -> Option<String> {
422    let suffix: String = lexical.chars().rev().take(depth).collect();
423    (suffix.chars().next().is_some()).then_some(suffix)
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429
430    /// Build a small collector and record a corpus; a helper mirroring
431    /// the rebuild loop.
432    fn build_from(seed_chars: usize, lexicals: &[&str]) -> TextSeedSketch {
433        let mut sketch = TextSeedSketch::collector(seed_chars);
434        for lexical in lexicals {
435            sketch.record(lexical);
436        }
437        sketch
438    }
439
440    #[test]
441    fn point_estimates_never_under_and_near_exact_on_sparse_corpora() {
442        // 300 "aa…" seeds and 200 "b…" seeds over w=19,000 columns:
443        // expected collision mass per cell ≈ 500/19,000 ≈ 0.03 — the row
444        // minimum makes exactness the common case, and the NEVER-UNDER
445        // property is unconditional.
446        let mut lexicals: Vec<String> = Vec::new();
447        for i in 0..300 {
448            lexicals.push(format!("aa{i:04}"));
449        }
450        for i in 0..200 {
451            lexicals.push(format!("b{i:04}"));
452        }
453        let refs: Vec<&str> = lexicals.iter().map(|s| s.as_str()).collect();
454        let sketch = build_from(16, &refs);
455        for (probe, truth) in [("aa", 300u64), ("aa0001", 1), ("b", 200), ("b0042", 1)] {
456            let estimate = sketch.begin.estimate(probe).expect("non-empty probe");
457            assert!(
458                estimate >= truth,
459                "{probe}: estimate {estimate} < truth {truth} (never-under violated)"
460            );
461            assert!(
462                estimate <= truth + 20,
463                "{probe}: estimate {estimate} drifted far past truth {truth} on a sparse corpus"
464            );
465        }
466        // A family that does not exist estimates ~0 (pure noise floor).
467        assert!(sketch.begin.estimate("zz").expect("probe") <= 5);
468    }
469
470    #[test]
471    fn estimate_takes_the_minimum_over_levels() {
472        // The depth-2 family "wi" (3 postings) sits inside the depth-1
473        // family "w" (5 postings): the estimate for "wi" must read the
474        // deeper, tighter level, not the ancestor's count.
475        let sketch = build_from(16, &["windy", "winter", "wisp", "water", "walrus"]);
476        assert!(
477            sketch.begin.estimate("wi").expect("probe") <= 3 + 5,
478            "tighter than the ancestor"
479        );
480        assert!(
481            sketch.begin.estimate("w").expect("probe") >= 5,
482            "ancestor still bounds"
483        );
484    }
485
486    #[test]
487    fn depth_is_bounded_by_the_builds_seed_chars() {
488        // seed_chars 4: only levels 1..=4 exist and price; a longer
489        // pattern prices from its 4-char prefix (an upper bound on the
490        // 4-wide drain the index can resolve).
491        let mut sketch = TextSeedSketch::collector(4);
492        assert_eq!(sketch.begin.max_depth, 4);
493        sketch.record("abcdefgh");
494        assert_eq!(sketch.begin.levels.len(), 4);
495        assert!(
496            sketch.begin.estimate("abcdef").expect("probe") >= 1,
497            "long pattern bounds via depth 4"
498        );
499    }
500
501    #[test]
502    fn record_is_a_no_op_for_empty_lexicals() {
503        let mut sketch = TextSeedSketch::collector(16);
504        sketch.record("");
505        assert!(
506            sketch.begin.estimate("a").expect("probe") <= 5,
507            "nothing inserted, noise floor only"
508        );
509    }
510
511    #[test]
512    fn merge_sums_counters_and_keeps_the_newer_epoch() {
513        let left = build_from(16, &["windy", "windy", "sunny"]);
514        let mut right = build_from(16, &["windy", "rainy"]);
515        right.epoch = 7;
516        let mut merged = left;
517        merged.epoch = 3;
518        merged.merge(&right);
519        assert_eq!(merged.epoch, 7, "the newer build governs the gate");
520        assert!(
521            merged.begin.estimate("windy").expect("probe") >= 3,
522            "three windy postings across shards"
523        );
524        assert!(merged.begin.estimate("rainy").expect("probe") >= 1);
525        // The never-under property survives the merge.
526        assert!(merged.begin.estimate("sunny").expect("probe") >= 1);
527    }
528
529    #[test]
530    fn merge_with_an_empty_sketch_is_the_identity_in_both_directions() {
531        // M4's contract: a shard without a sketch contributes nothing.
532        // Under min-depth truncation the empty side (max_depth 0) wiped
533        // all pricing in one order and was never adopted in the other —
534        // the first partially-sketchless multi-shard rollup silently
535        // disabled the feature.
536        let populated_epoch = {
537            let mut sketch = build_from(16, &["windy", "sunny", "stormy"]);
538            sketch.epoch = 9;
539            sketch
540        };
541
542        // populated ⋈ empty: every estimate and the depth survive.
543        let mut keep = populated_epoch.clone();
544        keep.merge(&TextSeedSketch::empty());
545        assert!(keep.begin.estimate("windy").expect("probe") >= 1);
546        assert!(keep.begin.estimate("stormy").expect("probe") >= 1);
547        assert_eq!(
548            keep.begin.levels.len(),
549            populated_epoch.begin.levels.len(),
550            "merge depth kept against an empty side"
551        );
552        assert_eq!(keep.epoch, 9, "the populated side's epoch survives");
553
554        // empty ⋈ populated: the populated shard is adopted wholesale.
555        let mut adopt = TextSeedSketch::empty();
556        adopt.merge(&populated_epoch);
557        assert!(adopt.begin.estimate("windy").expect("probe") >= 1);
558        assert!(adopt.begin.estimate("sunny").expect("probe") >= 1);
559        assert_eq!(
560            adopt.begin.levels.len(),
561            populated_epoch.begin.levels.len(),
562            "adoption carries the populated depth"
563        );
564        assert_eq!(adopt.epoch, 9, "epoch max picks up the adopted side's");
565    }
566
567    #[test]
568    fn fold_delta_refuses_a_baseless_delta() {
569        // M1's contract: an additive rebuild with NO surviving base folds
570        // to None — the delta alone prices only the new documents, and
571        // stamping it with the fresh epoch would present a partial
572        // population as trusted. The caller writes nothing, so the store
573        // stays unpriced until a full rebuild.
574        let delta = build_from(16, &["windy", "sunny"]);
575        assert!(TextSeedSketch::fold_delta(None, delta).is_none());
576    }
577
578    #[test]
579    fn fold_delta_folds_into_a_surviving_base() {
580        let base = build_from(16, &["windy", "sunny"]);
581        let delta = build_from(16, &["windy", "stormy"]);
582        let folded = TextSeedSketch::fold_delta(Some(base), delta).expect("a surviving base folds");
583        assert!(folded.begin.estimate("windy").expect("probe") >= 2);
584        assert!(folded.begin.estimate("sunny").expect("probe") >= 1);
585        assert!(folded.begin.estimate("stormy").expect("probe") >= 1);
586    }
587
588    #[test]
589    fn merge_delta_folds_an_additive_rebuild() {
590        let mut base = build_from(16, &["windy", "sunny"]);
591        base.epoch = 5;
592        let delta = build_from(16, &["windy", "stormy"]);
593        base.merge_delta(&delta);
594        assert!(
595            base.begin.estimate("windy").expect("probe") >= 2,
596            "delta folded in"
597        );
598        assert!(base.begin.estimate("stormy").expect("probe") >= 1);
599        assert!(
600            base.begin.estimate("sunny").expect("probe") >= 1,
601            "base mass kept"
602        );
603    }
604
605    #[test]
606    fn encode_decode_roundtrip_and_rejects() {
607        let mut sketch = build_from(16, &["windy", "sunny", "stormy", "rainy"]);
608        sketch.epoch = 1794192803976;
609        let mut buf = Vec::new();
610        sketch.encode_body(&mut buf);
611        // Fixed size: header 10 + two directions of 8 levels × 3 × 19,000
612        // counters × 4 bytes + two depth fields.
613        assert_eq!(
614            buf.len(),
615            10 + 2
616                * (2 + TEXT_SEED_SKETCH_DEPTH * TEXT_SEED_SKETCH_ROWS * TEXT_SEED_SKETCH_WIDTH * 4),
617            "fixed frame size by construction"
618        );
619        let mut slice = buf.as_slice();
620        let decoded = TextSeedSketch::decode_body(&mut slice).expect("decodes");
621        assert_eq!(decoded, sketch);
622        assert!(slice.is_empty(), "consumes exactly its own bytes");
623        // Version mismatch rejects.
624        let mut bad = buf.clone();
625        bad[0] = 0xFF;
626        assert!(TextSeedSketch::decode_body(&mut bad.as_slice()).is_err());
627        // Truncation rejects.
628        let mut truncated = buf.as_slice();
629        truncated = &truncated[..truncated.len() - 3];
630        assert!(TextSeedSketch::decode_body(&mut truncated).is_err());
631    }
632
633    #[test]
634    fn epoch_gate_prices_only_matching_builds() {
635        let mut sketch = TextSeedSketch::empty();
636        assert!(!sketch.prices_at(Some(7)));
637        assert!(sketch.estimate_prefix("win", Some(7)).is_none());
638        sketch = build_from(16, &["windy"]);
639        sketch.epoch = 7;
640        assert!(sketch.prices_at(Some(7)));
641        assert!(sketch.estimate_prefix("win", Some(7)).is_some());
642        assert!(sketch.estimate_prefix("win", Some(9)).is_none());
643        assert!(sketch.estimate_prefix("win", None).is_none());
644        sketch.epoch = 0;
645        assert!(sketch.estimate_prefix("win", Some(0)).is_none());
646    }
647
648    #[test]
649    fn suffix_lookup_reverses_like_the_index_field() {
650        // The end direction stores REVERSED trailing seeds, and the query
651        // is reversed then PREFIX-queried — the same convention as the
652        // drain's `suffix_pattern_seed_reversed`. STRENDS semantics:
653        // "donkey" ends with "key" AND "nkey"; "spanky" ends with "nky",
654        // NOT "key" (it ends 'n-k-y').
655        let mut sketch = build_from(16, &["spanky", "donkey", "key"]);
656        sketch.epoch = 5;
657        assert!(
658            sketch.estimate_suffix("key", Some(5)).unwrap() >= 2,
659            "donkey, key"
660        );
661        assert!(
662            sketch.estimate_suffix("nky", Some(5)).unwrap() >= 1,
663            "spanky"
664        );
665        assert!(
666            sketch.estimate_suffix("an", Some(5)).unwrap() <= 1,
667            "no literal ends 'an'"
668        );
669    }
670
671    #[test]
672    fn super_seed_pattern_prices_as_its_deepest_prefix_population() {
673        // A 29-char pattern over an 8-deep sketch: the estimate comes from
674        // the 8-char prefix's family — an upper bound on the drain (which
675        // resolves at the index's 16-char seed), the documented
676        // conservatism.
677        let mut lexicals: Vec<String> = Vec::new();
678        for i in 0..2000 {
679            lexicals.push(format!("eco-watchdataset1{i:08}"));
680        }
681        let refs: Vec<&str> = lexicals.iter().map(|s| s.as_str()).collect();
682        let mut sketch = build_from(16, &refs);
683        sketch.epoch = 9;
684        let long = "eco-watchdataset1submission30-extra-chars";
685        let estimate = sketch.estimate_prefix(long, Some(9)).expect("prices");
686        assert!(estimate >= 2000, "bounds the whole family");
687        assert!(
688            estimate <= 2000 + 200,
689            "near-exact on this corpus (noise ≈ 2200 inserts / 19000 columns)"
690        );
691    }
692
693    #[test]
694    fn frame_fits_the_grpc_default_limit() {
695        let mut buf = Vec::new();
696        TextSeedSketch::empty().encode_body(&mut buf);
697        // The 4 MiB tonic default decode limit — the sizing invariant the
698        // width constant exists to respect (both directions populated).
699        let full = 10
700            + 2 * (2 + TEXT_SEED_SKETCH_DEPTH * TEXT_SEED_SKETCH_ROWS * TEXT_SEED_SKETCH_WIDTH * 4);
701        assert!(
702            full <= 4 * 1024 * 1024,
703            "frame {full} over the default limit"
704        );
705        assert!(full <= 3_670_016, "frame {full} over the 3.5 MiB policy");
706    }
707}