vlorql_core/cache/
prompt_cache.rs1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
21pub struct PromptCacheKey {
22 pub schema_version: String,
24 pub dialect: SqlDialect,
26 pub policy_hash: u64,
28 pub table_hash: u64,
30}
31
32impl PromptCacheKey {
33 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
55pub(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#[derive(Debug, Clone)]
76pub struct PromptCache {
77 inner: MokaCache<PromptCacheKey, String>,
78}
79
80impl PromptCache {
81 #[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 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 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 pub async fn invalidate(&self, key: &PromptCacheKey) {
124 self.inner.invalidate(key).await;
125 }
126
127 pub fn clear(&self) {
129 self.inner.invalidate_all();
130 }
131
132 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}