vlorql-core 0.2.0

A high-performance SQL query optimizer with constant folding, predicate pushdown, column pruning, and cost-based join reordering
Documentation
//! Cache for system prompts generated by [`PromptBuilder`].
//!
//! The prompt depends on the schema, dialect profile, and policy
//! configuration — all of which change infrequently.  Caching the
//! generated prompt string avoids re-building it on every query.

use crate::policy::PolicyConfig;
use crate::schema::{DialectProfile, SqlDialect};
use moka::future::Cache as MokaCache;
use std::hash::Hash;
use std::hash::Hasher;
use xxhash_rust::xxh3::Xxh3;

/// Key used to identify a cached system prompt.
///
/// The key captures the schema version, the SQL dialect, a hash of
/// the policy configuration, and a hash of the relevant table set.
/// Two `PromptBuilder` instances with the same key produce the same
/// prompt string.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PromptCacheKey {
    /// Schema version string (e.g. `"v1.2.3"`).
    pub schema_version: String,
    /// Target SQL dialect.
    pub dialect: SqlDialect,
    /// 64-bit hash of the policy configuration.
    pub policy_hash: u64,
    /// 64-bit hash of the relevant table names selected for this question.
    pub table_hash: u64,
}

impl PromptCacheKey {
    /// Creates a new key from the builder's parameters.
    ///
    /// `policy_hash` should be computed with `hash_policy` so that any
    /// change to the policy (table allowlists, denied columns, row filters)
    /// produces a different key.  `table_hash` captures which tables are
    /// relevant to the user question, so different questions that match
    /// different table sets produce different cache entries.
    pub fn new(
        schema_version: &str,
        dialect: &DialectProfile,
        policy_hash: u64,
        table_hash: u64,
    ) -> Self {
        Self {
            schema_version: schema_version.to_owned(),
            dialect: dialect.dialect,
            policy_hash,
            table_hash,
        }
    }
}

/// Computes a 64-bit hash of a [`PolicyConfig`] by serialising it to
/// JSON and hashing the bytes with xxh3.
pub(crate) fn hash_policy(policy: &PolicyConfig) -> u64 {
    let json = serde_json::to_value(policy).expect("PolicyConfig should serialize to JSON");
    let canonical = serde_json::to_string(&json).expect("JSON should serialize to string");
    let mut hasher = Xxh3::new();
    canonical.hash(&mut hasher);
    hasher.finish()
}

/// A cache for system prompt strings keyed by [`PromptCacheKey`].
///
/// # Examples
///
/// ```
/// use vlorql_core::cache::PromptCache;
///
/// let cache = PromptCache::new(100, 300);
/// assert_eq!(cache.size(), 0);
/// ```
#[derive(Debug, Clone)]
pub struct PromptCache {
    inner: MokaCache<PromptCacheKey, String>,
}

impl PromptCache {
    /// Creates a new prompt cache.
    ///
    /// * `capacity` — maximum number of entries before the cache evicts
    ///   least-recently-used items.
    /// * `ttl_seconds` — time-to-live in seconds.  Entries older than
    ///   this are automatically invalidated.
    #[must_use]
    pub fn new(capacity: u64, ttl_seconds: u64) -> Self {
        let mut builder = MokaCache::builder().max_capacity(capacity);
        if ttl_seconds > 0 {
            builder = builder.time_to_live(std::time::Duration::from_secs(ttl_seconds));
        }
        let inner = builder.build();
        Self { inner }
    }

    /// Returns the cached prompt for `key`, or `None` on a miss.
    pub async fn get(&self, key: &PromptCacheKey) -> Option<String> {
        let result = self.inner.get(key).await;
        let hit = result.is_some();
        tracing::debug!(
            target: "vlorql::cache",
            "Prompt cache {} for version={}, dialect={:?}",
            if hit { "HIT" } else { "MISS" },
            key.schema_version,
            key.dialect,
        );
        result
    }

    /// Inserts a prompt string into the cache.
    pub async fn insert(&self, key: PromptCacheKey, prompt: String) {
        tracing::debug!(
            target: "vlorql::cache",
            "Prompt cache INSERT for version={}, dialect={:?}",
            key.schema_version,
            key.dialect,
        );
        self.inner.insert(key, prompt).await;
    }

