Skip to main content

aither_agent/context/
cache.rs

1//! Prompt cache control for the assembled window.
2//!
3//! Every provider's prompt cache keys on an unbroken prefix, but they differ
4//! in how that prefix is nominated. OpenAI-compatible endpoints want a stable
5//! routing key so successive requests from one session land on the same
6//! shard. Claude wants explicit breakpoints naming the blocks worth
7//! persisting. Both are derived from the same two facts the agent already
8//! knows: the window layout, and whether the cacheable part of it changed
9//! since the previous request.
10//!
11//! The second fact is why this type exists rather than a free function.
12//! Reassembly and compaction deliberately rewrite the stable prefix, which
13//! makes everything cached under the old key dead weight. [`PromptCache`]
14//! notices the change through a fingerprint and bumps an *epoch* that is
15//! folded into the cache key, so a rewritten window asks for a new shard
16//! instead of repeatedly missing on the old one.
17
18use std::time::Duration;
19
20use aither_core::llm::Message;
21use aither_core::llm::model::Parameters;
22use aither_core::llm::model::{
23    CacheOptions, ClaudeCacheBreakpointTarget, ClaudeExplicitCacheBreakpoint,
24    ClaudeExplicitCacheBreakpoints, ClaudePromptCache, ClaudePromptCacheTtl,
25};
26
27/// How long the conversation's prompt cache stays warm.
28///
29/// This is what an idle gap is measured against: reassembly rewrites the
30/// cacheable prefix, so it is only free once the provider's copy can no
31/// longer be read anyway.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum CacheLifetime {
34    /// The cache expires after this long without a hit.
35    Limited(Duration),
36    /// The cache never expires; rewriting the prefix is never free.
37    Permanent,
38}
39
40/// Derives per-request cache controls for one agent session.
41#[derive(Debug, Clone)]
42pub struct PromptCache {
43    /// Stable identity for this session's cache shard.
44    session_key: String,
45    /// Incremented whenever the cacheable prefix is rewritten.
46    epoch: u32,
47    /// Fingerprint of the stable prefix as of the last request.
48    fingerprint: Option<u64>,
49    /// How long Claude should retain the cached prefix.
50    ttl: ClaudePromptCacheTtl,
51    /// How long the conversation's cache stays warm, across providers.
52    lifetime: CacheLifetime,
53}
54
55impl PromptCache {
56    /// Creates a cache controller for a session identified by `session_key`.
57    ///
58    /// Agent runs are long and their prefixes are large, so the one-hour
59    /// retention is the default: a five-minute TTL expires during ordinary
60    /// think time and turns the next request into a full re-read.
61    #[must_use]
62    pub fn new(session_key: impl Into<String>) -> Self {
63        Self {
64            session_key: session_key.into(),
65            epoch: 0,
66            fingerprint: None,
67            ttl: ClaudePromptCacheTtl::OneHour,
68            lifetime: CacheLifetime::Limited(Duration::from_secs(3600)),
69        }
70    }
71
72    /// Overrides the Claude cache retention.
73    ///
74    /// The cache lifetime follows the retention, since Claude's advertised
75    /// TTL is exactly how long the provider promises to keep the prefix.
76    #[must_use]
77    pub const fn with_ttl(mut self, ttl: ClaudePromptCacheTtl) -> Self {
78        self.ttl = ttl;
79        self.lifetime = CacheLifetime::Limited(match ttl {
80            ClaudePromptCacheTtl::FiveMinutes => Duration::from_secs(300),
81            ClaudePromptCacheTtl::OneHour => Duration::from_secs(3600),
82        });
83        self
84    }
85
86    /// Overrides how long the conversation's cache is trusted to stay warm.
87    ///
88    /// A host whose provider retains prompts longer than the breakpoints ask
89    /// for (or forever) widens the idle-reassembly gap here; a lifetime of
90    /// [`CacheLifetime::Permanent`] means an idle gap never justifies a
91    /// reassembly.
92    #[must_use]
93    pub const fn with_lifetime(mut self, lifetime: CacheLifetime) -> Self {
94        self.lifetime = lifetime;
95        self
96    }
97
98    /// How long the conversation's cache stays warm.
99    #[must_use]
100    pub const fn lifetime(&self) -> CacheLifetime {
101        self.lifetime
102    }
103
104    /// Resumes a session's key at `epoch`, as read back from
105    /// [`PromptCache::epoch`] on the agent being replaced.
106    ///
107    /// A rebuilt agent keyed by the same session identity and epoch asks the
108    /// provider for the same cache shard its predecessor warmed, instead of
109    /// restarting at epoch zero.
110    #[must_use]
111    pub const fn with_epoch(mut self, epoch: u32) -> Self {
112        self.epoch = epoch;
113        self
114    }
115
116    /// The current cache key, which changes only when the prefix is rewritten.
117    #[must_use]
118    pub fn key(&self) -> String {
119        format!("{}:{}", self.session_key, self.epoch)
120    }
121
122    /// How many times the cacheable prefix has been rewritten.
123    #[must_use]
124    pub const fn epoch(&self) -> u32 {
125        self.epoch
126    }
127
128    /// Records the stable prefix fingerprint for the request about to be sent.
129    ///
130    /// Returns `true` when the prefix changed, which means the previous
131    /// epoch's cache is now unreachable.
132    pub fn observe_prefix(&mut self, fingerprint: u64) -> bool {
133        match self.fingerprint {
134            Some(previous) if previous == fingerprint => false,
135            Some(_) => {
136                self.epoch += 1;
137                self.fingerprint = Some(fingerprint);
138                tracing::debug!(epoch = self.epoch, "prompt cache prefix rewritten");
139                true
140            }
141            None => {
142                self.fingerprint = Some(fingerprint);
143                false
144            }
145        }
146    }
147
148    /// Applies cache controls to `parameters` for a request.
149    ///
150    /// `messages` is the assembled request, `has_tools` says whether tool
151    /// definitions are attached, and `mid_conversation_system` whether the
152    /// model keeps later system messages in the conversation; all three decide
153    /// where a Claude breakpoint can legally be placed.
154    #[must_use]
155    pub fn apply(
156        &self,
157        mut parameters: Parameters,
158        messages: &[Message],
159        has_tools: bool,
160        mid_conversation_system: bool,
161    ) -> Parameters {
162        parameters.cache = CacheOptions {
163            openai: Some(aither_core::llm::model::OpenAIPromptCache {
164                key: Some(self.key()),
165                retention: Some(aither_core::llm::model::OpenAIPromptCacheRetention::Hours24),
166            }),
167            claude: Some(ClaudePromptCache::explicit(
168                self.ttl,
169                Self::breakpoints(messages, has_tools, mid_conversation_system),
170            )),
171            gemini: None,
172        };
173        parameters
174    }
175
176    /// Chooses the Claude breakpoints for an assembled request.
177    ///
178    /// The subtlety is the last message: it is the live tail, rebuilt from
179    /// context sources on every single request, so caching *it* would write a
180    /// new entry each turn and read none of them back. The breakpoint goes on
181    /// the message before it — the newest byte that will still be there next
182    /// time.
183    fn breakpoints(
184        messages: &[Message],
185        has_tools: bool,
186        mid_conversation_system: bool,
187    ) -> ClaudeExplicitCacheBreakpoints {
188        // Tool definitions precede the system prompt in Claude's cacheable
189        // order, so a breakpoint there protects the whole tool surface.
190        let breakpoints = if has_tools {
191            ClaudeExplicitCacheBreakpoints::new(ClaudeExplicitCacheBreakpoint::new(
192                ClaudeCacheBreakpointTarget::LastTool,
193            ))
194            .with_second(ClaudeExplicitCacheBreakpoint::new(
195                ClaudeCacheBreakpointTarget::LastSystem,
196            ))
197        } else {
198            ClaudeExplicitCacheBreakpoints::new(ClaudeExplicitCacheBreakpoint::new(
199                ClaudeCacheBreakpointTarget::LastSystem,
200            ))
201        };
202        let Some(index) = stable_conversation_end(messages)
203            .and_then(|end| claude_message_index(messages, end, mid_conversation_system))
204        else {
205            return breakpoints;
206        };
207        let breakpoint = ClaudeExplicitCacheBreakpoint::new(ClaudeCacheBreakpointTarget::Message {
208            message_index: index,
209            block_index: 0,
210        });
211        if has_tools {
212            breakpoints.with_third(breakpoint)
213        } else {
214            breakpoints.with_second(breakpoint)
215        }
216    }
217}
218
219/// Index of the last conversation message that will still be present, byte
220/// for byte, in the next request.
221///
222/// Returns `None` when there is nothing but the prefix and the live tail.
223pub(crate) const fn stable_conversation_end(messages: &[Message]) -> Option<usize> {
224    // The final message is the live tail; the one before it is the newest
225    // append-only item.
226    messages.len().checked_sub(2)
227}
228
229/// Position, in the message list Claude is sent, of `messages[index]`.
230///
231/// Claude lifts the leading system messages into the top-level `system`. A
232/// model that takes mid-conversation system messages keeps every later one in
233/// place; any other folds all of them into `system`, so none counts. Returns
234/// `None` when the message itself is lifted out.
235fn claude_message_index(
236    messages: &[Message],
237    index: usize,
238    mid_conversation_system: bool,
239) -> Option<usize> {
240    let is_system = |message: &Message| message.role() == aither_core::llm::Role::System;
241    let lifted = if mid_conversation_system {
242        messages
243            .iter()
244            .take_while(|message| is_system(message))
245            .count()
246    } else {
247        if is_system(&messages[index]) {
248            return None;
249        }
250        messages[..index]
251            .iter()
252            .filter(|message| is_system(message))
253            .count()
254    };
255    index.checked_sub(lifted)
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use aither_core::llm::model::ClaudePromptCacheStrategy;
262
263    fn claude_strategy(parameters: &Parameters) -> ClaudePromptCacheStrategy {
264        parameters
265            .cache
266            .claude
267            .expect("claude cache options are set")
268            .strategy
269    }
270
271    #[test]
272    fn the_key_is_stable_until_the_prefix_is_rewritten() {
273        let mut cache = PromptCache::new("session-1");
274        assert!(!cache.observe_prefix(7));
275        let first = cache.key();
276        assert!(!cache.observe_prefix(7));
277        assert_eq!(cache.key(), first);
278
279        assert!(cache.observe_prefix(9));
280        assert_ne!(cache.key(), first);
281        assert_eq!(cache.epoch(), 1);
282    }
283
284    #[test]
285    fn a_rebuilt_agent_keeps_the_sessions_key_and_rotates_with_the_epoch() {
286        let mut first = PromptCache::new("session-1");
287        first.observe_prefix(1);
288        first.observe_prefix(2);
289        let rebuilt = PromptCache::new("session-1").with_epoch(first.epoch());
290        assert_eq!(rebuilt.key(), first.key());
291        assert_eq!(rebuilt.key(), "session-1:1");
292        assert_ne!(PromptCache::new("session-1").key(), rebuilt.key());
293    }
294
295    #[test]
296    fn requests_carry_cache_options_for_every_provider_shape() {
297        let cache = PromptCache::new("session-1");
298        let messages = vec![
299            Message::system("prefix"),
300            Message::user("hello"),
301            Message::system("live tail"),
302        ];
303        let parameters = cache.apply(Parameters::default(), &messages, true, true);
304
305        assert!(!parameters.cache.is_empty());
306        assert_eq!(
307            parameters
308                .cache
309                .openai
310                .as_ref()
311                .and_then(|openai| openai.key.as_deref()),
312            Some("session-1:0")
313        );
314        let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(&parameters) else {
315            panic!("expected explicit claude breakpoints");
316        };
317        assert_eq!(
318            breakpoints.first.target,
319            ClaudeCacheBreakpointTarget::LastTool
320        );
321        assert_eq!(
322            breakpoints.second.map(|point| point.target),
323            Some(ClaudeCacheBreakpointTarget::LastSystem)
324        );
325    }
326
327    /// The live tail changes every request; caching it would write an entry
328    /// per turn and never read one back.
329    #[test]
330    fn the_message_breakpoint_skips_the_live_tail() {
331        let cache = PromptCache::new("session-1");
332        let messages = vec![
333            Message::system("prefix"),
334            Message::user("hello"),
335            Message::assistant("hi"),
336            Message::system("live tail"),
337        ];
338        let parameters = cache.apply(Parameters::default(), &messages, false, true);
339        let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(&parameters) else {
340            panic!("expected explicit claude breakpoints");
341        };
342        assert_eq!(
343            breakpoints.second.map(|point| point.target),
344            Some(ClaudeCacheBreakpointTarget::Message {
345                message_index: 1,
346                block_index: 0,
347            }),
348            "breakpoint must land on the last stable message, not the tail"
349        );
350    }
351
352    /// The index is into the list Claude is sent, which lacks the leading
353    /// system prefix.
354    #[test]
355    fn the_message_breakpoint_indexes_the_claude_message_list() {
356        let cache = PromptCache::new("session-1");
357        let messages = vec![
358            Message::system("prefix"),
359            Message::user("hello"),
360            Message::system("live tail"),
361        ];
362        let parameters = cache.apply(Parameters::default(), &messages, false, true);
363        let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(&parameters) else {
364            panic!("expected explicit claude breakpoints");
365        };
366        assert_eq!(
367            breakpoints.second.map(|point| point.target),
368            Some(ClaudeCacheBreakpointTarget::Message {
369                message_index: 0,
370                block_index: 0,
371            })
372        );
373    }
374
375    /// A model without mid-conversation system messages folds the tail into
376    /// `system`, so the Claude list holds only the conversation.
377    #[test]
378    fn without_the_ability_no_system_message_counts() {
379        let cache = PromptCache::new("session-1");
380        let messages = vec![
381            Message::system("prefix"),
382            Message::user("hello"),
383            Message::assistant("hi"),
384            Message::system("live tail"),
385        ];
386        let parameters = cache.apply(Parameters::default(), &messages, false, false);
387        let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(&parameters) else {
388            panic!("expected explicit claude breakpoints");
389        };
390        assert_eq!(
391            breakpoints.second.map(|point| point.target),
392            Some(ClaudeCacheBreakpointTarget::Message {
393                message_index: 1,
394                block_index: 0,
395            })
396        );
397    }
398
399    #[test]
400    fn a_stable_system_prefix_gets_no_message_breakpoint() {
401        let cache = PromptCache::new("session-1");
402        let messages = vec![
403            Message::system("prefix"),
404            Message::system("more prefix"),
405            Message::system("live tail"),
406        ];
407        let parameters = cache.apply(Parameters::default(), &messages, false, true);
408        let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(&parameters) else {
409            panic!("expected explicit claude breakpoints");
410        };
411        assert!(breakpoints.second.is_none());
412    }
413
414    #[test]
415    fn with_ttl_keeps_the_lifetime_coherent() {
416        let cache = PromptCache::new("s").with_ttl(ClaudePromptCacheTtl::FiveMinutes);
417        assert_eq!(
418            cache.lifetime(),
419            CacheLifetime::Limited(Duration::from_secs(300))
420        );
421    }
422
423    #[test]
424    fn a_prefix_only_request_gets_no_message_breakpoint() {
425        let cache = PromptCache::new("session-1");
426        let messages = vec![Message::system("prefix")];
427        let parameters = cache.apply(Parameters::default(), &messages, false, true);
428        let ClaudePromptCacheStrategy::Explicit(breakpoints) = claude_strategy(&parameters) else {
429            panic!("expected explicit claude breakpoints");
430        };
431        assert!(breakpoints.second.is_none());
432    }
433}