use std::time::Duration;
use aither_core::llm::Message;
use aither_core::llm::model::Parameters;
use aither_core::llm::model::{
CacheOptions, ClaudeCacheBreakpointTarget, ClaudeExplicitCacheBreakpoint,
ClaudeExplicitCacheBreakpoints, ClaudePromptCache, ClaudePromptCacheTtl,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheLifetime {
Limited(Duration),
Permanent,
}
impl CacheLifetime {
#[must_use]
pub fn is_cold(&self, idle: Duration) -> bool {
match self {
Self::Limited(lifetime) => idle >= *lifetime,
Self::Permanent => false,
}
}
}
#[derive(Debug, Clone)]
pub struct PromptCache {
session_key: String,
epoch: u32,
fingerprint: Option<u64>,
ttl: ClaudePromptCacheTtl,
lifetime: CacheLifetime,
}
impl PromptCache {
#[must_use]
pub fn new(session_key: impl Into<String>) -> Self {
Self {
session_key: session_key.into(),
epoch: 0,
fingerprint: None,
ttl: ClaudePromptCacheTtl::OneHour,
lifetime: CacheLifetime::Limited(Duration::from_secs(3600)),
}
}
#[must_use]
pub const fn with_ttl(mut self, ttl: ClaudePromptCacheTtl) -> Self {
self.ttl = ttl;
self.lifetime = CacheLifetime::Limited(match ttl {
ClaudePromptCacheTtl::FiveMinutes => Duration::from_secs(300),
ClaudePromptCacheTtl::OneHour => Duration::from_secs(3600),
});
self
}
#[must_use]
pub const fn with_lifetime(mut self, lifetime: CacheLifetime) -> Self {
self.lifetime = lifetime;
self
}
#[must_use]
pub const fn lifetime(&self) -> CacheLifetime {
self.lifetime
}
#[must_use]
pub fn key(&self) -> String {
format!("{}:{}", self.session_key, self.epoch)
}
#[must_use]
pub const fn epoch(&self) -> u32 {
self.epoch
}
pub fn observe_prefix(&mut self, fingerprint: u64) -> bool {
match self.fingerprint {
Some(previous) if previous == fingerprint => false,
Some(_) => {
self.epoch += 1;
self.fingerprint = Some(fingerprint);
tracing::debug!(epoch = self.epoch, "prompt cache prefix rewritten");
true
}
None => {
self.fingerprint = Some(fingerprint);
false
}
}
}
#[must_use]
pub fn apply(
&self,
mut parameters: Parameters,
messages: &[Message],
has_tools: bool,
) -> Parameters {
parameters.cache = CacheOptions {
openai: Some(aither_core::llm::model::OpenAIPromptCache {
key: Some(self.key()),
retention: Some(aither_core::llm::model::OpenAIPromptCacheRetention::Hours24),
}),
claude: Some(ClaudePromptCache::explicit(
self.ttl,
Self::breakpoints(messages, has_tools),
)),
gemini: None,
};
parameters
}
const fn breakpoints(messages: &[Message], has_tools: bool) -> ClaudeExplicitCacheBreakpoints {
let breakpoints = if has_tools {
ClaudeExplicitCacheBreakpoints::new(ClaudeExplicitCacheBreakpoint::new(
ClaudeCacheBreakpointTarget::LastTool,
))
.with_second(ClaudeExplicitCacheBreakpoint::new(
ClaudeCacheBreakpointTarget::LastSystem,
))
} else {
ClaudeExplicitCacheBreakpoints::new(ClaudeExplicitCacheBreakpoint::new(
ClaudeCacheBreakpointTarget::LastSystem,
))
};
let Some(index) = stable_conversation_end(messages) else {
return breakpoints;
};
let breakpoint = ClaudeExplicitCacheBreakpoint::new(ClaudeCacheBreakpointTarget::Message {
message_index: index,
block_index: 0,
});
if has_tools {
breakpoints.with_third(breakpoint)
} else {
breakpoints.with_second(breakpoint)
}
}
}
const fn stable_conversation_end(messages: &[Message]) -> Option<usize> {
messages.len().checked_sub(2)
}
#[cfg(test)]
mod tests {
use super::*;
use aither_core::llm::model::ClaudePromptCacheStrategy;
fn claude_strategy(parameters: &Parameters) -> ClaudePromptCacheStrategy {
parameters
.cache
.claude
.expect("claude cache options are set")
.strategy
}
#[test]
fn the_key_is_stable_until_the_prefix_is_rewritten() {
let mut cache = PromptCache::new("session-1");
assert!(!cache.observe_prefix(7));
let first = cache.key();
assert!(!cache.observe_prefix(7));
assert_eq!(cache.key(), first);
assert!(cache.observe_prefix(9));
assert_ne!(cache.key(), first);
assert_eq!(cache.epoch(), 1);
}
#[test]
fn requests_carry_cache_options_for_every_provider_shape() {
let cache = PromptCache::new("session-1");
let messages = vec![
Message::system("prefix"),
Message::user("hello"),
Message::system("live tail"),
];
let parameters = cache.apply(Parameters::default(), &messages, true);
assert!(!parameters.cache.is_empty());
assert_eq!(
parameters
.cache
.openai
.as_ref()
.and_then(|openai| openai.key.as_deref()),
Some("session-1:0")
);
let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(¶meters) else {
panic!("expected explicit claude breakpoints");
};
assert_eq!(
breakpoints.first.target,
ClaudeCacheBreakpointTarget::LastTool
);
assert_eq!(
breakpoints.second.map(|point| point.target),
Some(ClaudeCacheBreakpointTarget::LastSystem)
);
}
#[test]
fn the_message_breakpoint_skips_the_live_tail() {
let cache = PromptCache::new("session-1");
let messages = vec![
Message::system("prefix"),
Message::user("hello"),
Message::assistant("hi"),
Message::system("live tail"),
];
let parameters = cache.apply(Parameters::default(), &messages, false);
let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(¶meters) else {
panic!("expected explicit claude breakpoints");
};
assert_eq!(
breakpoints.second.map(|point| point.target),
Some(ClaudeCacheBreakpointTarget::Message {
message_index: 2,
block_index: 0,
}),
"breakpoint must land on the last stable message, not the tail"
);
}
#[test]
fn the_idle_gap_follows_the_cache_lifetime() {
let lifetime = CacheLifetime::Limited(Duration::from_secs(3600));
assert!(!lifetime.is_cold(Duration::from_secs(300)));
assert!(!lifetime.is_cold(Duration::from_secs(3540)));
assert!(lifetime.is_cold(Duration::from_secs(3660)));
assert!(!CacheLifetime::Permanent.is_cold(Duration::from_secs(86_400)));
}
#[test]
fn with_ttl_keeps_the_lifetime_coherent() {
let cache = PromptCache::new("s").with_ttl(ClaudePromptCacheTtl::FiveMinutes);
assert_eq!(
cache.lifetime(),
CacheLifetime::Limited(Duration::from_secs(300))
);
}
#[test]
fn a_prefix_only_request_gets_no_message_breakpoint() {
let cache = PromptCache::new("session-1");
let messages = vec![Message::system("prefix")];
let parameters = cache.apply(Parameters::default(), &messages, false);
let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(¶meters) else {
panic!("expected explicit claude breakpoints");
};
assert!(breakpoints.second.is_none());
}
}