Skip to main content

rig_core/providers/gemini/
caching.rs

1//! Automatic explicit caching for long Gemini runs.
2//!
3//! [`Caching`](super::Caching) is a transport that wraps another. Every `generateContent`
4//! and `streamGenerateContent` request passes through it with its encoded
5//! body, and a shared [`CacheBook`] decides what the request reads from a
6//! cache and when a new cache is worth creating:
7//!
8//! ```no_run
9//! use rig_core::providers::gemini::{AutoCache, CacheBook, Gemini};
10//!
11//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
12//! let gemini = Gemini::from_env()?;
13//! let book = CacheBook::new(AutoCache::default());
14//! let model = gemini.completion("gemini-3.8-flash").caching(&book);
15//! // ... run an agent or a chat on `model` ...
16//! book.close(&gemini.cached_contents()).await;
17//! println!("{:?}", book.report());
18//! # Ok(())
19//! # }
20//! ```
21//!
22//! An explicit cache (`cachedContents`) holds the conversation so far, and a
23//! request that reads it sends only what came after. Caches cannot be
24//! extended or chained, so a growing conversation needs a new cache from
25//! time to time, billed again at the input price. The `Auto` policy creates
26//! one once the input premium the conversation paid for tokens a cache could
27//! have held covers the new cache's creation and storage, and stays inline
28//! above `implicit_ceiling` tokens until Gemini's implicit caching is seen
29//! failing. Only the Gemini Developer API is covered: not Interactions,
30//! which has no explicit caching, Vertex AI, `rig-gemini-grpc` or
31//! hosted-tool parts.
32
33use std::collections::{BTreeMap, HashMap, HashSet};
34use std::sync::{Arc, Mutex};
35use std::time::Duration;
36
37use indexmap::IndexMap;
38use serde::{Deserialize, Serialize};
39use serde_json::value::RawValue;
40use sha2::{Digest, Sha256};
41
42use crate::json_utils::remove_preserving_order;
43
44/// Unix seconds.
45#[cfg(not(target_family = "wasm"))]
46pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
47/// Unix seconds (browser wasm: no `Send + Sync`, no threads).
48#[cfg(target_family = "wasm")]
49pub type Clock = Arc<dyn Fn() -> u64>;
50
51/// Seconds since the Unix epoch, also on the web.
52fn system_now() -> u64 {
53    crate::now_ms() / 1000
54}
55
56/// The longest TTL the book gives a cache: past about 81 minutes between
57/// reads, storage costs more than a cached read saves at the default prices.
58const MAX_TTL_SECS: u64 = 81 * 60;
59
60/// How long a cache delete may go unanswered. A cache whose delete runs out
61/// of time stays in the book.
62pub(crate) const DELETE_TIMEOUT: Duration =
63    Duration::from_millis(if cfg!(test) { 500 } else { 10_000 });
64
65/// A cache is used only with more than this many seconds left.
66const EXPIRY_MARGIN_SECS: u64 = 5;
67
68/// A conversation cache unread for this long, or three times its line's
69/// longest gap if longer, belongs to a conversation that moved on.
70const MIN_IDLE_SECS: u64 = 60;
71
72/// The `Auto` policy's parameters. The price ratios default to
73/// gemini-3.8-flash standard prices relative to its input price (cached read
74/// $0.075 and storage $0.50 per 1M tokens per hour, against $0.75 input);
75/// [`AutoCache::for_spec`] reads the cached-read ratio of another model
76/// from its catalog spec. The catalog holds no storage price.
77#[derive(Clone, Copy, Debug, PartialEq)]
78pub struct AutoCache {
79    /// The shortest TTL a new cache gets. A cache that would come within 5
80    /// seconds of expiry before its next expected call is not created.
81    pub ttl: Duration,
82    /// Smallest request implicit caching serves (4,096 tokens on Gemini 3).
83    pub implicit_floor: u64,
84    /// Above this many cacheable tokens the book sends requests inline and
85    /// lets implicit caching serve them, until implicit caching is seen
86    /// failing.
87    pub implicit_ceiling: u64,
88    /// Gemini's minimum cache size.
89    pub min_tokens: u64,
90    /// The fewest tokens a new cache must add over the one it replaces.
91    pub min_gain: u64,
92    /// Cached-read price over input price.
93    pub cached_ratio: f64,
94    /// Storage price per hour over input price.
95    pub storage_ratio_per_hour: f64,
96}
97
98impl Default for AutoCache {
99    fn default() -> Self {
100        Self {
101            ttl: Duration::from_secs(60 * 60),
102            implicit_floor: 4_096,
103            implicit_ceiling: 16_000,
104            min_tokens: 1_024,
105            min_gain: 256,
106            cached_ratio: 0.1,
107            storage_ratio_per_hour: 0.5 / 0.75,
108        }
109    }
110}
111
112impl AutoCache {
113    /// The default policy with the cached-read ratio of `spec`'s pricing,
114    /// such as the spec a model carries ([`DynModel::spec`]). A spec with no
115    /// usable price keeps the default ratio.
116    ///
117    /// [`DynModel::spec`]: crate::DynModel::spec
118    pub fn for_spec(spec: &crate::catalog::ModelSpec) -> Self {
119        Self::priced(spec.pricing.as_ref())
120    }
121
122    /// The default policy with the cached-read ratio of `pricing`. Without
123    /// a cached-read price, with a negative one, or with no positive input
124    /// price to divide by, the default ratio stays.
125    fn priced(pricing: Option<&crate::catalog::Pricing>) -> Self {
126        let ratio = pricing
127            .and_then(|pricing| Some((pricing.cache_read?, pricing.input)))
128            .filter(|(read, input)| *read >= 0.0 && *input > 0.0)
129            .map(|(read, input)| read / input);
130        let default = Self::default();
131        Self {
132            cached_ratio: ratio.unwrap_or(default.cached_ratio),
133            ..default
134        }
135    }
136}
137
138/// One cache the book holds.
139#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
140pub struct Lease {
141    /// `cachedContents/<id>`.
142    pub name: String,
143    /// Hex SHA-256 of the prefix the cache holds. Its first 40 characters
144    /// end the cache's display name, which is how [`CacheBook::prove`]
145    /// recognizes it.
146    pub digest: String,
147    /// How many contents the cache holds.
148    pub covers: usize,
149    /// Its size, as Gemini counted it when it was created.
150    pub tokens: u64,
151    /// Unix seconds.
152    pub expires_at: u64,
153    /// The model the cache belongs to.
154    pub model: String,
155}
156
157impl Lease {
158    /// Whether a request sent at `now` can still read the cache.
159    pub(crate) fn live_at(&self, now: u64) -> bool {
160        self.expires_at > now + EXPIRY_MARGIN_SECS
161    }
162}
163
164/// Something that happened to a cache.
165#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
166pub enum CacheEvent {
167    /// A cache was created.
168    Created {
169        /// `cachedContents/<id>`.
170        name: String,
171        /// Its size, as Gemini counted it.
172        tokens: u64,
173        /// The book's estimate of its size before creating it.
174        estimated: u64,
175        /// How many contents it holds.
176        covers: usize,
177        /// Its TTL.
178        ttl_secs: u64,
179        /// Unix seconds.
180        at: u64,
181    },
182    /// The book deleted a cache it no longer needs.
183    Retired {
184        /// `cachedContents/<id>`.
185        name: String,
186        /// Unix seconds.
187        at: u64,
188    },
189    /// A cache answered 403 when a request named it, and was forgotten.
190    Lost {
191        /// `cachedContents/<id>`.
192        name: String,
193        /// Unix seconds.
194        at: u64,
195    },
196    /// A cache's expiry was pushed back.
197    Extended {
198        /// `cachedContents/<id>`.
199        name: String,
200        /// The new expiry, Unix seconds.
201        expires_at: u64,
202        /// Unix seconds.
203        at: u64,
204    },
205    /// Gemini refused to create a cache; the request went out without it.
206    CreateFailed {
207        /// The HTTP status, when there was one.
208        status: Option<u16>,
209        /// Gemini's message.
210        message: String,
211        /// Unix seconds.
212        at: u64,
213    },
214}
215
216/// One cache the book created.
217#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
218pub struct CreatedCache {
219    /// `cachedContents/<id>`.
220    pub name: String,
221    /// Its size.
222    pub tokens: u64,
223    /// Unix seconds.
224    pub at: u64,
225}
226
227/// What the book's caches did and cost, for pricing a run. Creation is
228/// billed like input (`tokens` × input price); storage is `token_hours` ×
229/// the storage price.
230#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
231pub struct CacheReport {
232    /// Every cache created, in order.
233    pub created: Vec<CreatedCache>,
234    /// How many requests read each cache, by name.
235    pub reads: BTreeMap<String, u64>,
236    /// Caches the book deleted because a roll replaced them, their
237    /// conversation moved on, or [`CacheBook::close`] ran.
238    pub retired: Vec<String>,
239    /// Caches that answered 403 and were forgotten.
240    pub lost: Vec<String>,
241    /// Σ tokens × hours each cache lived, until it was deleted, lost or
242    /// expired, or until now for a live one.
243    pub token_hours: f64,
244    /// The caches requests read.
245    pub live: Vec<Lease>,
246}
247
248#[derive(Clone, Debug, Default)]
249struct Line {
250    /// Premium tokens: cacheable input paid at full price, weighted by
251    /// `1 - cached_ratio`, since the line last rolled.
252    premium: f64,
253    /// EWMA of implicit coverage on inline calls big enough for it.
254    implicit: Option<f64>,
255    rolled_at: u64,
256    last_call: Option<u64>,
257    longest_gap: u64,
258    /// Coverable size at the last refused creation: no retry until the line
259    /// grows past it.
260    failed_at: Option<u64>,
261}
262
263#[derive(Clone, Debug)]
264struct Life {
265    tokens: u64,
266    created: u64,
267    expires_at: u64,
268    ended: Option<u64>,
269    last_read: u64,
270    /// Requests that read it, the one that created it among them.
271    reads: u64,
272    line_gap: u64,
273}
274
275/// The calls seen on one prefix.
276#[derive(Default)]
277struct Lineage {
278    /// The conversations on it, by their first content.
279    firsts: HashSet<String>,
280    /// When the current run of calls began: the calls one cache made then
281    /// would have served.
282    run_start: Option<u64>,
283    /// The calls in the run after its first, which that cache would have
284    /// read.
285    run_reads: u64,
286    /// The reads a run must show before an unproven cache is created. It
287    /// doubles with each cache that expired with no reader but its creator.
288    owed: u64,
289}
290
291#[derive(Default)]
292pub(crate) struct Book {
293    pub(crate) leases: HashMap<String, Lease>,
294    lives: BTreeMap<String, Life>,
295    lineages: HashMap<String, Lineage>,
296    /// Caches a replacement took the digest of, by name. They may still be
297    /// alive on the server, so they stay the book's until they are deleted.
298    displaced: HashMap<String, Lease>,
299    /// How many times [`CacheBook::close`] ran, so that a create it did not
300    /// see knows to delete its cache.
301    pub(crate) closes: u64,
302    lines: HashMap<String, Line>,
303    events: Vec<CacheEvent>,
304    report: CacheReport,
305    /// Gemini's tokens over this book's estimate, learned from each cache it
306    /// creates.
307    calibration: Option<f64>,
308}
309
310/// The shared, content-addressed record of the caches a set of models
311/// reads. Clone it into every model that should share caches: sub-agents on
312/// one prefix, a resumed run and its successor.
313///
314/// The book never sends a cache it knows has expired. A new cache's TTL is at
315/// least twice the longest gap seen between calls, never less than
316/// [`AutoCache::ttl`] and never more than 81 minutes, and a cache read close
317/// to expiry is extended. An expired shared-prefix cache that only its
318/// creator read is replaced after a run of calls one cache could have
319/// served, twice as long each time. A cache that answers 403 is forgotten and the
320/// request is sent again inline, once. A replaced cache stays in
321/// [`Self::leases`] until the roll deletes it, a conversation cache nobody
322/// has read for a while is deleted, and [`Self::close`] deletes everything
323/// still live. To resume, store [`Self::leases`] with the checkpoint, then
324/// call [`Self::restore`] and [`Self::prove`] on a new book.
325#[derive(Clone)]
326pub struct CacheBook {
327    inner: Arc<Mutex<Book>>,
328    /// Serializes cache creation, so a prefix is created once.
329    pub(crate) create: Arc<futures::lock::Mutex<()>>,
330    policy: AutoCache,
331    clock: Clock,
332    pub(crate) display_prefix: Arc<str>,
333}
334
335impl std::fmt::Debug for CacheBook {
336    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337        f.debug_struct("CacheBook")
338            .field("policy", &self.policy)
339            .field("display_prefix", &self.display_prefix)
340            .finish_non_exhaustive()
341    }
342}
343
344impl CacheBook {
345    /// A book with `policy`, on the system clock.
346    pub fn new(policy: AutoCache) -> Self {
347        Self {
348            inner: Arc::default(),
349            create: Arc::default(),
350            policy,
351            clock: Arc::new(system_now),
352            display_prefix: Arc::from("rig-cache-"),
353        }
354    }
355
356    /// The same book reading time from `clock` (Unix seconds).
357    pub fn with_clock(
358        mut self,
359        clock: impl Fn() -> u64
360        + crate::wasm_compat::WasmCompatSend
361        + crate::wasm_compat::WasmCompatSync
362        + 'static,
363    ) -> Self {
364        self.clock = Arc::new(clock);
365        self
366    }
367
368    /// The same book naming its caches `<prefix><digest>`, so they can be
369    /// listed and swept. Defaults to `rig-cache-`.
370    pub fn with_display_prefix(mut self, prefix: &str) -> Self {
371        self.display_prefix = Arc::from(prefix);
372        self
373    }
374
375    /// The book's policy.
376    pub fn policy(&self) -> AutoCache {
377        self.policy
378    }
379
380    pub(crate) fn book(&self) -> std::sync::MutexGuard<'_, Book> {
381        crate::lock(&self.inner)
382    }
383
384    pub(crate) fn now(&self) -> u64 {
385        (self.clock)()
386    }
387
388    /// Everything that happened to the book's caches, in order.
389    pub fn events(&self) -> Vec<CacheEvent> {
390        self.book().events.clone()
391    }
392
393    /// Every cache the book has not seen deleted, for a checkpoint: those it
394    /// reads and those a replacement displaced.
395    pub fn leases(&self) -> Vec<Lease> {
396        let book = self.book();
397        let held = book.leases.values().chain(book.displaced.values());
398        let mut leases: Vec<Lease> = held.cloned().collect();
399        leases.sort_by(|a, b| a.name.cmp(&b.name));
400        leases
401    }
402
403    /// Put checkpointed leases back. Call [`Self::prove`] next. A lease
404    /// whose name is not `cachedContents/<id>` is reported lost, since the
405    /// requests that delete or extend it would put its name in their path.
406    pub fn restore(&self, leases: Vec<Lease>) {
407        let now = self.now();
408        let mut book = self.book();
409        let mut bad = Vec::new();
410        for lease in leases {
411            if !lease
412                .name
413                .strip_prefix("cachedContents/")
414                .is_some_and(super::cached_content::is_resource_id)
415            {
416                bad.push(lease);
417                continue;
418            }
419            book.lives.entry(lease.name.clone()).or_insert(Life {
420                tokens: lease.tokens,
421                created: now,
422                expires_at: lease.expires_at,
423                ended: None,
424                last_read: now,
425                // Whoever created it read it once.
426                reads: 1,
427                line_gap: 0,
428            });
429            book.hold(lease);
430        }
431        drop(book);
432        for lease in &bad {
433            self.lost(lease);
434        }
435    }
436
437    /// What the caches did and cost so far.
438    pub fn report(&self) -> CacheReport {
439        let now = self.now();
440        let book = self.book();
441        let mut report = book.report.clone();
442        report.token_hours = book
443            .lives
444            .values()
445            .map(|life| {
446                let end = life.ended.unwrap_or(now).min(life.expires_at);
447                life.tokens as f64 * end.saturating_sub(life.created) as f64 / 3600.0
448            })
449            .sum();
450        report.live = book.leases.values().cloned().collect();
451        report.live.sort_by(|a, b| a.name.cmp(&b.name));
452        report
453    }
454
455    pub(crate) fn retired(&self, lease: &Lease) {
456        let now = self.now();
457        let mut book = self.book();
458        book.forget(lease, now);
459        book.events.push(CacheEvent::Retired {
460            name: lease.name.clone(),
461            at: now,
462        });
463        book.report.retired.push(lease.name.clone());
464        tracing::info!(target: "gemini.cache.retired", name = %lease.name);
465    }
466
467    pub(crate) fn lost(&self, lease: &Lease) {
468        let now = self.now();
469        let mut book = self.book();
470        book.forget(lease, now);
471        book.events.push(CacheEvent::Lost {
472            name: lease.name.clone(),
473            at: now,
474        });
475        book.report.lost.push(lease.name.clone());
476        tracing::info!(target: "gemini.cache.lost", name = %lease.name);
477    }
478}
479
480impl Book {
481    /// Whether `lease` is the cache requests on its digest read.
482    fn holds(&self, lease: &Lease) -> bool {
483        self.leases
484            .get(&lease.digest)
485            .is_some_and(|held| held.name == lease.name)
486    }
487
488    /// Whether `lease` is not yet deleted, as far as the book knows.
489    fn owns(&self, lease: &Lease) -> bool {
490        self.holds(lease) || self.displaced.contains_key(&lease.name)
491    }
492
493    /// Take `lease` in. The later expiry holds its digest, so a restore needs
494    /// no order, and the other cache is displaced, never dropped.
495    fn hold(&mut self, lease: Lease) {
496        let (held, other) = match self.leases.remove(&lease.digest) {
497            Some(old) if old.expires_at > lease.expires_at => (old, Some(lease)),
498            old => (lease, old),
499        };
500        if let Some(other) = other.filter(|other| other.name != held.name) {
501            self.displaced.insert(other.name.clone(), other);
502        }
503        self.leases.insert(held.digest.clone(), held);
504    }
505
506    /// Stop holding `lease`, now it is gone, and end its life. A live cache
507    /// displaced from its digest takes over.
508    fn forget(&mut self, lease: &Lease, now: u64) {
509        self.displaced.remove(&lease.name);
510        if self.holds(lease) {
511            self.leases.remove(&lease.digest);
512            let next = self
513                .displaced
514                .values()
515                .filter(|other| other.digest == lease.digest && other.live_at(now))
516                .max_by_key(|other| other.expires_at)
517                .map(|other| other.name.clone());
518            if let Some(next) = next.and_then(|name| self.displaced.remove(&name)) {
519                self.hold(next);
520            }
521        }
522        if let Some(life) = self.lives.get_mut(&lease.name)
523            && life.ended.is_none()
524        {
525            life.ended = Some(now);
526        }
527    }
528}
529
530pub(crate) fn short_digest(digest: &str) -> &str {
531    digest.get(..40).unwrap_or(digest)
532}
533
534// ---------------------------------------------------------------------------
535// Request bodies: parsing, digests, stripping and cache bodies.
536
537const PREFIX_KEYS: [&str; 3] = ["systemInstruction", "tools", "toolConfig"];
538
539/// A `generateContent` body, its contents kept as their exact bytes.
540pub(crate) struct Parsed {
541    /// Every other top-level field, in order, as exact bytes.
542    pub(crate) rest: Vec<(String, Box<RawValue>)>,
543    /// `systemInstruction`, `tools` and `toolConfig`, when present and not null.
544    pub(crate) prefix: [Option<Box<RawValue>>; 3],
545    pub(crate) contents: Vec<Box<RawValue>>,
546    pub(crate) has_cached_content: bool,
547}
548
549pub(crate) fn parse(bytes: &[u8]) -> Option<Parsed> {
550    // A repeated key keeps its first place and its last value, as `IndexMap::insert` does.
551    let members: IndexMap<String, Box<RawValue>> = serde_json::from_slice(bytes).ok()?;
552    let mut parsed = Parsed {
553        rest: Vec::new(),
554        prefix: [None, None, None],
555        contents: Vec::new(),
556        has_cached_content: false,
557    };
558    for (key, value) in members {
559        if key == "contents" {
560            parsed.contents = serde_json::from_str(value.get()).ok()?;
561        } else if let Some(slot) = PREFIX_KEYS.iter().position(|prefix| *prefix == key) {
562            if value.get() != "null"
563                && let Some(field) = parsed.prefix.get_mut(slot)
564            {
565                *field = Some(value);
566            }
567        } else {
568            if key == "cachedContent" && value.get() != "null" {
569                parsed.has_cached_content = true;
570            }
571            parsed.rest.push((key, value));
572        }
573    }
574    Some(parsed)
575}
576
577fn hex(bytes: &[u8]) -> String {
578    use std::fmt::Write;
579    bytes.iter().fold(String::new(), |mut out, byte| {
580        let _ = write!(out, "{byte:02x}");
581        out
582    })
583}
584
585/// What the book reads off a body, before it takes its lock.
586pub(crate) struct Digested {
587    /// `d[k]`: the digest of the model, the prefix and `contents[..k]`.
588    pub(crate) d: Vec<String>,
589    /// The token estimate of the prefix.
590    pub(crate) prefix: u64,
591    /// The token estimate of each content.
592    pub(crate) contents: Vec<u64>,
593}
594
595pub(crate) fn digests(model: &str, parsed: &Parsed) -> Digested {
596    let mut hasher = Sha256::new();
597    hasher.update(model.as_bytes());
598    let mut prefix = 0;
599    for field in &parsed.prefix {
600        hasher.update([0u8]);
601        if let Some(raw) = field {
602            prefix += digest(&mut hasher, raw.get());
603        }
604    }
605    let mut state = hasher.finalize().to_vec();
606    let mut d = vec![hex(&state)];
607    let mut contents = Vec::with_capacity(parsed.contents.len());
608    for content in &parsed.contents {
609        let mut hasher = Sha256::new();
610        hasher.update(&state);
611        contents.push(digest(&mut hasher, content.get()));
612        state = hasher.finalize().to_vec();
613        d.push(hex(&state));
614    }
615    Digested {
616        d,
617        prefix,
618        contents,
619    }
620}
621
622/// Hash `fragment` with its keys sorted (a history replays a provider part
623/// with the key order it arrived in, which a recording does not keep, so
624/// the digests read the content, not its spelling), and return a rough
625/// token count of it: its bytes over four, without thought signatures,
626/// which Gemini expands into restored thoughts that no explicit cache holds.
627fn digest(hasher: &mut Sha256, fragment: &str) -> u64 {
628    let Ok(mut value) = serde_json::from_str::<serde_json::Value>(fragment) else {
629        hasher.update(fragment.as_bytes());
630        return (fragment.len() / 4) as u64;
631    };
632    hasher.update(crate::json_utils::to_canonical_string(&value).as_bytes());
633    fn scrub(value: &mut serde_json::Value) {
634        match value {
635            serde_json::Value::Object(map) => {
636                remove_preserving_order(map, "thoughtSignature");
637                map.values_mut().for_each(scrub);
638            }
639            serde_json::Value::Array(items) => items.iter_mut().for_each(scrub),
640            _ => {}
641        }
642    }
643    scrub(&mut value);
644    (value.to_string().len() / 4) as u64
645}
646
647/// Whether a content is the user's text: a new user turn, not a tool result.
648pub(crate) fn is_user_text(raw: &RawValue) -> bool {
649    #[derive(Deserialize)]
650    struct Content {
651        role: Option<String>,
652        #[serde(default)]
653        parts: Vec<serde_json::Map<String, serde_json::Value>>,
654    }
655    serde_json::from_str::<Content>(raw.get()).is_ok_and(|content| {
656        content.role.as_deref() == Some("user")
657            && content.parts.iter().any(|part| part.contains_key("text"))
658            && !content
659                .parts
660                .iter()
661                .any(|part| part.contains_key("functionResponse"))
662    })
663}
664
665/// The body that reads `lease` instead of what it holds.
666pub(crate) fn stripped(parsed: &Parsed, lease: &Lease) -> Option<Vec<u8>> {
667    let name = serde_json::value::to_raw_value(&lease.name).ok()?;
668    let contents = serde_json::value::to_raw_value(&parsed.contents.get(lease.covers..)?).ok()?;
669    let mut out: IndexMap<&str, &RawValue> = IndexMap::new();
670    out.insert("cachedContent", &name);
671    out.insert("contents", &contents);
672    out.extend(
673        parsed
674            .rest
675            .iter()
676            .filter(|(key, _)| key != "cachedContent")
677            .map(|(key, value)| (key.as_str(), &**value)),
678    );
679    serde_json::to_vec(&out).ok()
680}
681
682/// The `cachedContents` create body for the first `covers` contents, from
683/// the request's own bytes.
684pub(crate) fn cache_body(
685    model: &str,
686    parsed: &Parsed,
687    covers: usize,
688    display_name: &str,
689    ttl_secs: u64,
690) -> Option<Vec<u8>> {
691    let mut bytes = b"{".to_vec();
692    let mut field = |key: &str, value: &str| {
693        if bytes.len() > 1 {
694            bytes.push(b',');
695        }
696        bytes.extend(format!("\"{key}\":").as_bytes());
697        bytes.extend(value.as_bytes());
698    };
699    field(
700        "model",
701        &serde_json::to_string(&format!("models/{model}")).ok()?,
702    );
703    field("displayName", &serde_json::to_string(display_name).ok()?);
704    field("ttl", &format!("\"{ttl_secs}s\""));
705    for (key, value) in PREFIX_KEYS.iter().zip(&parsed.prefix) {
706        if let Some(value) = value {
707            field(key, value.get());
708        }
709    }
710    if covers > 0 {
711        let contents = serde_json::value::to_raw_value(&parsed.contents.get(..covers)?).ok()?;
712        field("contents", contents.get());
713    }
714    bytes.push(b'}');
715    Some(bytes)
716}
717
718// ---------------------------------------------------------------------------
719// The plan.
720
721/// What one request reads, creates, retires and extends.
722pub(crate) struct Plan {
723    pub(crate) read: Option<Lease>,
724    pub(crate) create: Option<Create>,
725    pub(crate) retire: Vec<Lease>,
726    pub(crate) extend: Option<(Lease, u64)>,
727    pub(crate) line: String,
728    pub(crate) coverable: u64,
729    pub(crate) closes: u64,
730}
731
732pub(crate) struct Create {
733    pub(crate) covers: usize,
734    pub(crate) digest: String,
735    pub(crate) ttl_secs: u64,
736    /// Uncalibrated bytes/4 estimate of what the cache holds.
737    estimate: u64,
738    /// The calibrated estimate the plan used.
739    expected: u64,
740    pub(crate) replaces: Option<Lease>,
741}
742
743impl CacheBook {
744    pub(crate) fn plan(&self, model: &str, digested: &Digested, roll_allowed: bool) -> Plan {
745        let p = self.policy;
746        let now = self.now();
747        let n = digested.contents.len();
748        // `d` holds one digest per content boundary, `0..=n`.
749        let at = |k: usize| digested.d.get(k).map_or("", String::as_str);
750        let (prefix_estimate, content_estimates) = (digested.prefix, &digested.contents);
751        let mut guard = self.book();
752        let book = &mut *guard;
753        let calibration = book.calibration.unwrap_or(1.0);
754
755        // Who shares this prefix: a second conversation on it (sub-agents,
756        // concurrent users, or the conversation a compaction started).
757        let lineage = book.lineages.entry(at(0).to_owned()).or_default();
758        if n >= 1 {
759            lineage.firsts.insert(at(1).to_owned());
760        }
761        let shared = lineage.firsts.len() >= 2;
762
763        // Retire conversation caches nobody reads any more.
764        let idle: Vec<Lease> = book
765            .leases
766            .values()
767            .filter(|lease| lease.covers > 0 && lease.model == model)
768            .filter(|lease| {
769                book.lives.get(&lease.name).is_some_and(|life| {
770                    now.saturating_sub(life.last_read)
771                        > MIN_IDLE_SECS.max(life.line_gap.saturating_mul(3))
772                })
773            })
774            .cloned()
775            .collect();
776
777        // The longest live cache this request starts with; never the newest content.
778        let read = (0..n.max(1))
779            .rev()
780            .find_map(|k| {
781                book.leases
782                    .get(at(k))
783                    .filter(|lease| lease.model == model)
784                    .filter(|lease| lease.live_at(now))
785                    .cloned()
786            })
787            .filter(|lease| !idle.iter().any(|gone| gone.name == lease.name));
788        let covered = read.as_ref().map_or(0, |lease| lease.covers);
789        let tail: u64 = content_estimates
790            .get(covered..n.saturating_sub(1).max(covered))
791            .unwrap_or_default()
792            .iter()
793            .sum();
794        let coverable = match &read {
795            Some(lease) => lease.tokens + (tail as f64 * calibration) as u64,
796            None => ((prefix_estimate + tail) as f64 * calibration) as u64,
797        };
798
799        // The conversation's line: its cache, or its first content when inline.
800        let line_key = read
801            .as_ref()
802            .filter(|lease| lease.covers > 0)
803            .map_or_else(|| at(1.min(n)).to_owned(), |lease| lease.digest.clone());
804        let held_prefix = book.leases.get(at(0));
805        let prefix_leased = held_prefix.is_some_and(|lease| lease.live_at(now));
806        let prefix_proven = held_prefix
807            .and_then(|lease| book.lives.get(&lease.name))
808            .is_some_and(|life| life.reads > 1);
809        let prefix_unread = held_prefix.is_some() && !prefix_proven;
810        let line = book.lines.entry(line_key.clone()).or_insert_with(|| Line {
811            rolled_at: now,
812            ..Line::default()
813        });
814        if let Some(last) = line.last_call {
815            line.longest_gap = line.longest_gap.max(now.saturating_sub(last));
816        }
817        line.last_call = Some(now);
818        let longest_gap = line.longest_gap;
819        let ttl_secs = p
820            .ttl
821            .as_secs()
822            .max(longest_gap.saturating_mul(2).min(MAX_TTL_SECS))
823            .max(1);
824
825        // A proven cache earns its replacement. Without one, a cache must look
826        // likely to be read: this run of calls has to have shown enough reads.
827        let lineage = book.lineages.entry(at(0).to_owned()).or_default();
828        let in_run = |start: &u64| ttl_secs > now.saturating_sub(*start) + EXPIRY_MARGIN_SECS;
829        if lineage.run_start.as_ref().is_some_and(in_run) {
830            lineage.run_reads += 1;
831        } else {
832            lineage.run_start = Some(now);
833            lineage.run_reads = 0;
834        }
835        if prefix_proven {
836            lineage.owed = 0;
837        }
838        let owed = lineage
839            .owed
840            .max(1)
841            .saturating_mul(1 + u64::from(prefix_unread));
842
843        let mut plan = Plan {
844            read: read.clone(),
845            create: None,
846            retire: idle,
847            extend: None,
848            line: line_key,
849            coverable,
850            closes: book.closes,
851        };
852
853        // Past the ceiling, implicit caching serves: go inline until it fails.
854        let implicit_serving = line.implicit.is_none_or(|ratio| ratio >= 0.5);
855        if coverable >= p.implicit_ceiling && implicit_serving {
856            plan.read = None;
857            return plan;
858        }
859
860        // Create only what lives to the line's next call, or every call would
861        // create one. A gap past what the longest TTL spans is an idle spell,
862        // which must not stop a later cache.
863        let next_call = longest_gap.min(MAX_TTL_SECS / 2);
864        let may_create = ttl_secs > next_call + EXPIRY_MARGIN_SECS
865            && !line.failed_at.is_some_and(|at| coverable < at + p.min_gain);
866        if read.is_none()
867            && shared
868            && !prefix_leased
869            && (prefix_estimate as f64 * calibration) as u64 >= p.min_tokens
870            && may_create
871            && (prefix_proven || lineage.run_reads >= owed)
872        {
873            lineage.owed = owed;
874            plan.create = Some(Create {
875                covers: 0,
876                digest: at(0).to_owned(),
877                ttl_secs,
878                estimate: prefix_estimate,
879                expected: (prefix_estimate as f64 * calibration) as u64,
880                replaces: None,
881            });
882        } else if n >= 2 && roll_allowed && may_create {
883            let cached = read.as_ref().map_or(0, |lease| lease.tokens);
884            let gain = coverable.saturating_sub(cached);
885            let held_hours = now.saturating_sub(line.rolled_at).max(60) as f64 / 3600.0;
886            let cost = coverable as f64 * (1.0 + p.storage_ratio_per_hour * held_hours);
887            if gain >= p.min_gain && coverable >= p.min_tokens && line.premium >= cost {
888                plan.create = Some(Create {
889                    covers: n - 1,
890                    digest: at(n - 1).to_owned(),
891                    ttl_secs,
892                    estimate: prefix_estimate
893                        + content_estimates
894                            .get(..n - 1)
895                            .unwrap_or_default()
896                            .iter()
897                            .sum::<u64>(),
898                    expected: coverable,
899                    replaces: read.clone().filter(|lease| lease.covers > 0),
900                });
901            }
902        }
903
904        // Extend a cache that would expire before its line's next call.
905        if plan.create.is_none()
906            && let Some(lease) = &read
907            && longest_gap > 0
908            && lease.expires_at.saturating_sub(now) < longest_gap.saturating_mul(3) / 2
909        {
910            plan.extend = Some((lease.clone(), ttl_secs));
911        }
912        plan
913    }
914
915    /// Account for one reply's usage on `line`.
916    pub(crate) fn observe(&self, line: &str, read: Option<&str>, coverable: u64, cached: u64) {
917        let p = self.policy;
918        let mut book = self.book();
919        if let Some(name) = read {
920            *book.report.reads.entry(name.to_owned()).or_default() += 1;
921        }
922        let entry = book.lines.entry(line.to_owned()).or_default();
923        let mut missed = coverable.saturating_sub(cached) as f64;
924        if read.is_none() && coverable >= p.implicit_floor {
925            let ratio = cached as f64 / coverable.max(1) as f64;
926            let implicit = entry
927                .implicit
928                .map_or(ratio, |ewma| 0.5 * ewma + 0.5 * ratio);
929            entry.implicit = Some(implicit);
930            if implicit >= 0.5 {
931                missed = 0.0;
932            }
933        }
934        entry.premium += missed * (1.0 - p.cached_ratio);
935    }
936
937    pub(crate) fn created(
938        &self,
939        from_line: &str,
940        create: &Create,
941        name: String,
942        tokens: u64,
943        model: &str,
944    ) -> Lease {
945        let now = self.now();
946        let lease = Lease {
947            name: name.clone(),
948            digest: create.digest.clone(),
949            covers: create.covers,
950            tokens,
951            expires_at: now + create.ttl_secs,
952            model: model.to_owned(),
953        };
954        let mut book = self.book();
955        if create.estimate > 0 && tokens > 0 {
956            let ratio = tokens as f64 / create.estimate as f64;
957            book.calibration = Some(book.calibration.map_or(ratio, |c| 0.5 * c + 0.5 * ratio));
958        }
959        let previous = book.lines.get(from_line).cloned().unwrap_or_default();
960        if create.covers > 0 {
961            book.lines.insert(
962                lease.digest.clone(),
963                Line {
964                    premium: 0.0,
965                    implicit: previous.implicit,
966                    rolled_at: now,
967                    last_call: previous.last_call,
968                    longest_gap: previous.longest_gap,
969                    failed_at: None,
970                },
971            );
972        }
973        book.lives.insert(
974            name.clone(),
975            Life {
976                tokens,
977                created: now,
978                expires_at: lease.expires_at,
979                ended: None,
980                last_read: now,
981                reads: 0,
982                line_gap: previous.longest_gap,
983            },
984        );
985        book.events.push(CacheEvent::Created {
986            name: name.clone(),
987            tokens,
988            estimated: create.expected,
989            covers: create.covers,
990            ttl_secs: create.ttl_secs,
991            at: now,
992        });
993        book.report.created.push(CreatedCache {
994            name,
995            tokens,
996            at: now,
997        });
998        book.hold(lease.clone());
999        tracing::info!(target: "gemini.cache.created", name = %lease.name, tokens, covers = create.covers);
1000        lease
1001    }
1002
1003    pub(crate) fn create_failed(
1004        &self,
1005        line: &str,
1006        coverable: u64,
1007        status: Option<u16>,
1008        message: String,
1009    ) {
1010        let now = self.now();
1011        let mut book = self.book();
1012        if let Some(entry) = book.lines.get_mut(line) {
1013            entry.failed_at = Some(coverable);
1014        }
1015        book.events.push(CacheEvent::CreateFailed {
1016            status,
1017            message,
1018            at: now,
1019        });
1020    }
1021
1022    /// Whether the book still owns `lease`.
1023    pub(crate) fn owns(&self, lease: &Lease) -> bool {
1024        self.book().owns(lease)
1025    }
1026
1027    /// Record a successful extend. Returns whether the book still owns the
1028    /// cache; if not, the extend kept a retired cache alive.
1029    pub(crate) fn extended(&self, lease: &Lease, ttl_secs: u64) -> bool {
1030        let now = self.now();
1031        let expires_at = now + ttl_secs;
1032        let mut guard = self.book();
1033        let book = &mut *guard;
1034        let owned = book.owns(lease);
1035        let held = book.leases.get_mut(&lease.digest);
1036        let held = held.filter(|held| held.name == lease.name);
1037        if let Some(owned) = held.or(book.displaced.get_mut(&lease.name)) {
1038            owned.expires_at = expires_at;
1039        }
1040        if let Some(life) = book.lives.get_mut(&lease.name) {
1041            life.expires_at = expires_at;
1042        }
1043        book.events.push(CacheEvent::Extended {
1044            name: lease.name.clone(),
1045            expires_at,
1046            at: now,
1047        });
1048        tracing::info!(target: "gemini.cache.extended", name = %lease.name, expires_at);
1049        owned
1050    }
1051
1052    pub(crate) fn touched(&self, lease: &Lease) {
1053        let now = self.now();
1054        let mut book = self.book();
1055        let gap = book
1056            .lines
1057            .get(&lease.digest)
1058            .map_or(0, |line| line.longest_gap);
1059        if let Some(life) = book.lives.get_mut(&lease.name) {
1060            life.last_read = now;
1061            life.reads += 1;
1062            life.line_gap = life.line_gap.max(gap);
1063        }
1064    }
1065}
1066
1067#[cfg(test)]
1068mod tests;