Skip to main content

vlorql_core/cache/
prompt_cache.rs

1//! Cache for system prompts generated by [`PromptBuilder`].
2//!
3//! The prompt depends on the schema, dialect profile, and policy
4//! configuration — all of which change infrequently.  Caching the
5//! generated prompt string avoids re-building it on every query.
6
7use crate::policy::PolicyConfig;
8use crate::schema::{DialectProfile, SqlDialect};
9use moka::future::Cache as MokaCache;
10use std::hash::Hash;
11use std::hash::Hasher;
12use xxhash_rust::xxh3::Xxh3;
13
14/// Key used to identify a cached system prompt.
15///
16/// The key captures the schema version, the SQL dialect, a hash of
17/// the policy configuration, and a hash of the relevant table set.
18/// Two `PromptBuilder` instances with the same key produce the same
19/// prompt string.
20#[derive(Debug, Clone, PartialEq, Eq, Hash)]
21pub struct PromptCacheKey {
22    /// Schema version string (e.g. `"v1.2.3"`).
23    pub schema_version: String,
24    /// Target SQL dialect.
25    pub dialect: SqlDialect,
26    /// 64-bit hash of the policy configuration.
27    pub policy_hash: u64,
28    /// 64-bit hash of the relevant table names selected for this question.
29    pub table_hash: u64,
30}
31
32impl PromptCacheKey {
33    /// Creates a new key from the builder's parameters.
34    ///
35    /// `policy_hash` should be computed with `hash_policy` so that any
36    /// change to the policy (table allowlists, denied columns, row filters)
37    /// produces a different key.  `table_hash` captures which tables are
38    /// relevant to the user question, so different questions that match
39    /// different table sets produce different cache entries.
40    pub fn new(
41        schema_version: &str,
42        dialect: &DialectProfile,
43        policy_hash: u64,
44        table_hash: u64,
45    ) -> Self {
46        Self {
47            schema_version: schema_version.to_owned(),
48            dialect: dialect.dialect,
49            policy_hash,
50            table_hash,
51        }
52    }
53}
54
55/// Computes a 64-bit hash of a [`PolicyConfig`] by serialising it to
56/// JSON and hashing the bytes with xxh3.
57pub(crate) fn hash_policy(policy: &PolicyConfig) -> u64 {
58    let json = serde_json::to_value(policy).expect("PolicyConfig should serialize to JSON");
59    let canonical = serde_json::to_string(&json).expect("JSON should serialize to string");
60    let mut hasher = Xxh3::new();
61    canonical.hash(&mut hasher);
62    hasher.finish()
63}
64
65/// A cache for system prompt strings keyed by [`PromptCacheKey`].
66///
67/// # Examples
68///
69/// ```
70/// use vlorql_core::cache::PromptCache;
71///
72/// let cache = PromptCache::new(100, 300);
73/// assert_eq!(cache.size(), 0);
74/// ```
75#[derive(Debug, Clone)]
76pub struct PromptCache {
77    inner: MokaCache<PromptCacheKey, String>,
78}
79
80impl PromptCache {
81    /// Creates a new prompt cache.
82    ///
83    /// * `capacity` — maximum number of entries before the cache evicts
84    ///   least-recently-used items.
85    /// * `ttl_seconds` — time-to-live in seconds.  Entries older than
86    ///   this are automatically invalidated.
87    #[must_use]
88    pub fn new(capacity: u64, ttl_seconds: u64) -> Self {
89        let mut builder = MokaCache::builder().max_capacity(capacity);
90        if ttl_seconds > 0 {
91            builder = builder.time_to_live(std::time::Duration::from_secs(ttl_seconds));
92        }
93        let inner = builder.build();
94        Self { inner }
95    }
96
97    /// Returns the cached prompt for `key`, or `None` on a miss.
98    pub async fn get(&self, key: &PromptCacheKey) -> Option<String> {
99        let result = self.inner.get(key).await;
100        let hit = result.is_some();
101        tracing::debug!(
102            target: "vlorql::cache",
103            "Prompt cache {} for version={}, dialect={:?}",
104            if hit { "HIT" } else { "MISS" },
105            key.schema_version,
106            key.dialect,
107        );
108        result
109    }
110
111    /// Inserts a prompt string into the cache.
112    pub async fn insert(&self, key: PromptCacheKey, prompt: String) {
113        tracing::debug!(
114            target: "vlorql::cache",
115            "Prompt cache INSERT for version={}, dialect={:?}",
116            key.schema_version,
117            key.dialect,
118        );
119        self.inner.insert(key, prompt).await;
120    }
121
122    /// Removes the entry for `key` from the cache.
123    pub async fn invalidate(&self, key: &PromptCacheKey) {
124        self.inner.invalidate(key).await;
125    }
126
127    /// Removes all entries from the cache.
128    pub fn clear(&self) {
129        self.inner.invalidate_all();
130    }
131
132    /// Returns the number of entries currently in the cache.
133    #[must_use]
134    pub fn size(&self) -> u64 {
135        self.inner.entry_count()
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::policy::{PolicyConfig, TablePolicy};
143    use crate::schema::DialectProfile;
144    use std::collections::HashMap;
145
146    fn key_v1() -> PromptCacheKey {
147        PromptCacheKey::new(
148            "v1",
149            &DialectProfile::default(),
150            hash_policy(&PolicyConfig::default()),
151            0,
152        )
153    }
154
155    fn key_v2() -> PromptCacheKey {
156        PromptCacheKey::new(
157            "v2",
158            &DialectProfile::default(),
159            hash_policy(&PolicyConfig::default()),
160            0,
161        )
162    }
163
164    /// Same configuration → same key.
165    #[test]
166    fn same_config_same_key() {
167        let a = key_v1();
168        let b = PromptCacheKey::new(
169            "v1",
170            &DialectProfile::default(),
171            hash_policy(&PolicyConfig::default()),
172            0,
173        );
174        assert_eq!(a, b);
175    }
176
177    /// Different schema version → different key.
178    #[test]
179    fn different_version_different_key() {
180        let a = key_v1();
181        let b = key_v2();
182        assert_ne!(a, b);
183    }
184
185    /// Different dialect → different key.
186    #[test]
187    fn different_dialect_different_key() {
188        let pg = PromptCacheKey::new(
189            "v1",
190            &DialectProfile::default(),
191            hash_policy(&PolicyConfig::default()),
192            0,
193        );
194        let sqlite = PromptCacheKey::new(
195            "v1",
196            &DialectProfile {
197                dialect: SqlDialect::Sqlite,
198                ..DialectProfile::default()
199            },
200            hash_policy(&PolicyConfig::default()),
201            0,
202        );
203        assert_ne!(pg, sqlite);
204    }
205
206    /// Different policy → different key.
207    #[test]
208    fn different_policy_different_key() {
209        let strict = PolicyConfig {
210            table_policies: HashMap::from([(
211                "secrets".to_owned(),
212                TablePolicy {
213                    allowed: false,
214                    ..TablePolicy::default()
215                },
216            )]),
217            ..PolicyConfig::default()
218        };
219
220        let default_key = PromptCacheKey::new(
221            "v1",
222            &DialectProfile::default(),
223            hash_policy(&PolicyConfig::default()),
224            0,
225        );
226        let strict_key =
227            PromptCacheKey::new("v1", &DialectProfile::default(), hash_policy(&strict), 0);
228        assert_ne!(default_key, strict_key);
229    }
230
231    /// Cache hit returns the cached prompt.
232    #[tokio::test]
233    async fn cache_hit_returns_cached_prompt() {
234        let cache = PromptCache::new(10, 60);
235        let key = key_v1();
236
237        assert!(cache.get(&key).await.is_none());
238        cache
239            .insert(key.clone(), "SELECT * FROM users".to_owned())
240            .await;
241        let cached = cache.get(&key).await;
242        assert_eq!(cached, Some("SELECT * FROM users".to_owned()));
243    }
244
245    /// Different keys do not share entries.
246    #[tokio::test]
247    async fn different_keys_do_not_share() {
248        let cache = PromptCache::new(10, 60);
249        let k1 = key_v1();
250        let k2 = key_v2();
251
252        cache.insert(k1.clone(), "prompt_v1".to_owned()).await;
253        cache.insert(k2.clone(), "prompt_v2".to_owned()).await;
254
255        assert_eq!(cache.get(&k1).await, Some("prompt_v1".to_owned()));
256        assert_eq!(cache.get(&k2).await, Some("prompt_v2".to_owned()));
257    }
258
259    /// Clear removes all entries.
260    #[tokio::test]
261    async fn clear_removes_all_entries() {
262        let cache = PromptCache::new(10, 60);
263        let key = key_v1();
264
265        cache.insert(key.clone(), "data".to_owned()).await;
266        assert!(cache.get(&key).await.is_some());
267        cache.clear();
268        assert!(cache.get(&key).await.is_none());
269    }
270}