Skip to main content

lean_ctx/proxy/
cache_safety.rs

1//! Cache-preservation telemetry for the proxy's frozen-region prose rewrites
2//! (#710).
3//!
4//! The proxy only ever rewrites prose inside the cache-safe frozen window
5//! `[cached_prefix_len, boundary)` — never inside the client-cached prefix and
6//! never in the live tail. This module turns that invariant into a *measurable*
7//! production signal: every request that performs a frozen-region prose rewrite
8//! reports whether the rewrite stayed cache-safe, and `/status` surfaces the
9//! resulting ratio (`1.0` = every rewrite was provably cache-safe, the
10//! healthy steady state). A value below `1.0` is a regression signal.
11
12use std::sync::atomic::{AtomicU64, Ordering};
13
14use serde::{Deserialize, Serialize};
15
16/// Total prose segments (text fields) compressed across all requests.
17static PROSE_SEGMENTS: AtomicU64 = AtomicU64::new(0);
18/// Requests that performed at least one frozen-region prose rewrite.
19static PROSE_REQUESTS: AtomicU64 = AtomicU64::new(0);
20/// Of those, the requests whose every rewrite was cache-safe.
21static CACHE_SAFE_REQUESTS: AtomicU64 = AtomicU64::new(0);
22/// Deliberate cold-prefix repacks (#480): requests where the proxy predicted the
23/// client-cached prefix was already cold and rewrote it on purpose. Tracked
24/// separately so an *intentional* prefix rewrite never dilutes the
25/// `cache_safe_ratio`, whose job is to catch *accidental* #448 regressions.
26static COLD_PREFIX_REPACKS: AtomicU64 = AtomicU64::new(0);
27/// Prompt-cache breakpoints the proxy actively injected (#939): requests where a
28/// client set no `cache_control` and the proxy added one on `system` so an
29/// otherwise-uncached prefix bills at the cached rate. Pure win signal.
30static BREAKPOINTS_INJECTED: AtomicU64 = AtomicU64::new(0);
31/// Requests whose unanchored system prompt carried at least one volatile,
32/// cache-busting field (#940, cache-aligner telemetry). A measurement-only
33/// signal — the body is never mutated — that quantifies how much cache the
34/// client's system prompt leaks before any opt-in relocate.
35static VOLATILE_SYSTEM_REQUESTS: AtomicU64 = AtomicU64::new(0);
36/// Cumulative volatile fields detected across those requests (#940).
37static VOLATILE_FIELDS_DETECTED: AtomicU64 = AtomicU64::new(0);
38
39/// Record one request's frozen-region prose activity.
40///
41/// `segments` is how many prose fields were compressed this request; `all_safe`
42/// is `true` when *every* rewrite landed strictly inside the cache-safe frozen
43/// window. A no-op request (`segments == 0`) is not counted, so the ratio
44/// reflects only requests that actually mutated prose.
45pub fn record(segments: u64, all_safe: bool) {
46    if segments == 0 {
47        return;
48    }
49    PROSE_SEGMENTS.fetch_add(segments, Ordering::Relaxed);
50    PROSE_REQUESTS.fetch_add(1, Ordering::Relaxed);
51    if all_safe {
52        CACHE_SAFE_REQUESTS.fetch_add(1, Ordering::Relaxed);
53    }
54}
55
56/// Record one deliberate cold-prefix repack (#480). Counted on its own gauge,
57/// never against [`record`]'s cache-safe ratio.
58pub fn record_cold_repack() {
59    COLD_PREFIX_REPACKS.fetch_add(1, Ordering::Relaxed);
60}
61
62/// Record one actively-injected prompt-cache breakpoint (#939).
63pub fn record_breakpoint_injected() {
64    BREAKPOINTS_INJECTED.fetch_add(1, Ordering::Relaxed);
65}
66
67/// Record one unanchored-system scan that found `fields` volatile fields (#940).
68/// A no-op when none were found, so the gauges count only cache-leaking requests.
69pub fn record_volatile_system(fields: u64) {
70    if fields == 0 {
71        return;
72    }
73    VOLATILE_SYSTEM_REQUESTS.fetch_add(1, Ordering::Relaxed);
74    VOLATILE_FIELDS_DETECTED.fetch_add(fields, Ordering::Relaxed);
75}
76
77/// Cache-preservation ratio: `safe / total`, or `1.0` when nothing has been
78/// rewritten yet (the trivially-safe empty state). Pure, so it is unit-tested
79/// independently of the global counters.
80#[must_use]
81pub fn ratio(safe: u64, total: u64) -> f64 {
82    if total == 0 {
83        return 1.0;
84    }
85    safe as f64 / total as f64
86}
87
88/// Point-in-time view of the cache-safety counters for `/status`.
89#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
90pub struct CacheSafety {
91    /// Prose segments compressed in the frozen region (cumulative).
92    pub prose_segments_compressed: u64,
93    /// Requests that performed at least one frozen-region prose rewrite.
94    pub prose_requests: u64,
95    /// Fraction of those requests whose every rewrite was cache-safe (`1.0` is
96    /// the healthy steady state; the proxy only rewrites inside the cache-safe
97    /// window by construction).
98    pub cache_safe_ratio: f64,
99    /// Deliberate cold-prefix repacks (#480), cumulative. Non-zero only when the
100    /// opt-in mode fired on a predicted-cold session resume — expected, not a
101    /// regression.
102    #[serde(default)]
103    pub cold_prefix_repacks: u64,
104    /// Prompt-cache breakpoints the proxy actively injected (#939), cumulative.
105    /// Non-zero only when the opt-in `cache_breakpoint` mode added a `system`
106    /// breakpoint for a client that set none — a pure cache win, not a regression.
107    #[serde(default)]
108    pub breakpoints_injected: u64,
109    /// Requests whose unanchored system prompt leaked at least one volatile field
110    /// (#940), cumulative. Measurement-only (the body is never mutated); non-zero
111    /// only when the opt-in `cache_aligner` telemetry is enabled.
112    #[serde(default)]
113    pub volatile_system_requests: u64,
114    /// Volatile fields detected across those requests (#940), cumulative.
115    #[serde(default)]
116    pub volatile_fields_detected: u64,
117}
118
119#[must_use]
120pub fn snapshot() -> CacheSafety {
121    let prose_requests = PROSE_REQUESTS.load(Ordering::Relaxed);
122    let safe = CACHE_SAFE_REQUESTS.load(Ordering::Relaxed);
123    CacheSafety {
124        prose_segments_compressed: PROSE_SEGMENTS.load(Ordering::Relaxed),
125        prose_requests,
126        cache_safe_ratio: ratio(safe, prose_requests),
127        cold_prefix_repacks: COLD_PREFIX_REPACKS.load(Ordering::Relaxed),
128        breakpoints_injected: BREAKPOINTS_INJECTED.load(Ordering::Relaxed),
129        volatile_system_requests: VOLATILE_SYSTEM_REQUESTS.load(Ordering::Relaxed),
130        volatile_fields_detected: VOLATILE_FIELDS_DETECTED.load(Ordering::Relaxed),
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn ratio_is_one_when_empty() {
140        assert_eq!(ratio(0, 0), 1.0);
141    }
142
143    #[test]
144    fn ratio_reflects_unsafe_rewrites() {
145        assert_eq!(ratio(3, 3), 1.0);
146        assert_eq!(ratio(2, 4), 0.5);
147        assert_eq!(ratio(0, 2), 0.0);
148    }
149}