linkrs-query 0.1.0

Query engine, parser, and executor for Linkrs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use moka::sync::Cache;
use std::sync::Arc;
use std::time::Duration;

use crate::cache::config::CteCacheConfig;
use crate::cache::stats::{CteCacheStats, CteCacheStatsSnapshot};
use linkrs_metrics::StatsManager;

use super::entry::CteCacheEntry;

/// CTE Cache Manager
///
/// Managing caching of CTE (Common Table Expression) query results and ensuring thread-safe access.
#[derive(Debug)]
pub struct CteCacheManager {
    /// Cache storage - using moka for high-performance concurrent access with weigher
    cache: Cache<String, Arc<CteCacheEntry>>,
    /// Configuration
    config: Arc<std::sync::RwLock<CteCacheConfig>>,
    /// Statistics
    stats: Arc<CteCacheStats>,
    /// Stats manager for reporting cache metrics
    stats_manager: std::sync::RwLock<Option<Arc<StatsManager>>>,
}

impl CteCacheManager {
    /// Create a new cache manager.
    pub fn new() -> Self {
        Self::with_config(CteCacheConfig::default())
    }

    /// Create using the configuration.
    pub fn with_config(config: CteCacheConfig) -> Self {
        let max_weight = config.max_size as u64;

        let cache = Cache::builder()
            .weigher(|_key, value: &Arc<CteCacheEntry>| -> u32 {
                let arc_overhead = std::mem::size_of::<Arc<CteCacheEntry>>();
                (value.estimate_memory() + arc_overhead) as u32
            })
            .max_capacity(max_weight)
            .time_to_live(Duration::from_secs(config.entry_ttl_seconds))
            .build();

        let stats = Arc::new(CteCacheStats::new(config.max_size));

        Self {
            cache,
            config: Arc::new(std::sync::RwLock::new(config.clone())),
            stats,
            stats_manager: std::sync::RwLock::new(None),
        }
    }

    pub fn with_stats_manager(mut self, stats_manager: Arc<StatsManager>) -> Self {
        self.stats_manager = std::sync::RwLock::new(Some(stats_manager));
        self
    }

    /// Set the stats manager after creation
    pub fn set_stats_manager(&self, stats_manager: Arc<StatsManager>) {
        if let Ok(mut guard) = self.stats_manager.write() {
            *guard = Some(stats_manager);
        }
    }

    /// Obtain the configuration.
    pub fn config(&self) -> CteCacheConfig {
        self.config.read().expect("Config lock poisoned").clone()
    }

    /// Update the configuration.
    pub fn set_config(&self, config: CteCacheConfig) {
        let mut cfg = self.config.write().expect("Config lock poisoned");
        self.stats.memory.set_max_bytes(config.max_size);
        *cfg = config;
    }

    /// Determine whether to enable caching.
    pub fn is_enabled(&self) -> bool {
        self.config.read().expect("Config lock poisoned").enabled
    }

    /// Determine whether the results of the CTE (Common Table Expression) are cached.
    ///
    /// # Parameters
    /// `cte_definition`: Text defining the Common Table Expression (CTE).
    /// estimated_rows: The estimated number of rows
    /// `is_deterministic`: Whether the CTE (Common Table Expression) is deterministic.
    pub fn should_cache(
        &self,
        cte_definition: &str,
        estimated_rows: u64,
        is_deterministic: bool,
    ) -> bool {
        let config = self.config.read().expect("Config lock poisoned");

        if !config.enabled {
            return false;
        }

        if !is_deterministic {
            return false;
        }

        if estimated_rows < config.min_row_count || estimated_rows > config.max_row_count {
            return false;
        }

        let reuse_prob = self.predict_reuse_probability(cte_definition);
        if reuse_prob < 0.3 {
            return false;
        }

        true
    }