    /// Removes the entry for `key` from the cache.
    pub async fn invalidate(&self, key: &PromptCacheKey) {
        self.inner.invalidate(key).await;
    }

    /// Removes all entries from the cache.
    pub fn clear(&self) {
        self.inner.invalidate_all();
    }

    /// Returns the number of entries currently in the cache.
    #[must_use]
    pub fn size(&self) -> u64 {
        self.inner.entry_count()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::{PolicyConfig, TablePolicy};
    use crate::schema::DialectProfile;
    use std::collections::HashMap;

    fn key_v1() -> PromptCacheKey {
        PromptCacheKey::new(
            "v1",
            &DialectProfile::default(),
            hash_policy(&PolicyConfig::default()),
            0,
        )
    }

    fn key_v2() -> PromptCacheKey {
        PromptCacheKey::new(
            "v2",
            &DialectProfile::default(),
            hash_policy(&PolicyConfig::default()),
            0,
        )
    }

    /// Same configuration → same key.
    #[test]
    fn same_config_same_key() {
        let a = key_v1();
        let b = PromptCacheKey::new(
            "v1",
            &DialectProfile::default(),
            hash_policy(&PolicyConfig::default()),
            0,
        );
        assert_eq!(a, b);
    }

    /// Different schema version → different key.
    #[test]
    fn different_version_different_key() {
        let a = key_v1();
        let b = key_v2();
        assert_ne!(a, b);
    }

    /// Different dialect → different key.
    #[test]
    fn different_dialect_different_key() {
        let pg = PromptCacheKey::new(
            "v1",
            &DialectProfile::default(),
            hash_policy(&PolicyConfig::default()),
            0,
        );
        let sqlite = PromptCacheKey::new(
            "v1",
            &DialectProfile {
                dialect: SqlDialect::Sqlite,
                ..DialectProfile::default()
            },
            hash_policy(&PolicyConfig::default()),
            0,
        );
        assert_ne!(pg, sqlite);
    }

    /// Different policy → different key.
    #[test]
    fn different_policy_different_key() {
        let strict = PolicyConfig {
            table_policies: HashMap::from([(
                "secrets".to_owned(),
                TablePolicy {
                    allowed: false,
                    ..TablePolicy::default()
                },
            )]),
            ..PolicyConfig::default()
        };

        let default_key = PromptCacheKey::new(
            "v1",
            &DialectProfile::default(),
            hash_policy(&PolicyConfig::default()),
            0,
        );
        let strict_key =
            PromptCacheKey::new("v1", &DialectProfile::default(), hash_policy(&strict), 0);
        assert_ne!(default_key, strict_key);
    }

    /// Cache hit returns the cached prompt.
    #[tokio::test]
    async fn cache_hit_returns_cached_prompt() {
        let cache = PromptCache::new(10, 60);
        let key = key_v1();

        assert!(cache.get(&key).await.is_none());
        cache
            .insert(key.clone(), "SELECT * FROM users".to_owned())
            .await;
        let cached = cache.get(&key).await;
        assert_eq!(cached, Some("SELECT * FROM users".to_owned()));
    }

    /// Different keys do not share entries.
    #[tokio::test]
    async fn different_keys_do_not_share() {
        let cache = PromptCache::new(10, 60);
        let k1 = key_v1();
        let k2 = key_v2();

        cache.insert(k1.clone(), "prompt_v1".to_owned()).await;
        cache.insert(k2.clone(), "prompt_v2".to_owned()).await;

        assert_eq!(cache.get(&k1).await, Some("prompt_v1".to_owned()));
        assert_eq!(cache.get(&k2).await, Some("prompt_v2".to_owned()));
    }

    /// Clear removes all entries.
    #[tokio::test]
    async fn clear_removes_all_entries() {
        let cache = PromptCache::new(10, 60);
        let key = key_v1();

        cache.insert(key.clone(), "data".to_owned()).await;
        assert!(cache.get(&key).await.is_some());
        cache.clear();
        assert!(cache.get(&key).await.is_none());
    }
}