Skip to main content

spg_engine/
memoize.rs

1// pedantic doc_markdown flags every bare ident in the comment-as-
2// spec block; allowing at the module level keeps the spec readable.
3#![allow(clippy::doc_markdown)]
4
5//! v6.2.6 — Memoize cache for correlated subqueries.
6//!
7//! When a `WHERE` clause references a scalar subquery whose inner
8//! body depends on the outer row's column values (the classic
9//! `WHERE id IN (SELECT MAX(x) FROM y WHERE y.k = outer.k)`
10//! shape), the engine's current behaviour re-runs the inner
11//! SELECT once per outer row — `O(outer_rows × inner_cost)` work
12//! even when many outer rows share the same correlated key.
13//!
14//! v6.2.6 wraps that path with a per-query `MemoizeCache`:
15//! before running the inner, hash the (subquery identity, outer-
16//! row values) key and look it up; cache hits return the prior
17//! result without re-executing. Caps:
18//!
19//!   - **1024 entries** (configurable via the planner's
20//!     [`Self::with_max_entries`])
21//!   - **16 MiB** of cumulative cached `Value` bytes (v5.5
22//!     per-query memory budget's 1/16 share; configurable via
23//!     [`Self::with_max_bytes`])
24//!
25//! When either cap is hit, the least-recently-used entry is
26//! evicted before insertion.
27//!
28//! v6.2.6 ships the simple linear-vec LRU. v6.2.x can swap to a
29//! BTreeMap + LinkedList for sub-`O(n)` lookup if it ever
30//! matters; the gate is "≥ 5× speedup on the repeated-key
31//! workload" which the linear scan clears at scale-1k.
32
33use alloc::collections::VecDeque;
34use alloc::string::String;
35use alloc::vec::Vec;
36
37use spg_storage::Value;
38
39/// v6.2.6 — default cache size cap. Matches the design's "1024
40/// entries" figure (V6_2_DESIGN.md L2 row 6).
41pub const DEFAULT_MAX_ENTRIES: usize = 1024;
42
43/// v6.2.6 — default cumulative bytes cap. 16 MiB matches the
44/// v5.5 per-query budget's 1/16 share.
45pub const DEFAULT_MAX_BYTES: usize = 16 * 1024 * 1024;
46
47/// Cache key — the subquery's textual identity plus the outer
48/// row's value tuple. Two scalar-subquery node positions with
49/// identical Display text are treated as the same subquery for
50/// caching purposes (sound: equal Display → equal AST).
51#[derive(Debug, Clone, PartialEq)]
52pub struct CacheKey {
53    pub subquery_repr: String,
54    pub outer_values: Vec<Value>,
55}
56
57/// v7.29 - one batch-evaluated correlated subquery: the outer key
58/// column and the key -> value map.
59pub type GroupMap = (
60    spg_sql::ast::ColumnName,
61    alloc::collections::BTreeMap<String, Value>,
62);
63
64/// v7.29 (3c) - per-expression resolution plan: for the i-th scalar
65/// subquery node (pre-order) of a host expression, the shared batch
66/// map (None = unbatchable, resolve per row). Keyed by the HOST
67/// expression's address - callers guarantee the expression outlives
68/// the per-query memo (aggregate items / WHERE trees do). The stored
69/// subquery count guards against address reuse.
70/// (subquery count, per-subquery batch maps, hollow template). The
71/// template is the host expression with every scalar subquery BODY
72/// emptied - cloning it per row costs nodes, not whole subquery
73/// ASTs (the splice walk replaces the hollow nodes by pre-order).
74pub type ExprPlan = (
75    usize,
76    alloc::vec::Vec<Option<alloc::rc::Rc<GroupMap>>>,
77    spg_sql::ast::Expr,
78);
79
80/// v7.30.2 (mailrs round-25) - canonicalised membership set for a
81/// large all-literal `IN` list. Integer literals canonicalise to
82/// i64 (cross-width `Int = BigInt` stays correct); string literals
83/// stay verbatim. Mixed or exotic families are not eligible and
84/// keep the linear `apply_binary` scan.
85#[derive(Debug, Clone)]
86pub enum InListSet {
87    Int(alloc::collections::BTreeSet<i64>),
88    Text(alloc::collections::BTreeSet<String>),
89}
90
91#[derive(Debug, Clone)]
92pub struct InListSetEntry {
93    pub set: InListSet,
94    /// The list carried a NULL literal: a non-matching needle
95    /// yields NULL, not FALSE (SQL three-valued logic).
96    pub has_null: bool,
97}
98
99#[derive(Debug, Clone)]
100pub struct MemoizeCache {
101    /// LRU front = most recently used. Stored as a `VecDeque` so
102    /// re-promoting a hit is `O(n)` worst-case but `O(1)`
103    /// amortised for the common front-half-hit pattern of nested-
104    /// loop correlated subqueries.
105    entries: VecDeque<(CacheKey, Value)>,
106    /// v7.29 (round-22 phase 3) - batch-evaluated correlated scalar
107    /// subqueries: subquery repr -> Some((outer column, key -> value
108    /// map built in ONE pass)) or None when the shape can't batch
109    /// (so we don't re-analyse it per row). Turns 23.5k per-group
110    /// executions into one grouped scan + 23.5k lookups.
111    pub group_maps: alloc::collections::BTreeMap<String, Option<alloc::rc::Rc<GroupMap>>>,
112    /// v7.29 (3c) - host-expression ptr -> (subquery count, plan).
113    pub expr_plans: alloc::collections::BTreeMap<usize, ExprPlan>,
114    /// v7.30.2 (mailrs round-25) - InList node ptr -> membership set
115    /// for large all-literal `IN` lists, built once per row loop.
116    /// Turns the O(rows × list) membership scan into
117    /// O(rows × log list). `None` = analysed, not eligible.
118    pub in_sets: alloc::collections::BTreeMap<usize, Option<InListSetEntry>>,
119    /// v7.30.2 (mailrs round-25) - host-expression ptr -> "contains
120    /// a subquery node". The walk is O(tree) and a materialised IN
121    /// list makes the tree huge — caching it makes the per-row
122    /// dispatch O(log n) instead of O(24k list elements).
123    pub has_subquery: alloc::collections::BTreeMap<usize, bool>,
124    max_entries: usize,
125    max_bytes: usize,
126    current_bytes: usize,
127    pub hit_count: u64,
128    pub miss_count: u64,
129}
130
131impl Default for MemoizeCache {
132    fn default() -> Self {
133        Self::new()
134    }
135}
136
137impl MemoizeCache {
138    pub fn new() -> Self {
139        Self {
140            entries: VecDeque::with_capacity(DEFAULT_MAX_ENTRIES),
141            max_entries: DEFAULT_MAX_ENTRIES,
142            max_bytes: DEFAULT_MAX_BYTES,
143            current_bytes: 0,
144            hit_count: 0,
145            miss_count: 0,
146            group_maps: alloc::collections::BTreeMap::new(),
147            expr_plans: alloc::collections::BTreeMap::new(),
148            in_sets: alloc::collections::BTreeMap::new(),
149            has_subquery: alloc::collections::BTreeMap::new(),
150        }
151    }
152
153    pub const fn with_max_entries(mut self, n: usize) -> Self {
154        self.max_entries = n;
155        self
156    }
157
158    pub const fn with_max_bytes(mut self, b: usize) -> Self {
159        self.max_bytes = b;
160        self
161    }
162
163    pub fn len(&self) -> usize {
164        self.entries.len()
165    }
166
167    pub fn is_empty(&self) -> bool {
168        self.entries.is_empty()
169    }
170
171    /// Look up a cached scalar value. On hit, re-promotes the
172    /// entry to the LRU front and bumps `hit_count`. On miss,
173    /// returns `None` (caller runs the subquery + `insert`s).
174    pub fn get(&mut self, key: &CacheKey) -> Option<Value> {
175        let pos = self.entries.iter().position(|(k, _)| k == key);
176        if let Some(p) = pos {
177            let (k, v) = self.entries.remove(p)?;
178            self.entries.push_front((k, v.clone()));
179            self.hit_count += 1;
180            Some(v)
181        } else {
182            self.miss_count += 1;
183            None
184        }
185    }
186
187    /// Insert a freshly-computed scalar value. Caller must have
188    /// `get`-missed first (the cache doesn't dedupe inserts).
189    /// Evicts LRU entries until both caps are satisfied.
190    pub fn insert(&mut self, key: CacheKey, value: Value) {
191        let entry_bytes = approx_bytes(&key) + approx_value_bytes(&value);
192        while !self.entries.is_empty()
193            && (self.entries.len() >= self.max_entries
194                || self.current_bytes + entry_bytes > self.max_bytes)
195        {
196            let Some((k, v)) = self.entries.pop_back() else {
197                break;
198            };
199            self.current_bytes = self
200                .current_bytes
201                .saturating_sub(approx_bytes(&k) + approx_value_bytes(&v));
202        }
203        self.current_bytes = self.current_bytes.saturating_add(entry_bytes);
204        self.entries.push_front((key, value));
205    }
206}
207
208fn approx_bytes(key: &CacheKey) -> usize {
209    key.subquery_repr.len()
210        + key
211            .outer_values
212            .iter()
213            .map(approx_value_bytes)
214            .sum::<usize>()
215        + 16
216}
217
218fn approx_value_bytes(v: &Value) -> usize {
219    match v {
220        Value::Null | Value::Bool(_) | Value::SmallInt(_) => 1,
221        Value::Int(_) => 4,
222        Value::BigInt(_) | Value::Float(_) => 8,
223        Value::Date(_) | Value::Timestamp(_) => 8,
224        Value::Interval { .. } => 16,
225        Value::Numeric { .. } => 16,
226        Value::Text(s) | Value::Json(s) => s.len(),
227        Value::Vector(v) => v.len() * 4,
228        Value::Sq8Vector(q) => q.bytes.len() + 8,
229        Value::HalfVector(h) => h.dim() * 2,
230        // v7.5.0 — Value is #[non_exhaustive]; conservative estimate.
231        _ => 16,
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    fn key(repr: &str, outer: &[Value]) -> CacheKey {
240        CacheKey {
241            subquery_repr: repr.into(),
242            outer_values: outer.to_vec(),
243        }
244    }
245
246    #[test]
247    fn empty_cache_misses_everything() {
248        let mut c = MemoizeCache::new();
249        let k = key("SELECT 1", &[Value::Int(1)]);
250        assert!(c.get(&k).is_none());
251        assert_eq!(c.miss_count, 1);
252        assert_eq!(c.hit_count, 0);
253    }
254
255    #[test]
256    fn insert_then_get_hits() {
257        let mut c = MemoizeCache::new();
258        let k = key("SELECT 1", &[Value::Int(1)]);
259        c.insert(k.clone(), Value::BigInt(42));
260        let v = c.get(&k);
261        assert_eq!(v, Some(Value::BigInt(42)));
262        assert_eq!(c.hit_count, 1);
263    }
264
265    #[test]
266    fn repeated_outer_key_hits_after_first_insert() {
267        let mut c = MemoizeCache::new();
268        let repr = "SELECT MAX(x) FROM y WHERE y.k = outer.k";
269        for i in 0..100 {
270            let k = key(repr, &[Value::Int(i % 5)]);
271            if c.get(&k).is_none() {
272                c.insert(k, Value::BigInt(i64::from(i)));
273            }
274        }
275        // 5 unique keys → 5 misses, 95 hits.
276        assert_eq!(c.miss_count, 5);
277        assert_eq!(c.hit_count, 95);
278    }
279
280    #[test]
281    fn lru_eviction_at_max_entries() {
282        let mut c = MemoizeCache::new().with_max_entries(3);
283        for i in 0..5 {
284            let k = key("q", &[Value::Int(i)]);
285            c.insert(k, Value::BigInt(i64::from(i)));
286        }
287        assert!(c.len() <= 3, "len={}", c.len());
288        // Last 3 inserted (i=2, 3, 4) should be the survivors.
289        assert!(c.get(&key("q", &[Value::Int(4)])).is_some());
290        assert!(c.get(&key("q", &[Value::Int(3)])).is_some());
291        assert!(c.get(&key("q", &[Value::Int(2)])).is_some());
292        // Older entries evicted.
293        assert!(c.get(&key("q", &[Value::Int(0)])).is_none());
294    }
295
296    #[test]
297    fn lru_eviction_at_max_bytes() {
298        let mut c = MemoizeCache::new().with_max_bytes(128);
299        // Big strings exceed 128 bytes fast.
300        for i in 0..10 {
301            let big_str = alloc::string::String::from_iter(core::iter::repeat_n('x', 64));
302            c.insert(key("q", &[Value::Int(i)]), Value::Text(big_str));
303        }
304        assert!(c.len() < 10, "len={}", c.len());
305    }
306
307    #[test]
308    fn distinct_subquery_reprs_dont_collide() {
309        let mut c = MemoizeCache::new();
310        let k1 = key("SELECT 1", &[Value::Int(1)]);
311        let k2 = key("SELECT 2", &[Value::Int(1)]);
312        c.insert(k1.clone(), Value::BigInt(10));
313        c.insert(k2.clone(), Value::BigInt(20));
314        assert_eq!(c.get(&k1), Some(Value::BigInt(10)));
315        assert_eq!(c.get(&k2), Some(Value::BigInt(20)));
316    }
317
318    #[test]
319    fn miss_then_hit_bumps_promotes_to_lru_front() {
320        let mut c = MemoizeCache::new().with_max_entries(3);
321        c.insert(key("q", &[Value::Int(0)]), Value::BigInt(0));
322        c.insert(key("q", &[Value::Int(1)]), Value::BigInt(1));
323        c.insert(key("q", &[Value::Int(2)]), Value::BigInt(2));
324        // Touch 0 — promote to front.
325        let _ = c.get(&key("q", &[Value::Int(0)]));
326        // Insert a new entry — evicts the LRU (which is now 1, not 0).
327        c.insert(key("q", &[Value::Int(3)]), Value::BigInt(3));
328        assert!(c.get(&key("q", &[Value::Int(0)])).is_some());
329        assert!(c.get(&key("q", &[Value::Int(1)])).is_none());
330    }
331}