Skip to main content

LlmCache

Struct LlmCache 

Source
pub struct LlmCache { /* private fields */ }
Expand description

Content-hash-keyed file cache for LLM inference.

Cloning is cheap — the counters use shared atomics so a cloned handle reports the same totals as its parent, which is the invariant the CLI --stats subcommand relies on when multiple pipeline threads each hold a handle.

Implementations§

Source§

impl LlmCache

Source

pub const fn new(root: PathBuf) -> Self

Constructs a cache rooted at root with the DEFAULT_TTL.

The directory is created lazily on the first write; calling this on a path that does not yet exist is fine.

§Examples
use ssg::llm_cache::LlmCache;
let tmp = tempfile::tempdir().unwrap();
let cache = LlmCache::new(tmp.path().to_path_buf());
assert_eq!(cache.root(), tmp.path());
Source

pub const fn with_ttl(root: PathBuf, ttl: Duration) -> Self

Constructs a cache rooted at root with a custom TTL. Used by the AC4 expiry tests so they don’t have to wait 90 days.

§Examples
use std::time::Duration;
use ssg::llm_cache::LlmCache;
let tmp = tempfile::tempdir().unwrap();
let cache = LlmCache::with_ttl(tmp.path().to_path_buf(), Duration::from_secs(60));
assert_eq!(cache.stats().hits, 0);
Source

pub fn default_cache_dir() -> PathBuf

Resolves the platform-default cache root.

Selection order (first that yields a path wins):

  1. $SSG_LLM_CACHE_DIR — explicit override, used by tests and by ops who want to point at a shared cache on tmpfs.
  2. $XDG_CACHE_HOME/ssg/llm — Linux / XDG_CACHE_HOME set.
  3. $HOME/Library/Caches/ssg/llm — macOS default.
  4. %LOCALAPPDATA%\ssg\llm — Windows.
  5. $HOME/.cache/ssg/llm — generic Unix fallback.
  6. ./.ssg-llm-cache — last-resort relative path so the cache is still usable in sandboxes where neither $HOME nor %LOCALAPPDATA% is set.
§Examples
use ssg::llm_cache::LlmCache;
let dir = LlmCache::default_cache_dir();
assert!(!dir.as_os_str().is_empty());
Source

pub fn compute_key( endpoint: &str, model: &str, prompt: &str, timeout_secs: u64, ) -> [u8; 32]

Computes the 32-byte SHA-256 key for (endpoint, model, prompt, timeout_secs).

Every parameter that can change the model’s output is folded into the digest so a request that differs in even one byte gets a fresh inference (AC2). The hash is domain-separated with a versioned prefix so a future change to the key composition can be rolled out without colliding with stored entries.

§Examples
use ssg::llm_cache::LlmCache;
let a = LlmCache::compute_key("http://x", "llama", "hi", 30);
let b = LlmCache::compute_key("http://x", "llama", "hi", 30);
assert_eq!(a, b);
let c = LlmCache::compute_key("http://x", "llama", "bye", 30);
assert_ne!(a, c);
Source

pub fn get(&self, key: &[u8; 32]) -> Option<String>

Returns the cached payload for key, or None on miss / stale / corrupt.

A corrupted entry (truncated JSON, version mismatch, length mismatch) is evicted in-place and reported as a miss so the caller does a fresh inference (AC5). A TTL-expired entry is handled the same way (AC4).

§Examples
use ssg::llm_cache::LlmCache;
let tmp = tempfile::tempdir().unwrap();
let cache = LlmCache::new(tmp.path().to_path_buf());
let key = LlmCache::compute_key("e", "m", "p", 1);
assert!(cache.get(&key).is_none());
cache.set(&key, "answer").unwrap();
assert_eq!(cache.get(&key).as_deref(), Some("answer"));
Source

pub fn set(&self, key: &[u8; 32], payload: &str) -> Result<()>

Stores payload under key.

Returns Ok(()) on success. On any filesystem error the call silently falls through (counter is not bumped) so a transient disk failure never breaks the build — the next invocation will just be another miss + recompute.

§Errors

Returns the underlying io::Error when the cache file cannot be created or renamed into place.

§Examples
use ssg::llm_cache::LlmCache;
let tmp = tempfile::tempdir().unwrap();
let cache = LlmCache::new(tmp.path().to_path_buf());
let key = LlmCache::compute_key("e", "m", "p", 1);
cache.set(&key, "stored").unwrap();
assert_eq!(cache.stats().stores, 1);
Source

pub fn evict(&self, key: &[u8; 32]) -> Result<()>

Removes the entry for key if present. Used by the ssg cache --clear command and by the unit tests.

§Errors

Returns the underlying io::Error when the entry exists but cannot be removed. A missing entry is treated as success.

§Examples
use ssg::llm_cache::LlmCache;
let tmp = tempfile::tempdir().unwrap();
let cache = LlmCache::new(tmp.path().to_path_buf());
let key = LlmCache::compute_key("e", "m", "p", 1);
cache.set(&key, "x").unwrap();
cache.evict(&key).unwrap();
assert!(cache.get(&key).is_none());
Source

pub fn stats(&self) -> CacheStats

Returns the running session counters.

§Examples
use ssg::llm_cache::LlmCache;
let tmp = tempfile::tempdir().unwrap();
let cache = LlmCache::new(tmp.path().to_path_buf());
let stats = cache.stats();
assert_eq!(stats.hits, 0);
assert_eq!(stats.stores, 0);
Source

pub fn root(&self) -> &Path

Returns the cache root.

§Examples
use ssg::llm_cache::LlmCache;
let tmp = tempfile::tempdir().unwrap();
let cache = LlmCache::new(tmp.path().to_path_buf());
assert_eq!(cache.root(), tmp.path());

Trait Implementations§

Source§

impl Debug for LlmCache

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more