Skip to main content

lean_ctx/proxy/
determinism_guard.rs

1//! Formal, verifiable prompt-cache safety for proxy request rewrites.
2//!
3//! A provider can reuse a prompt-cache entry only while its cached prefix stays
4//! byte-identical. This module makes that invariant observable: it canonicalizes
5//! cache-relevant messages, hashes their frozen prefix, and writes compact audit
6//! records for offline verification.
7
8use std::{
9    collections::BTreeMap,
10    fs::{self, OpenOptions},
11    io::Write,
12    path::PathBuf,
13};
14
15use axum::{
16    http::{HeaderMap, HeaderValue, request::Parts},
17    response::Response,
18};
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21
22/// A cryptographic proof that a provider-cached message prefix was preserved.
23#[derive(Clone, Debug, Deserialize, Serialize)]
24pub struct DeterminismProof {
25    /// Stable request identifier supplied by the proxy trace layer.
26    pub request_id: String,
27    /// BLAKE3 of the cache-relevant prefix before lean-ctx processing.
28    pub prefix_hash_before: String,
29    /// BLAKE3 of the cache-relevant prefix after lean-ctx processing.
30    pub prefix_hash_after: String,
31    /// `true` only when both prefix hashes are identical.
32    pub is_stable: bool,
33    /// Exact number of canonical JSON bytes equal before the first modification.
34    pub frozen_bytes: usize,
35    /// Byte offset at which lean-ctx processing first differs from the input.
36    pub modification_start_byte: usize,
37}
38
39/// Verifies transformations under one proxy trace id.
40#[derive(Clone, Debug)]
41pub struct DeterminismGuard {
42    request_id: String,
43}
44
45impl DeterminismGuard {
46    #[must_use]
47    pub fn new(request_id: impl Into<String>) -> Self {
48        Self {
49            request_id: request_id.into(),
50        }
51    }
52
53    /// Produces a proof for the supplied request id.
54    #[must_use]
55    pub fn verify(&self, before: &[Value], after: &[Value]) -> DeterminismProof {
56        verify_with_request_id(&self.request_id, before, after)
57    }
58}
59
60/// Verifies that `after` leaves the provider-cached prefix of `before` intact.
61///
62/// Both slices are canonical JSON arrays. `frozen_bytes` is their common byte
63/// prefix. The proof hashes the cached-message prefix when one exists. Without
64/// explicit `cache_control` breakpoints the proof prefix is empty (stable by
65/// definition): the proxy cannot determine the provider's auto-cache boundary,
66/// so it allows compression of any message.
67#[must_use]
68pub fn verify_determinism(before: &[Value], after: &[Value]) -> DeterminismProof {
69    let request_id = blake3::hash(&canonical_messages(before))
70        .to_hex()
71        .to_string();
72    verify_with_request_id(&request_id, before, after)
73}
74
75fn verify_with_request_id(request_id: &str, before: &[Value], after: &[Value]) -> DeterminismProof {
76    let before_bytes = canonical_messages(before);
77    let after_bytes = canonical_messages(after);
78    let frozen_bytes = common_prefix_len(&before_bytes, &after_bytes);
79    let cached_messages = cache_breakpoint_len(before);
80    let proof_prefix_bytes = if cached_messages > 0 {
81        canonical_message_prefix_len(before, cached_messages)
82    } else {
83        // No explicit cache_control breakpoints — we cannot determine the
84        // provider's auto-cache boundary. Tool-result dedup and content dedup
85        // may legitimately modify any message, so there is no safe frozen region
86        // to verify. The guard only adds value when the client declares a
87        // cache boundary via cache_control.
88        0
89    };
90    let before_prefix = &before_bytes[..proof_prefix_bytes];
91    let after_prefix = after_bytes
92        .get(..proof_prefix_bytes)
93        .unwrap_or(&after_bytes);
94    let prefix_hash_before = blake3::hash(before_prefix).to_hex().to_string();
95    let prefix_hash_after = blake3::hash(after_prefix).to_hex().to_string();
96
97    DeterminismProof {
98        request_id: request_id.to_owned(),
99        is_stable: prefix_hash_before == prefix_hash_after,
100        prefix_hash_before,
101        prefix_hash_after,
102        frozen_bytes,
103        modification_start_byte: frozen_bytes,
104    }
105}
106
107/// Extracts the fields whose order and content determine prompt-cache reuse.
108///
109/// Anthropic carries `system` outside `messages`; modeling it as the first
110/// message lets the same proof detect a cached system-prompt mutation.
111#[must_use]
112pub fn cache_relevant_messages(request: &Value) -> Vec<Value> {
113    let mut messages = Vec::new();
114    if let Some(system) = request.get("system") {
115        messages.push(serde_json::json!({"role": "system", "content": system}));
116    }
117    if let Some(items) = request
118        .get("messages")
119        .or_else(|| request.get("input"))
120        .and_then(Value::as_array)
121    {
122        messages.extend(items.iter().cloned());
123    }
124    messages
125}
126
127/// Parses an incoming proxy body without mutating it, including supported
128/// content encodings. Invalid bodies intentionally yield `None` and pass through.
129#[must_use]
130pub fn parse_request_body(body: &[u8], parts: &Parts, limit: usize) -> Option<Value> {
131    use crate::proxy::codec::{
132        RequestBodyEncoding, decode_gzip_bounded, decode_zstd_bounded, request_body_encoding,
133    };
134
135    let decoded = match request_body_encoding(parts) {
136        RequestBodyEncoding::Identity => body.to_vec(),
137        RequestBodyEncoding::Gzip => decode_gzip_bounded(body, limit).ok()?,
138        RequestBodyEncoding::Zstd => decode_zstd_bounded(body, limit).ok()?,
139        RequestBodyEncoding::Passthrough => return None,
140    };
141    serde_json::from_slice(&decoded).ok()
142}
143
144/// Applies the public verification headers to a proxied response.
145pub fn apply_response_headers(response: &mut Response, proof: &DeterminismProof) {
146    let headers = response.headers_mut();
147    headers.insert(
148        "x-leanctx-determinism",
149        HeaderValue::from_static(if proof.is_stable {
150            "stable"
151        } else {
152            "unstable"
153        }),
154    );
155    insert_header(
156        headers,
157        "x-leanctx-frozen-bytes",
158        &proof.frozen_bytes.to_string(),
159    );
160    headers.insert(
161        "x-leanctx-cache-safe",
162        HeaderValue::from_static(if proof.is_stable { "true" } else { "false" }),
163    );
164    insert_header(headers, "x-leanctx-proof-hash", &proof.prefix_hash_after);
165}
166
167/// Adds deterministic defaults for responses that never enter the shared
168/// forwarder (health, auth refusals, local APIs, and WebSocket handshakes).
169pub fn ensure_response_headers(response: &mut Response) {
170    if !response.headers().contains_key("x-leanctx-determinism") {
171        apply_response_headers(response, &verify_determinism(&[], &[]));
172    }
173}
174
175fn insert_header(headers: &mut HeaderMap, name: &str, value: &str) {
176    if let (Ok(header_name), Ok(header_value)) = (
177        axum::http::HeaderName::from_bytes(name.as_bytes()),
178        HeaderValue::from_str(value),
179    ) {
180        headers.insert(header_name, header_value);
181    }
182}
183
184#[derive(Clone, Debug, Deserialize, Serialize)]
185struct AuditRecord {
186    proof: DeterminismProof,
187    violation: bool,
188}
189
190/// A machine-readable audit summary for `lean-ctx audit determinism`.
191#[derive(Clone, Debug, Deserialize, Serialize)]
192pub struct DeterminismAuditReport {
193    pub total_requests: usize,
194    pub stable_count: usize,
195    pub unstable_count: usize,
196    pub stability_rate: f64,
197    pub violations: Vec<DeterminismProof>,
198}
199
200const AUDIT_FILE: &str = "proxy-determinism-audit.jsonl";
201
202fn audit_path() -> Option<PathBuf> {
203    crate::core::data_dir::lean_ctx_data_dir()
204        .ok()
205        .map(|dir| dir.join(AUDIT_FILE))
206}
207
208/// Persists a compact, newline-delimited proof record for offline audit.
209pub fn record_audit(proof: &DeterminismProof, violation: bool) {
210    let Some(path) = audit_path() else {
211        return;
212    };
213    let Some(parent) = path.parent() else {
214        return;
215    };
216    if let Err(error) = fs::create_dir_all(parent) {
217        tracing::debug!(%error, "determinism audit directory unavailable");
218        return;
219    }
220    let record = AuditRecord {
221        proof: proof.clone(),
222        violation,
223    };
224    let Ok(line) = serde_json::to_string(&record) else {
225        return;
226    };
227    match OpenOptions::new().create(true).append(true).open(path) {
228        Ok(mut file) => {
229            if let Err(error) = writeln!(file, "{line}") {
230                tracing::debug!(%error, "determinism audit write failed");
231            }
232        }
233        Err(error) => tracing::debug!(%error, "determinism audit file unavailable"),
234    }
235}
236
237/// Reads the recent determinism audit records and summarizes cache safety.
238#[must_use]
239pub fn audit_report() -> DeterminismAuditReport {
240    let records = audit_path()
241        .and_then(|path| fs::read_to_string(path).ok())
242        .map(|contents| {
243            contents
244                .lines()
245                .filter_map(|line| serde_json::from_str::<AuditRecord>(line).ok())
246                .collect::<Vec<_>>()
247        })
248        .unwrap_or_default();
249    let total_requests = records.len();
250    let violations = records
251        .iter()
252        .filter(|record| record.violation || !record.proof.is_stable)
253        .map(|record| record.proof.clone())
254        .collect::<Vec<_>>();
255    let unstable_count = violations.len();
256    let stable_count = total_requests.saturating_sub(unstable_count);
257    let stability_rate = if total_requests == 0 {
258        1.0
259    } else {
260        stable_count as f64 / total_requests as f64
261    };
262    DeterminismAuditReport {
263        total_requests,
264        stable_count,
265        unstable_count,
266        stability_rate,
267        violations,
268    }
269}
270
271fn canonical_messages(messages: &[Value]) -> Vec<u8> {
272    canonical_json(&Value::Array(messages.to_vec()))
273}
274
275fn canonical_message_prefix_len(messages: &[Value], count: usize) -> usize {
276    if count == 0 {
277        return 0;
278    }
279    let mut bytes = Vec::from(b"[".as_slice());
280    for (index, message) in messages.iter().take(count).enumerate() {
281        if index > 0 {
282            bytes.push(b',');
283        }
284        write_canonical_json(message, &mut bytes);
285    }
286    bytes.len()
287}
288
289fn canonical_json(value: &Value) -> Vec<u8> {
290    let mut bytes = Vec::new();
291    write_canonical_json(value, &mut bytes);
292    bytes
293}
294
295fn write_canonical_json(value: &Value, out: &mut Vec<u8>) {
296    match value {
297        Value::Array(items) => {
298            out.push(b'[');
299            for (index, item) in items.iter().enumerate() {
300                if index > 0 {
301                    out.push(b',');
302                }
303                write_canonical_json(item, out);
304            }
305            out.push(b']');
306        }
307        Value::Object(map) => {
308            out.push(b'{');
309            let sorted = map.iter().collect::<BTreeMap<_, _>>();
310            for (index, (key, item)) in sorted.into_iter().enumerate() {
311                if index > 0 {
312                    out.push(b',');
313                }
314                out.extend(serde_json::to_vec(key).expect("JSON object keys serialize"));
315                out.push(b':');
316                write_canonical_json(item, out);
317            }
318            out.push(b'}');
319        }
320        _ => out.extend(serde_json::to_vec(value).expect("JSON scalar serializes")),
321    }
322}
323
324fn common_prefix_len(before: &[u8], after: &[u8]) -> usize {
325    before
326        .iter()
327        .zip(after)
328        .take_while(|(left, right)| left == right)
329        .count()
330}
331
332fn cache_breakpoint_len(messages: &[Value]) -> usize {
333    messages
334        .iter()
335        .enumerate()
336        .filter_map(|(index, message)| message_has_cache_control(message).then_some(index + 1))
337        .last()
338        .unwrap_or_default()
339}
340
341fn message_has_cache_control(message: &Value) -> bool {
342    if message.get("cache_control").is_some() {
343        return true;
344    }
345    message
346        .get("content")
347        .and_then(Value::as_array)
348        .is_some_and(|blocks| {
349            blocks.iter().any(|block| {
350                block.get("cache_control").is_some()
351                    || block
352                        .get("content")
353                        .and_then(Value::as_array)
354                        .is_some_and(|items| {
355                            items.iter().any(|item| item.get("cache_control").is_some())
356                        })
357            })
358        })
359}
360
361#[cfg(test)]
362mod tests {
363    use axum::{body::Body, response::Response};
364    use serde_json::json;
365
366    use super::{apply_response_headers, canonical_messages, verify_determinism};
367
368    #[test]
369    fn stable_cached_prefix_produces_a_stable_proof() {
370        let before = vec![
371            json!({"role": "user", "content": "frozen", "cache_control": {"type": "ephemeral"}}),
372            json!({"role": "user", "content": "live"}),
373        ];
374        let after = vec![
375            before[0].clone(),
376            json!({"role": "user", "content": "rewritten live"}),
377        ];
378
379        let proof = verify_determinism(&before, &after);
380
381        assert!(proof.is_stable);
382        assert_eq!(proof.prefix_hash_before, proof.prefix_hash_after);
383    }
384
385    #[test]
386    fn modified_cached_prefix_is_unstable() {
387        let before = vec![json!({"role": "user", "content": "frozen", "cache_control": {}})];
388        let after = vec![json!({"role": "user", "content": "changed", "cache_control": {}})];
389
390        assert!(!verify_determinism(&before, &after).is_stable);
391    }
392
393    #[test]
394    fn single_message_without_cache_control_allows_compression() {
395        let before = vec![json!({"role": "user", "content": "frozen"})];
396        let after = vec![json!({"role": "user", "content": "changed"})];
397        assert!(verify_determinism(&before, &after).is_stable);
398    }
399
400    #[test]
401    fn last_message_modification_without_cache_control_is_stable() {
402        let before = vec![
403            json!({"role": "system", "content": "rules"}),
404            json!({"role": "user", "content": "original"}),
405        ];
406        let after = vec![
407            json!({"role": "system", "content": "rules"}),
408            json!({"role": "user", "content": "compressed"}),
409        ];
410        assert!(verify_determinism(&before, &after).is_stable);
411    }
412
413    #[test]
414    fn any_modification_without_cache_control_is_stable() {
415        // Without cache_control markers the proxy cannot know the auto-cache
416        // boundary, so all modifications (including earlier messages) are allowed.
417        let before = vec![
418            json!({"role": "system", "content": "rules"}),
419            json!({"role": "user", "content": "q1"}),
420            json!({"role": "assistant", "content": "a1"}),
421            json!({"role": "user", "content": "q2"}),
422        ];
423        let after = vec![
424            json!({"role": "system", "content": "MODIFIED"}),
425            json!({"role": "user", "content": "q1"}),
426            json!({"role": "assistant", "content": "a1"}),
427            json!({"role": "user", "content": "q2"}),
428        ];
429        assert!(verify_determinism(&before, &after).is_stable);
430    }
431
432    #[test]
433    fn explicit_cache_control_still_catches_violations() {
434        // With explicit cache_control the guard MUST detect modifications
435        // within the cached region.
436        let before = vec![
437            json!({"role": "system", "content": [{"type": "text", "text": "rules", "cache_control": {}}]}),
438            json!({"role": "user", "content": "q1"}),
439        ];
440        let after = vec![
441            json!({"role": "system", "content": [{"type": "text", "text": "MODIFIED", "cache_control": {}}]}),
442            json!({"role": "user", "content": "q1"}),
443        ];
444        assert!(!verify_determinism(&before, &after).is_stable);
445    }
446
447    #[test]
448    fn cached_system_message_modification_is_detected() {
449        let before = vec![
450            json!({"role": "system", "content": [{"type": "text", "text": "rules", "cache_control": {}}]}),
451        ];
452        let after = vec![
453            json!({"role": "system", "content": [{"type": "text", "text": "changed", "cache_control": {}}]}),
454        ];
455
456        assert!(!verify_determinism(&before, &after).is_stable);
457    }
458
459    #[test]
460    fn frozen_byte_count_matches_the_common_canonical_prefix() {
461        let before = vec![json!({"role": "user", "content": "same", "cache_control": {}})];
462        let after = vec![json!({"role": "user", "content": "different", "cache_control": {}})];
463        let before_bytes = canonical_messages(&before);
464        let after_bytes = canonical_messages(&after);
465        let expected = before_bytes
466            .iter()
467            .zip(&after_bytes)
468            .take_while(|(left, right)| left == right)
469            .count();
470
471        assert_eq!(verify_determinism(&before, &after).frozen_bytes, expected);
472    }
473
474    #[test]
475    fn proof_headers_are_set() {
476        let proof = verify_determinism(&[], &[]);
477        let mut response = Response::new(Body::empty());
478
479        apply_response_headers(&mut response, &proof);
480
481        let headers = response.headers();
482        assert_eq!(headers["x-leanctx-determinism"], "stable");
483        assert_eq!(headers["x-leanctx-frozen-bytes"], "2");
484        assert_eq!(headers["x-leanctx-cache-safe"], "true");
485        assert_eq!(headers["x-leanctx-proof-hash"], proof.prefix_hash_after);
486    }
487}