Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(rust): A4 — honor cache_control markers; serde_json arbitrary_precision + raw_value
chopratejas3f991282364d
diff --git a/Cargo.toml b/Cargo.tomlindex 4905b4101..4b472ef6d 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -31,7 +31,21 @@ serde = { version = "1", features = ["derive"] }# smart_crusher port relies on this to match Python's `str(dict)` output,# which preserves insertion order; otherwise BTreeMap's sorted-key default# would diverge from Python on every multi-key object.-serde_json = { version = "1", features = ["preserve_order"] }+#+# `arbitrary_precision` keeps the literal numeric token from the source+# JSON intact: `Value::Number` becomes a wrapper around the original+# digit string, so `1.0` does NOT collapse to `1`, and `12345678901234567`+# does NOT lose precision through f64. Required by Realignment invariant+# I1 (byte-faithful passthrough on unmutated bytes; see REALIGNMENT/02-+# architecture.md §2.2) and PR-A4 (see REALIGNMENT/03-phase-A-lockdown.md).+#+# `raw_value` exposes `serde_json::value::RawValue`, the unparsed JSON+# fragment type. Phase B PR-B2 uses this to forward unmodified+# `messages[*]` entries as exact byte copies — the parser captures the+# original byte slice, so byte-for-byte round-trips work even with+# whitespace, key order, or escape preferences the producer chose.+# Enabled here in Phase A so PR-B2 can land as a pure consumer change.+serde_json = { version = "1", features = ["preserve_order", "arbitrary_precision", "raw_value"] }bytes = "1"thiserror = "1"tracing = "0.1"diff --git a/crates/headroom-core/src/cache_control.rs b/crates/headroom-core/src/cache_control.rsnew file mode 100644index 000000000..43ea5ccb0--- /dev/null+++ b/crates/headroom-core/src/cache_control.rs@@ -0,0 +1,414 @@+//! Customer `cache_control` marker walker for Anthropic `/v1/messages`+//! request bodies.+//!+//! # Why this exists+//!+//! Anthropic prompt caching pins a prefix of the request: every block+//! up to and including the last `cache_control` marker is part of+//! the cache key. The provider returns `cache_read_input_tokens` for+//! that prefix on subsequent requests; that's the customer's primary+//! lever for cost reduction.+//!+//! Headroom's compressor must **never** modify any byte that's part+//! of that prefix — doing so changes the cache key, drops the hit+//! rate to 0, and silently torches the customer's bill. Phase A+//! lockdown PR-A1 made `/v1/messages` a passthrough so we couldn't+//! cause this damage; PR-A4 (this module) computes the floor below+//! which Phase B's live-zone dispatcher must not touch.+//!+//! # Contract+//!+//! For an Anthropic request body parsed into `serde_json::Value`,+//! [`compute_frozen_count`] returns the smallest `N` such that+//! `messages[i]` is in the cache hot zone for every `i < N`.+//! Specifically:+//!+//! - For each marker found in `messages[i].content[*].cache_control`,+//! the function bumps `frozen_count` to at least `i + 1`. The "+1"+//! makes the floor exclusive: `messages[i]` itself is part of the+//! cached prefix, so it's frozen.+//! - For markers in `system` (string OR block list) or `tools[*]`,+//! the function does NOT bump `frozen_count`. Those fields are+//! unconditionally part of the cache hot zone (see invariant I2 in+//! `REALIGNMENT/02-architecture.md` §2.2); they're never touched by+//! the compressor regardless of marker placement, so they don't+//! affect the message-index floor.+//! - Returns `0` when there are no markers anywhere in `messages[*]`.+//!+//! # Why no regex+//!+//! Per the realignment build constraints+//! (`feedback_realignment_build_constraints.md` rule 3), pattern+//! detection uses parsers, not regex. We walk the parsed JSON tree+//! via `serde_json` accessors only — that's both safer (no+//! pattern-string typo risk) and faster (no compilation cost on+//! the hot path).+//!+//! # TTL ordering+//!+//! Per the Anthropic prompt-caching guide §2.19, when both `5m` and+//! `1h` markers appear, `1h` markers must precede `5m`. We compute+//! `frozen_count` correctly regardless of ordering, but emit a+//! `tracing::warn!` for the operator's benefit when the customer's+//! request violates the rule. We do NOT reject the request: it's the+//! customer's choice to make and Anthropic itself accepts both+//! orderings (just with potentially-suboptimal cache eviction).+//!+//! # Source priority+//!+//! Configurable on/off via `Config::cache_control_auto_frozen`+//! (CLI flag `--cache-control-auto-frozen` / env var+//! `HEADROOM_PROXY_CACHE_CONTROL_AUTO_FROZEN`). When `disabled`, the+//! caller bypasses [`compute_frozen_count`] entirely and treats every+//! message as live-zone. The function itself is config-agnostic; the+//! gate lives in the caller (the live-zone dispatcher in Phase B).++use serde_json::Value;++/// TTL marker value for the Anthropic 1-hour cache extension.+///+/// Per guide §2.19, the literal string `"1h"` selects the hour-long+/// ephemeral cache lane. We keep the constant here (rather than+/// inlining `"1h"` literal at use sites) so any future rename or+/// case-change is a single-edit affair. Avoiding magic strings is+/// rule 2 of the realignment build constraints.+const CACHE_TTL_1H: &str = "1h";++/// TTL marker value for the Anthropic 5-minute cache lane (the+/// default). Matches `cache_control.ttl == "5m"` literal.+const CACHE_TTL_5M: &str = "5m";++/// Walk the parsed Anthropic request body and return the smallest+/// `frozen_message_count` that respects every customer-set+/// `cache_control` marker.+///+/// # Arguments+///+/// - `parsed`: the request body as a `serde_json::Value`. The walker+/// reads `parsed.get("messages")`, `parsed.get("system")`, and+/// `parsed.get("tools")`. Other top-level fields are ignored.+///+/// # Returns+///+/// The lowest message index `N` such that `messages[i]` is frozen+/// for every `i < N`. Specifically:+/// - `0` when no markers are found in `messages[*]` (the live-zone+/// dispatcher is then free to compress every message).+/// - `i + 1` for the highest `i` whose `messages[i].content[*]`+/// contains a `cache_control` marker.+///+/// Markers in `system` and `tools[*]` do NOT raise the message-index+/// floor (those fields are unconditionally cache-hot; see module docs).+///+/// # Logging+///+/// Emits `tracing::debug!` for every marker found. Emits+/// `tracing::warn!` for any TTL ordering violation per guide §2.19+/// (a `5m` marker preceding a `1h` marker in the same field-list).+/// Returns the correct value regardless of ordering.+pub fn compute_frozen_count(parsed: &Value) -> usize {+ // Highest message-index marker seen so far. Tracked as `Option`+ // so a missing-vs-zero state is unambiguous: `None` means "no+ // marker observed", `Some(i)` means "saw a marker on index i".+ let mut highest_message_index: Option<usize> = None;++ // Walk `messages[*]` — the only field that affects the return+ // value. We log `system` and `tools` markers below for parity+ // with the design doc, but they don't bump the floor.+ walk_messages(parsed, &mut highest_message_index);++ // Walk `system` blocks for logging + TTL-ordering check only.+ // These markers never bump `frozen_count`; the system field is+ // always part of the cache hot zone independently.+ walk_system(parsed);++ // Walk `tools[*]` blocks for logging + TTL-ordering check only.+ walk_tools(parsed);++ // Translate the highest-marker index into a frozen-count floor.+ // The "+1" makes the floor exclusive: `messages[i]` itself is+ // part of the cached prefix, so the live-zone dispatcher must+ // not touch any index up to and including `i`.+ highest_message_index.map(|i| i + 1).unwrap_or(0)+}++/// Walk `parsed.messages[*].content[*]` and update+/// `highest_message_index` for any `cache_control` marker found.+///+/// The walker tolerates two content shapes Anthropic accepts:+/// - String content: `messages[i].content` is a JSON string. No+/// block list, so no `cache_control` marker possible.+/// - Block list: `messages[i].content` is an array. Each block is+/// an object that MAY have a top-level `cache_control` field.+fn walk_messages(parsed: &Value, highest_message_index: &mut Option<usize>) {+ let Some(messages) = parsed.get("messages").and_then(Value::as_array) else {+ return;+ };++ // Track per-message-list TTL ordering: across the entire+ // messages[*].content[*] sequence, every `1h` marker must+ // precede every `5m` marker. We log a single warning if the+ // rule is violated, regardless of how many violations there are+ // — the customer just needs to know once.+ let mut ttl_walk = TtlOrderingWalk::new();++ for (i, message) in messages.iter().enumerate() {+ let Some(content) = message.get("content") else {+ continue;+ };+ let Some(blocks) = content.as_array() else {+ // String content: no block list, no markers possible.+ continue;+ };+ for block in blocks {+ if let Some(marker) = block.get("cache_control") {+ let ttl = extract_ttl(marker);+ tracing::debug!(+ field = "messages",+ message_index = i,+ ttl = ttl.as_deref().unwrap_or("default"),+ "cache_control marker found"+ );+ ttl_walk.observe(ttl.as_deref());+ // Bump the floor.+ *highest_message_index = Some(match highest_message_index {+ Some(prev) => (*prev).max(i),+ None => i,+ });+ }+ }+ }++ ttl_walk.warn_if_violated("messages");+}++/// Walk `parsed.system` for `cache_control` markers. Logs at+/// `tracing::debug!` per marker; emits TTL-ordering warning. Does NOT+/// affect `frozen_count` — the system field is unconditionally+/// cache-hot.+///+/// `system` may be a string (no markers possible) or an array of+/// blocks. Mirrors the `messages[*].content` shape rules.+fn walk_system(parsed: &Value) {+ let Some(system) = parsed.get("system") else {+ return;+ };+ let Some(blocks) = system.as_array() else {+ // String system prompt: no block list, no markers.+ return;+ };+ let mut ttl_walk = TtlOrderingWalk::new();+ for block in blocks {+ if let Some(marker) = block.get("cache_control") {+ let ttl = extract_ttl(marker);+ tracing::debug!(+ field = "system",+ ttl = ttl.as_deref().unwrap_or("default"),+ "cache_control marker found"+ );+ ttl_walk.observe(ttl.as_deref());+ }+ }+ ttl_walk.warn_if_violated("system");+}++/// Walk `parsed.tools[*].cache_control` markers. Logs at+/// `tracing::debug!`; emits TTL-ordering warning. Does NOT affect+/// `frozen_count` — `tools` is unconditionally cache-hot.+fn walk_tools(parsed: &Value) {+ let Some(tools) = parsed.get("tools").and_then(Value::as_array) else {+ return;+ };+ let mut ttl_walk = TtlOrderingWalk::new();+ for (i, tool) in tools.iter().enumerate() {+ if let Some(marker) = tool.get("cache_control") {+ let ttl = extract_ttl(marker);+ tracing::debug!(+ field = "tools",+ tool_index = i,+ ttl = ttl.as_deref().unwrap_or("default"),+ "cache_control marker found"+ );+ ttl_walk.observe(ttl.as_deref());+ }+ }+ ttl_walk.warn_if_violated("tools");+}++/// Pull the optional `ttl` string out of a `cache_control` marker.+///+/// The marker is shaped `{"type": "ephemeral", "ttl": "1h"}` — the+/// `type` field is always `"ephemeral"` (Anthropic's only legal+/// value today) and `ttl` is optional, defaulting to `5m`. We+/// deliberately don't normalise here: returning `None` lets callers+/// distinguish "default 5m" from "explicit 5m" if they ever need to.+///+/// Returns `None` when `marker` isn't an object, when there's no+/// `ttl` key, or when `ttl` isn't a string.+fn extract_ttl(marker: &Value) -> Option<String> {+ marker.get("ttl")?.as_str().map(str::to_owned)+}++/// State machine for the TTL-ordering check (guide §2.19).+///+/// As we walk a sequence of markers, we record whether we've seen a+/// `5m` marker yet. If we then see a `1h` marker after that, the+/// rule is violated: `1h` markers must precede `5m`.+///+/// We accept all orderings (the customer's request, not ours to+/// reject) but emit one `tracing::warn!` per field-list when a+/// violation is detected, scoped to the field name passed to+/// `warn_if_violated` (e.g. `"messages"`, `"system"`, `"tools"`).+struct TtlOrderingWalk {+ seen_5m: bool,+ violated: bool,+}++impl TtlOrderingWalk {+ fn new() -> Self {+ Self {+ seen_5m: false,+ violated: false,+ }+ }++ /// Record one observed marker. `ttl` is `Some("1h")`, `Some("5m")`,+ /// `Some(other)`, or `None` (defaulting to 5m semantics). Only+ /// `1h`/`5m` participate in the ordering rule; unknown TTL values+ /// don't affect the state machine.+ fn observe(&mut self, ttl: Option<&str>) {+ // Default TTL is "5m" per guide §2.19. Treat None and+ // `Some("5m")` identically for ordering purposes.+ let is_5m = matches!(ttl, None | Some(CACHE_TTL_5M));+ let is_1h = matches!(ttl, Some(CACHE_TTL_1H));++ if is_5m {+ self.seen_5m = true;+ } else if is_1h && self.seen_5m {+ self.violated = true;+ }+ }++ fn warn_if_violated(&self, field: &'static str) {+ if self.violated {+ tracing::warn!(+ field = field,+ rule = "anthropic_prompt_caching_guide_2_19",+ "cache_control TTL ordering violation: 1h marker appears after 5m marker; \+ cache eviction may be suboptimal but request is forwarded"+ );+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn no_markers_yields_zero() {+ let body = json!({+ "model": "claude-3-5-sonnet-20241022",+ "messages": [+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": "hello"},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 0);+ }++ #[test]+ fn marker_at_message_zero_yields_one() {+ let body = json!({+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "first", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "assistant", "content": "second"},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 1);+ }++ #[test]+ fn marker_in_system_does_not_bump() {+ let body = json!({+ "system": [+ {"type": "text", "text": "you are helpful", "cache_control": {"type": "ephemeral"}}+ ],+ "messages": [+ {"role": "user", "content": "hi"},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 0);+ }++ #[test]+ fn marker_in_tools_does_not_bump() {+ let body = json!({+ "tools": [+ {"name": "search", "description": "search", "cache_control": {"type": "ephemeral"}}+ ],+ "messages": [+ {"role": "user", "content": "hi"},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 0);+ }++ #[test]+ fn missing_messages_yields_zero() {+ let body = json!({"model": "claude"});+ assert_eq!(compute_frozen_count(&body), 0);+ }++ #[test]+ fn string_content_yields_zero() {+ // String-shaped content can't carry a cache_control marker;+ // the walker must skip over it without panicking.+ let body = json!({+ "messages": [+ {"role": "user", "content": "plain string"},+ {"role": "assistant", "content": "another string"},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 0);+ }++ #[test]+ fn ttl_extracted_when_present() {+ let m = json!({"type": "ephemeral", "ttl": "1h"});+ assert_eq!(extract_ttl(&m).as_deref(), Some("1h"));+ }++ #[test]+ fn ttl_missing_returns_none() {+ let m = json!({"type": "ephemeral"});+ assert_eq!(extract_ttl(&m), None);+ }++ #[test]+ fn ttl_walker_accepts_1h_before_5m() {+ let mut w = TtlOrderingWalk::new();+ w.observe(Some("1h"));+ w.observe(Some("5m"));+ assert!(!w.violated);+ }++ #[test]+ fn ttl_walker_flags_5m_before_1h() {+ let mut w = TtlOrderingWalk::new();+ w.observe(Some("5m"));+ w.observe(Some("1h"));+ assert!(w.violated);+ }++ #[test]+ fn ttl_walker_treats_default_as_5m() {+ let mut w = TtlOrderingWalk::new();+ w.observe(None);+ w.observe(Some("1h"));+ assert!(w.violated);+ }+}diff --git a/crates/headroom-core/src/lib.rs b/crates/headroom-core/src/lib.rsindex 9b6fb70e4..0af75e54f 100644--- a/crates/headroom-core/src/lib.rs+++ b/crates/headroom-core/src/lib.rs@@ -1,5 +1,6 @@//! headroom-core: foundation crate for the Rust port of Headroom.+pub mod cache_control;pub mod ccr;pub mod context;pub mod relevance;@@ -8,6 +9,13 @@ pub mod signals;pub mod tokenizer;pub mod transforms;+// Re-exports for the live-zone dispatcher (Phase B PR-B2 consumes this).+// Hoisted to the crate root so the proxy crate gets one stable import+// path: `use headroom_core::compute_frozen_count;`. Keeping the+// `cache_control` module public too means downstream code can reach+// the helper types directly when needed.+pub use cache_control::compute_frozen_count;+/// Identity stub used by downstream crates and the Python binding to verify/// linkage end-to-end.pub fn hello() -> &'static str {diff --git a/crates/headroom-core/tests/cache_control.rs b/crates/headroom-core/tests/cache_control.rsnew file mode 100644index 000000000..cf343718c--- /dev/null+++ b/crates/headroom-core/tests/cache_control.rs@@ -0,0 +1,297 @@+//! Unit + property tests for the `cache_control` walker (PR-A4).+//!+//! These tests exercise [`headroom_core::compute_frozen_count`] in+//! isolation — no proxy, no upstream, no I/O. Integration tests that+//! drive the walker through the proxy live in+//! `crates/headroom-proxy/tests/integration_cache_control.rs`.++use headroom_core::compute_frozen_count;+use proptest::prelude::*;+use serde_json::{json, Value};++/// Marker placement table-driven cases. Spec (PR-A4):+/// - markers in `messages[i].content[*]` bump frozen_count to ≥ i+1+/// - markers in `system` or `tools[*]` do NOT bump+/// - returns max(i+1) across all messages, or 0 if no markers+#[test]+fn cache_control_marker_at_message_3_yields_frozen_count_4() {+ // Spec: marker on messages[3] => frozen_count = 4.+ // (4 messages are in the cache hot zone: indices 0, 1, 2, 3.)+ let body = json!({+ "messages": [+ {"role": "user", "content": "first"},+ {"role": "assistant", "content": "second"},+ {"role": "user", "content": "third"},+ {"role": "assistant", "content": [+ {"type": "text", "text": "fourth", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "user", "content": "fifth"},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 4);+}++#[test]+fn cache_control_in_system_blocks_does_not_bump_frozen_count() {+ // Spec: markers in `system` are unconditionally cache-hot;+ // they don't raise the message-index floor.+ let body = json!({+ "system": [+ {"type": "text", "text": "you are helpful", "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "cite sources", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ],+ "messages": [+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": "hello"},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 0);+}++#[test]+fn cache_control_in_tools_does_not_bump_frozen_count() {+ let body = json!({+ "tools": [+ {"name": "search", "description": "search the web", "cache_control": {"type": "ephemeral"}},+ {"name": "calc", "description": "calculator", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ],+ "messages": [+ {"role": "user", "content": "what is 2+2?"},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 0);+}++#[test]+fn cache_control_ttl_1h_before_5m_passes_no_warn() {+ // Per guide §2.19, `1h` markers must precede `5m` markers.+ // This ordering is the *correct* one; the function must return+ // the right frozen_count and emit no warning.+ //+ // We don't assert "no warning" here directly — capturing tracing+ // output requires a global subscriber that conflicts with other+ // tests. The "warning is emitted on violation" path is covered+ // by `cache_control_ttl_5m_before_1h_warns_and_passes` below+ // with a dedicated capture; here we just confirm the function+ // returns the correct floor under a legal ordering.+ let body = json!({+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "first 1h", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ]},+ {"role": "assistant", "content": [+ {"type": "text", "text": "second 5m", "cache_control": {"type": "ephemeral"}},+ ]},+ ],+ });+ // Both messages have markers; highest index is 1, so floor = 2.+ assert_eq!(compute_frozen_count(&body), 2);+}++#[test]+fn cache_control_no_markers_yields_zero() {+ let body = json!({+ "model": "claude-3-5-sonnet-20241022",+ "max_tokens": 1024,+ "messages": [+ {"role": "user", "content": "no marker here"},+ {"role": "assistant", "content": [+ {"type": "text", "text": "no marker either"},+ ]},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 0);+}++#[test]+fn cache_control_multiple_markers_in_messages_returns_max_index() {+ // Multiple markers across non-adjacent indices — function+ // returns max(i+1) per spec.+ let body = json!({+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "m0", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "assistant", "content": "m1 string"},+ {"role": "user", "content": [+ {"type": "text", "text": "m2", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "assistant", "content": [+ {"type": "text", "text": "m3"},+ ]},+ {"role": "user", "content": [+ {"type": "text", "text": "m4", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ]},+ {"role": "assistant", "content": "m5 string"},+ ],+ });+ // Highest marker is on index 4; floor = 5.+ assert_eq!(compute_frozen_count(&body), 5);+}++#[test]+fn cache_control_marker_on_multiple_blocks_within_one_message() {+ // Marker on multiple blocks of the SAME message — the message+ // index is what matters, not the block count. Floor = i+1 once.+ let body = json!({+ "messages": [+ {"role": "user", "content": "first"},+ {"role": "assistant", "content": [+ {"type": "text", "text": "block A", "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "block B", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ {"type": "text", "text": "block C", "cache_control": {"type": "ephemeral"}},+ ]},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 2);+}++#[test]+fn cache_control_string_content_skipped() {+ // Anthropic accepts both string and block-list `content`. The+ // walker must skip string content without panicking and without+ // hallucinating markers.+ let body = json!({+ "messages": [+ {"role": "user", "content": "plain string"},+ {"role": "assistant", "content": "another plain string"},+ {"role": "user", "content": [+ {"type": "text", "text": "now with marker", "cache_control": {"type": "ephemeral"}},+ ]},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 3);+}++#[test]+fn cache_control_missing_messages_field_yields_zero() {+ // Body has no `messages` field at all — walker tolerates and+ // returns 0.+ let body = json!({"model": "claude", "system": "you are helpful"});+ assert_eq!(compute_frozen_count(&body), 0);+}++#[test]+fn cache_control_messages_not_an_array_yields_zero() {+ // Defensive: malformed body where `messages` is a string.+ // Walker tolerates and returns 0 (no markers possible).+ let body = json!({"messages": "not an array"});+ assert_eq!(compute_frozen_count(&body), 0);+}++#[test]+fn cache_control_marker_with_non_object_content_block_skipped() {+ // Defensive: a content block isn't an object (shouldn't happen+ // per Anthropic spec, but we don't crash).+ let body = json!({+ "messages": [+ {"role": "user", "content": [+ "not an object",+ 42,+ null,+ {"type": "text", "text": "real block", "cache_control": {"type": "ephemeral"}},+ ]},+ ],+ });+ assert_eq!(compute_frozen_count(&body), 1);+}++// ─── Property tests ───────────────────────────────────────────────────++proptest! {+ #![proptest_config(ProptestConfig {+ cases: 256,+ .. ProptestConfig::default()+ })]++ /// Monotonic non-decrease: adding more markers to a body never+ /// *lowers* the frozen_count. Specifically, if we take a body with+ /// markers on a subset of indices and add a new marker on a+ /// higher index, the frozen_count grows; adding markers on an+ /// equal-or-lower index keeps the count.+ #[test]+ fn frozen_count_monotonic_non_decreasing(+ // Bound message count so proptest can shrink predictably.+ // We pick indices in 0..32 and unique-sort them so the test+ // exercises both adjacent and non-adjacent markers.+ marker_indices in proptest::collection::vec(0usize..32, 0..16),+ message_count in 32usize..=32,+ ) {+ // Build a body with markers on the deduplicated indices.+ let initial = build_body_with_markers(&marker_indices, message_count);+ let initial_count = compute_frozen_count(&initial);++ // Add a marker on a strictly higher index (max+1, or 0 if+ // empty) and recompute. The new floor must be >= old.+ let new_index = marker_indices.iter().copied().max().map(|m| m + 1).unwrap_or(0);+ if new_index < message_count {+ let mut more_indices = marker_indices.clone();+ more_indices.push(new_index);+ let augmented = build_body_with_markers(&more_indices, message_count);+ let augmented_count = compute_frozen_count(&augmented);+ prop_assert!(+ augmented_count >= initial_count,+ "monotonicity broken: initial={} augmented={} new_index={}",+ initial_count, augmented_count, new_index+ );+ }+ }++ /// Adding a marker to `system` or `tools` never changes+ /// frozen_count — those fields don't bump the message-index+ /// floor regardless of marker placement.+ #[test]+ fn system_and_tools_markers_dont_change_count(+ marker_indices in proptest::collection::vec(0usize..16, 0..8),+ message_count in 16usize..=16,+ ) {+ let bare = build_body_with_markers(&marker_indices, message_count);+ let bare_count = compute_frozen_count(&bare);++ // Same body but with system markers added.+ let mut with_system = bare.clone();+ with_system["system"] = json!([+ {"type": "text", "text": "sys", "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "sys2", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ]);+ prop_assert_eq!(compute_frozen_count(&with_system), bare_count);++ // And with tools markers.+ let mut with_tools = bare.clone();+ with_tools["tools"] = json!([+ {"name": "t", "description": "tool", "cache_control": {"type": "ephemeral"}},+ ]);+ prop_assert_eq!(compute_frozen_count(&with_tools), bare_count);+ }++ /// Empty messages array always yields 0.+ #[test]+ fn empty_messages_yields_zero(_dummy in 0u8..1) {+ let body = json!({"messages": []});+ prop_assert_eq!(compute_frozen_count(&body), 0);+ }+}++/// Build a request body with markers on the given message indices.+/// Indices outside `0..message_count` are ignored; duplicates are+/// fine. Used by the property tests above.+fn build_body_with_markers(marker_indices: &[usize], message_count: usize) -> Value {+ let messages: Vec<Value> = (0..message_count)+ .map(|i| {+ if marker_indices.contains(&i) {+ json!({+ "role": if i % 2 == 0 { "user" } else { "assistant" },+ "content": [+ {"type": "text", "text": format!("m{i}"), "cache_control": {"type": "ephemeral"}},+ ],+ })+ } else {+ json!({+ "role": if i % 2 == 0 { "user" } else { "assistant" },+ "content": format!("m{i}"),+ })+ }+ })+ .collect();+ json!({"messages": messages})+}diff --git a/crates/headroom-proxy/src/compression/anthropic.rs b/crates/headroom-proxy/src/compression/anthropic.rsindex 3e8671de0..f5213ea47 100644--- a/crates/headroom-proxy/src/compression/anthropic.rs+++ b/crates/headroom-proxy/src/compression/anthropic.rs@@ -40,8 +40,9 @@//! existing log context (added in `proxy.rs`).use bytes::Bytes;+use serde_json::Value;-use crate::config::CompressionMode;+use crate::config::{CacheControlAutoFrozen, CompressionMode};/// What happened. The caller uses the variant to decide whether to/// forward the original bytes (everything) or a modified body@@ -129,6 +130,55 @@ pub fn compress_anthropic_request(Outcome::NoCompression}+/// Resolve the `frozen_message_count` floor for a parsed Anthropic+/// `/v1/messages` request body, honouring the+/// `cache_control_auto_frozen` config gate (PR-A4).+///+/// This is a thin wrapper around [`headroom_core::compute_frozen_count`]+/// that returns `0` when the operator has disabled automatic+/// derivation, regardless of the markers in `parsed`. Intended to be+/// called by Phase B's live-zone dispatcher; PR-A4 ships it ready+/// for that consumer alongside the underlying core helper.+///+/// # Arguments+///+/// - `parsed`: parsed JSON body. The walker reads `messages`,+/// `system`, and `tools`; other fields are ignored. The function+/// itself does NOT mutate the value.+/// - `policy`: the resolved [`CacheControlAutoFrozen`] from `Config`.+/// `Disabled` short-circuits to `0` without inspecting the body.+/// - `request_id`: the per-request id used for log correlation,+/// matched against the proxy's existing `tracing` span fields.+///+/// # Returns+///+/// The frozen-count floor (smallest `N` such that `messages[i]` for+/// `i < N` is in the cache hot zone), or `0` when auto-derivation+/// is disabled. Phase B PR-B2 forbids the live-zone dispatcher from+/// touching any index below this value.+pub fn resolve_frozen_count(+ parsed: &Value,+ policy: CacheControlAutoFrozen,+ request_id: &str,+) -> usize {+ if !policy.is_enabled() {+ tracing::debug!(+ request_id = %request_id,+ cache_control_auto_frozen = policy.as_str(),+ "cache_control auto-derivation disabled; floor=0"+ );+ return 0;+ }+ let count = headroom_core::compute_frozen_count(parsed);+ tracing::debug!(+ request_id = %request_id,+ cache_control_auto_frozen = policy.as_str(),+ frozen_count = count,+ "cache_control auto-derivation result"+ );+ count+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/headroom-proxy/src/compression/mod.rs b/crates/headroom-proxy/src/compression/mod.rsindex 358570d5b..fa4e47fa1 100644--- a/crates/headroom-proxy/src/compression/mod.rs+++ b/crates/headroom-proxy/src/compression/mod.rs@@ -35,7 +35,7 @@pub mod anthropic;pub mod model_limits;-pub use anthropic::{compress_anthropic_request, Outcome, PassthroughReason};+pub use anthropic::{compress_anthropic_request, resolve_frozen_count, Outcome, PassthroughReason};/// Does this request path target an LLM endpoint we know how to/// compress? Cheap pre-filter before buffering the body. Phase Bdiff --git a/crates/headroom-proxy/src/config.rs b/crates/headroom-proxy/src/config.rsindex 27d711609..37c8efde0 100644--- a/crates/headroom-proxy/src/config.rs+++ b/crates/headroom-proxy/src/config.rs@@ -30,6 +30,54 @@ pub enum CompressionMode {LiveZone,}+/// Policy for automatically deriving `frozen_message_count` from the+/// customer's `cache_control` markers (PR-A4).+///+/// When `enabled` (default), the live-zone dispatcher will walk+/// `messages[*].content[*].cache_control` and bump the floor below+/// which compression is forbidden. When `disabled`, the floor stays+/// at 0 regardless of markers — Phase B's dispatcher will then treat+/// every message as live-zone, which is dangerous in production but+/// useful for benchmarking the cache-control machinery.+///+/// `system` and `tools[*]` markers never bump `frozen_count` because+/// those fields are *always* part of the cache hot zone (invariant I2);+/// they're guaranteed-immutable independently of marker placement.+///+/// Source priority: CLI flag → `HEADROOM_PROXY_CACHE_CONTROL_AUTO_FROZEN`+/// env var → default (`enabled`).+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]+#[clap(rename_all = "snake_case")]+pub enum CacheControlAutoFrozen {+ /// Walk customer `cache_control` markers and derive+ /// `frozen_message_count` automatically. Default.+ Enabled,+ /// Ignore customer `cache_control` markers when deriving+ /// `frozen_message_count`; the function returns 0 regardless of+ /// what the body contains. Intended for benchmarking and the+ /// "no automatic floor" testing path; not for production use.+ Disabled,+}++impl CacheControlAutoFrozen {+ /// Stable snake_case name suitable for log fields. Mirrors+ /// `CompressionMode::as_str` so the two policy fields render+ /// identically in JSON tracing output.+ pub fn as_str(self) -> &'static str {+ match self {+ CacheControlAutoFrozen::Enabled => "enabled",+ CacheControlAutoFrozen::Disabled => "disabled",+ }+ }++ /// Convenience: is the auto-frozen derivation switched on? Most+ /// callers want the boolean rather than pattern-matching on the+ /// enum.+ pub fn is_enabled(self) -> bool {+ matches!(self, CacheControlAutoFrozen::Enabled)+ }+}+impl CompressionMode {/// Stable snake_case name suitable for log fields. Avoids relying/// on `Debug` (which renders `Off`/`LiveZone`) or `Display`@@ -127,6 +175,26 @@ pub struct CliArgs {default_value_t = CompressionMode::Off,)]pub compression_mode: CompressionMode,++ /// Whether to derive `frozen_message_count` from customer+ /// `cache_control` markers in the request body (PR-A4).+ ///+ /// `enabled` (default): walk `messages[*].content[*].cache_control`+ /// and bump the floor for live-zone compression so any message+ /// the customer cache-pinned is left untouched. `disabled`: skip+ /// the walk; the floor stays at 0. The off switch exists for+ /// benchmark setups that want to measure compression independent+ /// of marker placement; it is NOT recommended for production.+ ///+ /// Source priority: CLI flag → `HEADROOM_PROXY_CACHE_CONTROL_AUTO_FROZEN`+ /// env var → default (`enabled`).+ #[arg(+ long = "cache-control-auto-frozen",+ env = "HEADROOM_PROXY_CACHE_CONTROL_AUTO_FROZEN",+ value_enum,+ default_value_t = CacheControlAutoFrozen::Enabled,+ )]+ pub cache_control_auto_frozen: CacheControlAutoFrozen,}fn parse_duration(s: &str) -> Result<Duration, String> {@@ -163,6 +231,11 @@ pub struct Config {/// because the dispatcher isn't implemented yet (Phase B PR-B2/// fills this in).pub compression_mode: CompressionMode,+ /// Whether the live-zone dispatcher derives `frozen_message_count`+ /// automatically from customer `cache_control` markers. PR-A4+ /// adds the derivation function (`compute_frozen_count`); Phase+ /// B's dispatcher consumes the resolved value here.+ pub cache_control_auto_frozen: CacheControlAutoFrozen,}impl Config {@@ -187,6 +260,7 @@ impl Config {compression: args.compression,compression_max_body_bytes,compression_mode: args.compression_mode,+ cache_control_auto_frozen: args.cache_control_auto_frozen,}}@@ -205,6 +279,9 @@ impl Config {compression: false,compression_max_body_bytes: 100 * 1024 * 1024,compression_mode: CompressionMode::Off,+ // Match production default so the cache-control walker is+ // exercised under test without per-test opt-in.+ cache_control_auto_frozen: CacheControlAutoFrozen::Enabled,}}}diff --git a/crates/headroom-proxy/tests/integration_cache_control.rs b/crates/headroom-proxy/tests/integration_cache_control.rsnew file mode 100644index 000000000..9fbca217b--- /dev/null+++ b/crates/headroom-proxy/tests/integration_cache_control.rs@@ -0,0 +1,252 @@+//! Integration tests for the proxy-side cache_control resolver+//! (PR-A4).+//!+//! The core walker `headroom_core::compute_frozen_count` is unit-+//! tested in `crates/headroom-core/tests/cache_control.rs`. This file+//! exercises the proxy wrapper [`resolve_frozen_count`] which adds+//! the configurability gate (`HEADROOM_PROXY_CACHE_CONTROL_AUTO_FROZEN`)+//! and the structured-log emission tested via in-memory tracing+//! capture.++use headroom_proxy::compression::resolve_frozen_count;+use headroom_proxy::config::CacheControlAutoFrozen;+use serde_json::json;++#[test]+fn cache_control_marker_at_message_3_yields_frozen_count_4() {+ let body = json!({+ "messages": [+ {"role": "user", "content": "first"},+ {"role": "assistant", "content": "second"},+ {"role": "user", "content": "third"},+ {"role": "assistant", "content": [+ {"type": "text", "text": "fourth", "cache_control": {"type": "ephemeral"}},+ ]},+ ],+ });+ assert_eq!(+ resolve_frozen_count(&body, CacheControlAutoFrozen::Enabled, "test-req-1"),+ 4+ );+}++#[test]+fn cache_control_in_system_blocks_does_not_bump_frozen_count() {+ let body = json!({+ "system": [+ {"type": "text", "text": "you are helpful", "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "cite sources", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ],+ "messages": [+ {"role": "user", "content": "hi"},+ ],+ });+ assert_eq!(+ resolve_frozen_count(&body, CacheControlAutoFrozen::Enabled, "test-req-2"),+ 0+ );+}++#[test]+fn cache_control_in_tools_does_not_bump_frozen_count() {+ let body = json!({+ "tools": [+ {"name": "search", "description": "search", "cache_control": {"type": "ephemeral"}},+ ],+ "messages": [+ {"role": "user", "content": "hi"},+ ],+ });+ assert_eq!(+ resolve_frozen_count(&body, CacheControlAutoFrozen::Enabled, "test-req-3"),+ 0+ );+}++#[test]+fn cache_control_ttl_1h_before_5m_passes_no_warn() {+ // Legal ordering: 1h before 5m. Walker returns the right+ // frozen_count and emits no warning. Tracing assertion lives+ // in the dedicated module below.+ let body = json!({+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "first 1h", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ]},+ {"role": "assistant", "content": [+ {"type": "text", "text": "second 5m", "cache_control": {"type": "ephemeral"}},+ ]},+ ],+ });+ assert_eq!(+ resolve_frozen_count(&body, CacheControlAutoFrozen::Enabled, "test-req-4"),+ 2+ );+}++#[test]+fn cache_control_no_markers_yields_zero() {+ let body = json!({+ "model": "claude-3-5-sonnet-20241022",+ "messages": [+ {"role": "user", "content": "no marker"},+ {"role": "assistant", "content": [+ {"type": "text", "text": "still no marker"},+ ]},+ ],+ });+ assert_eq!(+ resolve_frozen_count(&body, CacheControlAutoFrozen::Enabled, "test-req-5"),+ 0+ );+}++#[test]+fn cache_control_multiple_markers_in_messages_returns_max_index() {+ // markers on indices 0, 2, 4 — function returns max(i+1) = 5.+ let body = json!({+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "m0", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "assistant", "content": "m1"},+ {"role": "user", "content": [+ {"type": "text", "text": "m2", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "assistant", "content": "m3"},+ {"role": "user", "content": [+ {"type": "text", "text": "m4", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ]},+ ],+ });+ assert_eq!(+ resolve_frozen_count(&body, CacheControlAutoFrozen::Enabled, "test-req-6"),+ 5+ );+}++#[test]+fn cache_control_disabled_via_config_returns_zero_even_with_markers() {+ // The disabled path returns 0 regardless of marker placement.+ // This is the bypass the operator opts into via+ // `--cache-control-auto-frozen=disabled` /+ // `HEADROOM_PROXY_CACHE_CONTROL_AUTO_FROZEN=disabled`.+ let body = json!({+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "m0", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "assistant", "content": [+ {"type": "text", "text": "m1", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "user", "content": [+ {"type": "text", "text": "m2", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ]},+ ],+ });+ assert_eq!(+ resolve_frozen_count(&body, CacheControlAutoFrozen::Disabled, "test-req-7"),+ 0,+ "disabled policy must override marker presence"+ );+ // Sanity: with the same body, enabled returns the full 3.+ assert_eq!(+ resolve_frozen_count(&body, CacheControlAutoFrozen::Enabled, "test-req-7b"),+ 3+ );+}++/// TTL-ordering warning path: capture tracing output and assert the+/// 5m-before-1h scenario emits a `warn!` log line.+///+/// The capture installs a global tracing subscriber, so we keep it+/// in its own module and run only one capture-driven test per binary+/// to avoid double-registration races with other integration tests+/// (mirrors the pattern in `integration_compression.rs`).+mod tracing_capture {+ use super::*;+ use std::sync::Arc;+ use std::sync::Mutex as StdMutex;+ use std::sync::OnceLock;+ use tracing_subscriber::fmt::MakeWriter;++ #[derive(Clone)]+ struct CaptureWriter {+ inner: Arc<StdMutex<Vec<u8>>>,+ }++ impl std::io::Write for CaptureWriter {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ self.inner.lock().unwrap().extend_from_slice(buf);+ Ok(buf.len())+ }+ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+ }++ impl<'a> MakeWriter<'a> for CaptureWriter {+ type Writer = Self;+ fn make_writer(&'a self) -> Self::Writer {+ self.clone()+ }+ }++ fn buffer() -> &'static Arc<StdMutex<Vec<u8>>> {+ static BUFFER: OnceLock<Arc<StdMutex<Vec<u8>>>> = OnceLock::new();+ BUFFER.get_or_init(|| {+ let buf = Arc::new(StdMutex::new(Vec::new()));+ let writer = CaptureWriter { inner: buf.clone() };+ let subscriber = tracing_subscriber::fmt()+ .json()+ .with_writer(writer)+ // WARN level is enough — we capture warn! and+ // implicitly higher; debug! lines are excluded so+ // the buffer stays small.+ .with_max_level(tracing::Level::WARN)+ .finish();+ // try_init returns Err if a global subscriber already+ // exists. Other test binaries in this crate also install+ // one — that's fine; we just need *some* subscriber to+ // be active for our `tracing::warn!` to be observable.+ let _ = tracing::subscriber::set_global_default(subscriber);+ buf+ })+ }++ #[test]+ fn cache_control_ttl_5m_before_1h_warns_and_passes() {+ let buf = buffer();+ buf.lock().unwrap().clear();++ // 5m marker on message 0, then 1h marker on message 1 —+ // violation per guide §2.19. Walker must:+ // 1. return the correct floor (= 2);+ // 2. emit a `warn!` so the operator can see the issue.+ let body = json!({+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "first 5m", "cache_control": {"type": "ephemeral"}},+ ]},+ {"role": "assistant", "content": [+ {"type": "text", "text": "second 1h", "cache_control": {"type": "ephemeral", "ttl": "1h"}},+ ]},+ ],+ });+ let count = resolve_frozen_count(&body, CacheControlAutoFrozen::Enabled, "test-req-warn");+ assert_eq!(count, 2, "function must compute correct floor regardless");++ let logs = String::from_utf8(buf.lock().unwrap().clone()).expect("logs are utf-8");+ // The warning must be present. We check for the rule+ // identifier rather than the exact prose so future copy+ // edits don't break the test.+ assert!(+ logs.contains("anthropic_prompt_caching_guide_2_19"),+ "TTL ordering warn log missing; logs: {logs}",+ );+ assert!(+ logs.contains(r#""field":"messages""#),+ "warn log missing field=messages; logs: {logs}",+ );+ }+}