    /// Predict the probability of reuse
    pub(super) fn predict_reuse_probability(&self, cte_definition: &str) -> f64 {
        let cte_hash = Self::compute_hash(cte_definition);

        if let Some(entry) = self.cache.get(&cte_hash) {
            return entry.reuse_probability;
        }

        let complexity = cte_definition.len() as f64 / 100.0;
        let base_prob = 0.5;
        let complexity_bonus = (complexity / 10.0).min(0.3);

        base_prob + complexity_bonus
    }

    /// Calculate the hash value defined by the CTE (Common Table Expression).
    pub(super) fn compute_hash(cte_definition: &str) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        cte_definition.hash(&mut hasher);
        format!("{:016x}", hasher.finish())
    }

    /// Store the data in the cache.
    pub fn put(&self, cte_definition: &str, data: Vec<u8>, row_count: u64) -> Option<String> {
        self.put_with_cost(cte_definition, data, row_count, 100)
    }

    /// Store the data in the cache with compute cost.
    pub fn put_with_cost(
        &self,
        cte_definition: &str,
        data: Vec<u8>,
        row_count: u64,
        compute_cost_ms: u64,
    ) -> Option<String> {
        let config = self.config.read().expect("Config lock poisoned");

        if !config.enabled {
            return None;
        }

        if data.len() > config.max_entry_size {
            self.stats.counters.record_rejection();
            return None;
        }

        drop(config);

        let cte_hash = Self::compute_hash(cte_definition);
        let entry = Arc::new(CteCacheEntry::new(
            cte_hash.clone(),
            cte_definition.to_string(),
            data,
            row_count,
            compute_cost_ms,
        ));

        self.cache.insert(cte_hash.clone(), entry);

        self.stats.counters.record_insertion();
        self.update_stats();

        Some(cte_hash)
    }

    /// Store the data in the cache with dependent tables.
    pub fn put_with_tables(
        &self,
        cte_definition: &str,
        data: Vec<u8>,
        row_count: u64,
        compute_cost_ms: u64,
        dependent_tables: Vec<String>,
    ) -> Option<String> {
        let config = self.config.read().expect("Config lock poisoned");

        if !config.enabled {
            return None;
        }

        if data.len() > config.max_entry_size {
            self.stats.counters.record_rejection();
            return None;
        }

        drop(config);

        let cte_hash = Self::compute_hash(cte_definition);
        let mut entry = CteCacheEntry::new(
            cte_hash.clone(),
            cte_definition.to_string(),
            data,
            row_count,
            compute_cost_ms,
        );
        entry.dependent_tables = dependent_tables;

        self.cache.insert(cte_hash.clone(), Arc::new(entry));

        self.stats.counters.record_insertion();
        self.update_stats();

        Some(cte_hash)
    }

    /// Evict low priority entries
    pub fn evict_low_priority(&self, target_bytes: usize) -> usize {
        let mut freed = 0;
        let mut to_remove = Vec::new();

        let entries: Vec<_> = self
            .cache
            .iter()
            .map(|entry| {
                let value_score = entry.1.value_score();
                (
                    entry.0.as_ref().clone(),
                    value_score,
                    entry.1.data_size,
                    entry.1.priority,
                )
            })
            .collect();

        let mut entries_sorted = entries;
        entries_sorted.sort_by(|a, b| {
            a.1.partial_cmp(&b.1)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.3.cmp(&b.3))
        });

        for (key, _, size, _) in entries_sorted {
            if freed >= target_bytes {
                break;
            }
            to_remove.push(key);
            freed += size;
        }

        for key in &to_remove {
            self.cache.invalidate(key);
        }

        if freed > 0 {
            self.stats.counters.record_eviction();
            self.update_stats();
        }

        freed
    }

    /// Retrieve data from the cache.
    pub fn get(&self, cte_definition: &str) -> Option<Arc<Vec<u8>>> {
        let config = self.config.read().expect("Config lock poisoned");

        if !config.enabled {
            return None;
        }

        drop(config);

        let cte_hash = Self::compute_hash(cte_definition);

        if let Some(entry) = self.cache.get(&cte_hash) {
            self.stats.counters.record_hit();
            if let Ok(ref sm_guard) = self.stats_manager.read() {
                if let Some(ref sm) = **sm_guard {
                    sm.record_cache_hit_global(true);
                }
            }
            Some(entry.data.clone())
        } else {
            self.stats.counters.record_miss();
            if let Ok(ref sm_guard) = self.stats_manager.read() {
                if let Some(ref sm) = **sm_guard {
                    sm.record_cache_hit_global(false);
                }
            }
            None
        }
    }

    /// Check whether it exists in the cache.
    pub fn contains(&self, cte_definition: &str) -> bool {
        let cte_hash = Self::compute_hash(cte_definition);
        self.cache.contains_key(&cte_hash)
    }

    /// Invalidate the cache entry
    pub fn invalidate(&self, cte_definition: &str) -> bool {
        let cte_hash = Self::compute_hash(cte_definition);
        self.invalidate_by_hash(&cte_hash)
    }

    /// Invalidate cache entry by hash
    pub fn invalidate_by_hash(&self, cte_hash: &str) -> bool {
        let removed = self.cache.remove(cte_hash).is_some();

        if removed {
            self.stats.counters.record_eviction();
            self.update_stats();
        }

        removed
    }

    /// Invalidate cache entries by table name
    pub fn invalidate_by_table(&self, table_name: &str) -> usize {
        let mut count = 0;
        let keys_to_remove: Vec<String> = self
            .cache
            .iter()
            .filter(|entry| entry.1.dependent_tables.iter().any(|t| t == table_name))
            .map(|entry| entry.0.as_ref().clone())
            .collect();

        for key in keys_to_remove {
            if self.cache.remove(&key).is_some() {
                count += 1;
            }
        }

        if count > 0 {
            self.stats.counters.record_eviction();
            self.update_stats();
        }

        count
    }

    /// Get cache entries for eviction (internal use)
    pub fn get_cache_entries(&self) -> Vec<(String, f64, usize)> {
        self.cache
            .iter()
            .map(|entry| {
                let value_score = entry.1.value_score();
                (entry.0.as_ref().clone(), value_score, entry.1.data_size)
            })
            .collect()
    }

    /// Increment eviction count (internal use)
    pub fn increment_evicted_count(&self, count: u64) {
        for _ in 0..count {
            self.stats.counters.record_eviction();
        }
    }

    /// Clear all caches.
    pub fn clear(&self) {
        self.cache.invalidate_all();
        self.stats.reset();
    }

    /// Obtain statistical information
    pub fn get_stats(&self) -> CteCacheStatsSnapshot {
        self.update_stats();
        self.stats.snapshot()
    }

    /// Update internal statistics
    fn update_stats(&self) {
        let current_entries = self.cache.entry_count() as usize;
        let current_memory = self.estimate_current_memory();
        self.stats.memory.update(current_memory, current_entries);
    }

    /// Estimate current memory usage
    fn estimate_current_memory(&self) -> usize {
        self.cache
            .iter()
            .map(|entry| entry.1.estimate_memory())
            .sum()
    }

    /// Reset statistics
    pub fn reset_stats(&self) {
        self.stats.reset();
    }

    /// Get the current memory usage
    pub fn current_memory(&self) -> usize {
        self.estimate_current_memory()
    }

    /// Obtain the number of cached entries
    pub fn entry_count(&self) -> usize {
        self.cache.entry_count() as usize
    }

    /// Clearance of obsolete entries
    /// Note: moka handles TTL automatically, so this is a no-op
    pub fn cleanup_expired(&self) -> usize {
        0
    }

    /// Get the statistics object
    pub fn stats(&self) -> Arc<CteCacheStats> {
        self.stats.clone()
    }
}

impl Default for CteCacheManager {
    fn default() -> Self {
        Self::new()
    }
}