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: PR-E3 Anthropic cache_control auto-placement (Phase E)
chopratejas8672d5c32680
diff --git a/crates/headroom-proxy/src/bedrock/invoke.rs b/crates/headroom-proxy/src/bedrock/invoke.rsindex 9af7baff0..c503de4e8 100644--- a/crates/headroom-proxy/src/bedrock/invoke.rs+++ b/crates/headroom-proxy/src/bedrock/invoke.rs@@ -377,10 +377,17 @@ fn run_anthropic_compression(body: &Bytes, state: &AppState, request_id: &str) -"bedrock invoke: envelope validated; dispatching to live-zone compressor");+ // PR-E3: Bedrock uses IAM-signed AWS SigV4 downstream. Inbound+ // requests to the proxy may or may not carry their own auth, but+ // Bedrock itself is a subscription/IAM channel — never PAYG —+ // so we hard-code `RequestAuthMode::OAuth` to skip E3+ // cache_control auto-placement. This keeps the Bedrock byte+ // contract stable; live-zone compression continues to run.let outcome = compress_anthropic_request(body,state.config.compression_mode,state.config.cache_control_auto_frozen,+ headroom_core::auth_mode::AuthMode::OAuth,request_id,);match outcome {diff --git a/crates/headroom-proxy/src/bedrock/invoke_streaming.rs b/crates/headroom-proxy/src/bedrock/invoke_streaming.rsindex 27dff6062..d816cc84a 100644--- a/crates/headroom-proxy/src/bedrock/invoke_streaming.rs+++ b/crates/headroom-proxy/src/bedrock/invoke_streaming.rs@@ -841,10 +841,13 @@ fn run_anthropic_compression(body: &Bytes, state: &AppState, request_id: &str) -return body.clone();}+ // PR-E3: Bedrock channel hard-codes OAuth so cache_control+ // auto-placement is skipped (see invoke.rs for rationale).let outcome = compress_anthropic_request(body,state.config.compression_mode,state.config.cache_control_auto_frozen,+ headroom_core::auth_mode::AuthMode::OAuth,request_id,);match outcome {diff --git a/crates/headroom-proxy/src/cache_stabilization/anthropic_cache_control.rs b/crates/headroom-proxy/src/cache_stabilization/anthropic_cache_control.rsnew file mode 100644index 000000000..22430dc97--- /dev/null+++ b/crates/headroom-proxy/src/cache_stabilization/anthropic_cache_control.rs@@ -0,0 +1,698 @@+//! PR-E3: Anthropic `cache_control` auto-placement.+//!+//! Anthropic's prompt cache is opt-in per content block: nothing is+//! cached unless the request body explicitly carries+//! `cache_control: {"type": "ephemeral"}` on at least one block.+//! Sophisticated clients (e.g. Claude Code) place those markers+//! themselves; less-sophisticated callers (hand-rolled SDK code,+//! smaller agents like Aider/Continue, plain `curl`) typically don't+//! even know `cache_control` exists. For *those* clients we can+//! get them cache hits at zero learning-cost by inserting one+//! marker on the highest-reuse content block in the request.+//!+//! # Safety contract+//!+//! This module is the only Phase E surface that **mutates request+//! bytes** — that's the whole point. To stay inside the Phase A+//! "passthrough is sacred" invariant we layer three independent+//! gates:+//!+//! 1. **Auth-mode gate (caller's responsibility).** Mutating bytes+//! on an OAuth-bearing or subscription-bound request risks+//! looking like cache-evasion to the upstream and can trigger+//! subscription revocation. The caller MUST classify the+//! inbound auth mode via [`headroom_core::auth_mode::classify`]+//! and only call this function when the mode is+//! [`headroom_core::auth_mode::AuthMode::Payg`]. The caller+//! emits a structured `event = "e3_skipped", reason =+//! "auth_mode"` log line on the non-PAYG path.+//! 2. **Customer-placement-wins gate.** If *any* `cache_control`+//! marker is found anywhere in the body the caller hands us we+//! return [`AutoPlaceOutcome::Skipped { reason:+//! SkipReason::MarkerPresent }`] and never mutate. This walks+//! `system` (string OR array of blocks), `messages[].content`+//! (string OR array of blocks), and `tools[]` (top-level on+//! each tool). The customer's cache layout is theirs to own.+//! 3. **Idempotency.** Re-running on a body that already carries+//! the markers we'd add is a no-op via gate (2) — the+//! previously-placed marker becomes the customer-placement-wins+//! signal on the next pass.+//!+//! Every skip / apply emits a structured `tracing::info!` with+//! `event = "e3_skipped"` or `event = "e3_applied"` so production+//! telemetry can confirm the gates fire as designed.+//!+//! # Placement strategy (first ship: ONE marker only)+//!+//! Anthropic's `cache_control` semantics: a marker on a block caches+//! *that block + everything before it* in the canonical request+//! order (`system → tools → messages`). Each cached prefix lasts+//! 5 minutes. A request may carry up to **4** markers (Anthropic's+//! hard limit).+//!+//! Future placement priority (not yet enabled — requires production+//! telemetry to validate before we mutate further bytes per request):+//!+//! 1. **Last tool definition (top-level).** Caches the entire+//! `tools` array — highest reuse across turns.+//! 2. **Last block of the system prompt.** Caches `system + tools`.+//! Only fires when `system` is already an array of blocks; we+//! do **not** convert a plain-string `system` to an array on+//! first ship — that's a bigger surgery and we'd want telemetry+//! first.+//! 3. **Last user message's last block** when the conversation+//! already has ≥ 2 turns of history (caches everything except+//! the live tool_result tail).+//! 4. Fourth slot reserved — left unplaced for safety.+//!+//! **First ship default:** place exactly one marker on the last tool+//! definition's top-level. Highest-value, lowest-risk, easiest to+//! revert. Slots 2/3/4 require production telemetry to enable.+//!+//! # Marker shape+//!+//! ```json+//! {"cache_control": {"type": "ephemeral"}}+//! ```+//!+//! No TTL field — the 5-minute default is the right one for the+//! first-ship "last tool" placement (tools rarely turn over within+//! 5 minutes; longer TTLs require careful auth-mode and per-tenant+//! sizing we don't yet have).++use serde_json::{json, Value};++/// Result of an auto-placement attempt.+///+/// Returned by [`auto_place_anthropic_cache_control`]. The caller+/// uses the variant + count to emit structured telemetry. Variants+/// stay narrow — one happy path with a count, one skip with a+/// machine-readable reason.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum AutoPlaceOutcome {+ /// At least one `cache_control` marker was inserted. `placed_count`+ /// is the number of markers added in this call. With the+ /// first-ship policy this is always `1` when the body has tools+ /// and `0` when it doesn't (the latter still returns `Applied`+ /// with `placed_count = 0` so the caller can log the+ /// "we-tried-but-no-target" branch).+ Applied {+ /// Number of markers added on this call.+ placed_count: usize,+ /// JSON-pointer-style locations the markers were placed at.+ /// Stable identifiers used by dashboards to spot which slots+ /// fire most. Example: `"tools[3]"`.+ locations: Vec<String>,+ },+ /// We did not mutate. `reason` tells dashboards which gate fired.+ Skipped {+ /// Why we skipped — see [`SkipReason`] for the closed set.+ reason: SkipReason,+ },+}++/// Why E3 declined to place a marker.+///+/// Closed enum so the structured `event = "e3_skipped"` log carries+/// a stable `reason` field. Dashboards filter on these strings.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SkipReason {+ /// Caller's auth-mode gate fired — request was not classified as+ /// PAYG, so the safety contract bans mutation. The caller is the+ /// one who detects this; surfaced here so the function's outcome+ /// shape stays uniform across both gates.+ AuthMode,+ /// At least one `cache_control` marker was already present in the+ /// body (`system`, any message block, any tool top-level).+ /// Customer placement wins.+ MarkerPresent,+}++impl SkipReason {+ /// Stable string for structured-log `reason` field. Dashboards+ /// filter on these — do not change without a deprecation note.+ pub fn as_str(self) -> &'static str {+ match self {+ SkipReason::AuthMode => "auth_mode",+ SkipReason::MarkerPresent => "marker_present",+ }+ }+}++/// Walk `body` and return `true` if any `cache_control` field appears+/// anywhere. Public so the caller can early-skip without going through+/// the full mutating path (e.g. when it wants to log a different+/// `reason` field on its own gate).+///+/// The walker inspects the three places Anthropic's request schema+/// allows `cache_control`:+///+/// - `body.system` — when it's an array of content blocks (string+/// form cannot carry a marker).+/// - `body.messages[].content` — when it's an array of blocks.+/// - `body.tools[]` — top-level on each tool definition.+///+/// We do **not** descend into arbitrary nested objects. The only+/// shape Anthropic recognises `cache_control` on is the documented+/// surface above; descending into tool `input_schema` etc. would+/// false-positive on customer JSON Schemas that happen to mention+/// the field name as a property key.+pub fn any_anthropic_cache_control(body: &Value) -> bool {+ // ── system: string OR array of blocks ─────────────────────────+ // Only the array form can carry markers — string form is+ // explicitly skipped (cannot carry a `cache_control` field).+ if let Some(Value::Array(blocks)) = body.get("system") {+ for block in blocks {+ if block_has_cache_control(block) {+ return true;+ }+ }+ }++ // ── messages[].content: string OR array of blocks ─────────────+ if let Some(Value::Array(messages)) = body.get("messages") {+ for msg in messages {+ if let Some(Value::Array(blocks)) = msg.get("content") {+ for block in blocks {+ if block_has_cache_control(block) {+ return true;+ }+ }+ }+ // string form: cannot carry a marker — skip.+ }+ }++ // ── tools[]: top-level field on each tool ─────────────────────+ if let Some(Value::Array(tools)) = body.get("tools") {+ for tool in tools {+ if block_has_cache_control(tool) {+ return true;+ }+ }+ }++ false+}++/// Auto-place up to one Anthropic `cache_control` marker on the+/// last tool definition.+///+/// **Caller contract:** caller MUST gate on auth_mode == PAYG before+/// invoking. This function does NOT classify auth mode itself; the+/// split lets unit tests exercise marker detection without+/// constructing a real `HeaderMap`.+///+/// **Behaviour:**+///+/// - If any `cache_control` marker is already present anywhere in+/// the body (`system` blocks, message blocks, or top-level on any+/// tool), returns [`AutoPlaceOutcome::Skipped { reason:+/// SkipReason::MarkerPresent }`] and does not mutate.+/// - If `body.tools[]` is missing, empty, or not an array, returns+/// [`AutoPlaceOutcome::Applied { placed_count: 0, locations: vec![] }`]+/// and does not mutate. (Distinguishes "we ran and found nothing+/// to do" from "we declined to run".)+/// - Otherwise, inserts a `cache_control: {"type": "ephemeral"}` field+/// on the last tool definition (top-level) and returns+/// [`AutoPlaceOutcome::Applied { placed_count: 1, locations: ["tools[N-1]"] }`].+///+/// **Idempotency:** running this twice on the same body is a no-op.+/// The first call inserts the marker; the second call sees it via+/// the customer-placement-wins gate and returns `Skipped`.+///+/// **First-ship scope:** only the "last tool" slot is enabled. The+/// system-prompt and message-history slots are documented in the+/// module-level docs but require production telemetry to enable.+pub fn auto_place_anthropic_cache_control(body: &mut Value) -> AutoPlaceOutcome {+ // Gate 2: any pre-existing marker → customer wins, full skip.+ if any_anthropic_cache_control(body) {+ return AutoPlaceOutcome::Skipped {+ reason: SkipReason::MarkerPresent,+ };+ }++ // First-ship default: place ONE marker on the last tool.+ let tools = match body.get_mut("tools") {+ Some(Value::Array(t)) if !t.is_empty() => t,+ _ => {+ // No tools array, or empty, or not an array. We "ran"+ // but had no target — return Applied{0} so the caller+ // can log "no_targets_present" for telemetry.+ return AutoPlaceOutcome::Applied {+ placed_count: 0,+ locations: Vec::new(),+ };+ }+ };+ let last_idx = tools.len() - 1;+ let last_tool = &mut tools[last_idx];+ if !insert_cache_control_on_object(last_tool) {+ // The last "tool" is not an object (Anthropic's schema+ // requires it to be — but we never panic on a malformed+ // body). Skip the slot rather than crashing.+ return AutoPlaceOutcome::Applied {+ placed_count: 0,+ locations: Vec::new(),+ };+ }+ AutoPlaceOutcome::Applied {+ placed_count: 1,+ locations: vec![format!("tools[{last_idx}]")],+ }+}++/// Does this content block carry a `cache_control` field at its top+/// level? Used by both the read-only walker+/// ([`any_anthropic_cache_control`]) and (transitively) the+/// idempotency gate.+fn block_has_cache_control(block: &Value) -> bool {+ block.get("cache_control").is_some()+}++/// Insert `"cache_control": {"type": "ephemeral"}` on `value` if it+/// is a JSON object. Returns `true` on insert, `false` if `value`+/// was not an object (so the caller can decline to claim a slot).+fn insert_cache_control_on_object(value: &mut Value) -> bool {+ match value.as_object_mut() {+ Some(map) => {+ map.insert("cache_control".to_string(), json!({"type": "ephemeral"}));+ true+ }+ None => false,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ /// Fresh body with one tool, one short user message, plain-string+ /// system. Used as the seed for "happy-path placement" tests.+ fn body_one_tool_no_markers() -> Value {+ json!({+ "model": "claude-3-5-sonnet-20241022",+ "system": "You are helpful.",+ "tools": [+ {+ "name": "search",+ "description": "search the web",+ "input_schema": {"type": "object", "properties": {}}+ }+ ],+ "messages": [+ {"role": "user", "content": "hi"}+ ],+ })+ }++ #[test]+ fn places_cache_control_on_last_tool_when_payg_and_no_markers() {+ let mut body = body_one_tool_no_markers();+ let outcome = auto_place_anthropic_cache_control(&mut body);+ match outcome {+ AutoPlaceOutcome::Applied {+ placed_count,+ locations,+ } => {+ assert_eq!(placed_count, 1);+ assert_eq!(locations, vec!["tools[0]"]);+ }+ other => panic!("expected Applied{{1}}, got {other:?}"),+ }+ // Marker visible at the right path.+ let cc = body+ .pointer("/tools/0/cache_control")+ .expect("marker inserted on tools[0]");+ assert_eq!(cc, &json!({"type": "ephemeral"}));+ }++ #[test]+ fn places_on_last_tool_when_multiple_tools() {+ // With multiple tools, the marker must go on the last one.+ let mut body = json!({+ "tools": [+ {"name": "a", "description": "a"},+ {"name": "b", "description": "b"},+ {"name": "c", "description": "c"}+ ],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let outcome = auto_place_anthropic_cache_control(&mut body);+ match outcome {+ AutoPlaceOutcome::Applied {+ placed_count,+ locations,+ } => {+ assert_eq!(placed_count, 1);+ assert_eq!(locations, vec!["tools[2]"]);+ }+ other => panic!("expected Applied{{1}}, got {other:?}"),+ }+ assert!(body.pointer("/tools/0/cache_control").is_none());+ assert!(body.pointer("/tools/1/cache_control").is_none());+ assert!(body.pointer("/tools/2/cache_control").is_some());+ }++ #[test]+ fn skips_when_any_tool_already_has_marker() {+ // Customer placed a marker on the FIRST tool (not the slot+ // we'd pick). Customer-placement-wins still skips us.+ let mut body = json!({+ "tools": [+ {+ "name": "search",+ "description": "search",+ "cache_control": {"type": "ephemeral"}+ },+ {"name": "fetch", "description": "fetch"}+ ],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let before = body.clone();+ let outcome = auto_place_anthropic_cache_control(&mut body);+ assert_eq!(+ outcome,+ AutoPlaceOutcome::Skipped {+ reason: SkipReason::MarkerPresent+ }+ );+ assert_eq!(body, before, "skip path must not mutate");+ }++ #[test]+ fn skips_when_system_block_already_has_marker() {+ // Customer used the array-form `system` and placed their own+ // marker. Customer-placement-wins.+ let mut body = json!({+ "system": [+ {"type": "text", "text": "you are helpful"},+ {+ "type": "text",+ "text": "cite sources",+ "cache_control": {"type": "ephemeral"}+ }+ ],+ "tools": [{"name": "search", "description": "search"}],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let before = body.clone();+ let outcome = auto_place_anthropic_cache_control(&mut body);+ assert_eq!(+ outcome,+ AutoPlaceOutcome::Skipped {+ reason: SkipReason::MarkerPresent+ }+ );+ assert_eq!(body, before, "skip path must not mutate");+ }++ #[test]+ fn skips_when_message_block_already_has_marker() {+ // Customer placed a marker mid-conversation. Skip everything.+ let mut body = json!({+ "tools": [{"name": "search", "description": "search"}],+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "remember this",+ "cache_control": {"type": "ephemeral"}+ }+ ]+ },+ {"role": "assistant", "content": "ok"},+ {"role": "user", "content": "now what?"}+ ],+ });+ let before = body.clone();+ let outcome = auto_place_anthropic_cache_control(&mut body);+ assert_eq!(+ outcome,+ AutoPlaceOutcome::Skipped {+ reason: SkipReason::MarkerPresent+ }+ );+ assert_eq!(body, before, "skip path must not mutate");+ }++ #[test]+ fn idempotent_when_we_already_placed_marker_last_run() {+ // Run once: marker placed. Run again: customer-placement-wins+ // gate fires (the marker we placed last time IS now a+ // customer-side marker as far as gate 2 is concerned).+ let mut body = body_one_tool_no_markers();+ let first = auto_place_anthropic_cache_control(&mut body);+ assert!(matches!(+ first,+ AutoPlaceOutcome::Applied {+ placed_count: 1,+ ..+ }+ ));+ let after_first = body.clone();+ let second = auto_place_anthropic_cache_control(&mut body);+ assert_eq!(+ second,+ AutoPlaceOutcome::Skipped {+ reason: SkipReason::MarkerPresent+ }+ );+ assert_eq!(body, after_first, "second run must not mutate");+ }++ #[test]+ fn does_nothing_when_no_tools_present() {+ // Body with no tools field. Returns Applied{0}, no mutation.+ let mut body = json!({+ "model": "claude-3-5-sonnet-20241022",+ "system": "You are helpful.",+ "messages": [{"role": "user", "content": "hi"}],+ });+ let before = body.clone();+ let outcome = auto_place_anthropic_cache_control(&mut body);+ assert_eq!(+ outcome,+ AutoPlaceOutcome::Applied {+ placed_count: 0,+ locations: Vec::new(),+ }+ );+ assert_eq!(body, before, "Applied{{0}} path must not mutate");+ }++ #[test]+ fn does_nothing_when_tools_array_is_empty() {+ let mut body = json!({+ "tools": [],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let before = body.clone();+ let outcome = auto_place_anthropic_cache_control(&mut body);+ assert_eq!(+ outcome,+ AutoPlaceOutcome::Applied {+ placed_count: 0,+ locations: Vec::new(),+ }+ );+ assert_eq!(body, before, "empty-tools path must not mutate");+ }++ #[test]+ fn system_string_form_does_not_get_converted_to_array() {+ // Conservative first-ship policy: a plain-string `system`+ // stays a plain string. We only place on tools.+ let mut body = json!({+ "system": "You are helpful. Cite sources.",+ "tools": [{"name": "search", "description": "search"}],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let outcome = auto_place_anthropic_cache_control(&mut body);+ assert!(matches!(+ outcome,+ AutoPlaceOutcome::Applied {+ placed_count: 1,+ ..+ }+ ));+ // System is still a plain string.+ assert_eq!(+ body.get("system"),+ Some(&json!("You are helpful. Cite sources.")),+ "string-form `system` must stay untouched on first ship",+ );+ // Marker landed on tools[0] instead.+ assert_eq!(+ body.pointer("/tools/0/cache_control"),+ Some(&json!({"type": "ephemeral"})),+ );+ }++ #[test]+ fn applies_only_one_marker_in_first_ship_default() {+ // Multi-turn conversation + multiple tools + array-form system.+ // First-ship default places exactly ONE marker (last tool).+ let mut body = json!({+ "system": [+ {"type": "text", "text": "rule 1"},+ {"type": "text", "text": "rule 2"}+ ],+ "tools": [+ {"name": "a", "description": "a"},+ {"name": "b", "description": "b"}+ ],+ "messages": [+ {"role": "user", "content": "first"},+ {"role": "assistant", "content": "second"},+ {"role": "user", "content": "third"},+ {"role": "assistant", "content": "fourth"},+ {"role": "user", "content": "fifth"}+ ],+ });+ let outcome = auto_place_anthropic_cache_control(&mut body);+ assert_eq!(+ outcome,+ AutoPlaceOutcome::Applied {+ placed_count: 1,+ locations: vec!["tools[1]".to_string()],+ }+ );+ // Walk every other slot to confirm it stayed clean.+ let system_blocks = body.pointer("/system").unwrap().as_array().unwrap();+ for block in system_blocks {+ assert!(+ !block_has_cache_control(block),+ "first-ship default must not place on system blocks: {block:?}"+ );+ }+ for (i, msg) in body+ .pointer("/messages")+ .unwrap()+ .as_array()+ .unwrap()+ .iter()+ .enumerate()+ {+ // Messages with string-form content can't carry markers+ // anyway, but assert no marker placed regardless.+ if let Some(Value::Array(blocks)) = msg.get("content") {+ for block in blocks {+ assert!(+ !block_has_cache_control(block),+ "message[{i}] block carries unexpected marker: {block:?}"+ );+ }+ }+ }+ // Only tools[1] carries a marker.+ assert!(body.pointer("/tools/0/cache_control").is_none());+ assert_eq!(+ body.pointer("/tools/1/cache_control"),+ Some(&json!({"type": "ephemeral"})),+ );+ }++ #[test]+ fn applied_path_preserves_other_tool_fields() {+ // Property: post-placement body matches input body modulo+ // the `tools[last].cache_control` key. Sort-stable, no+ // collateral mutation elsewhere.+ let original = body_one_tool_no_markers();+ let mut body = original.clone();+ let _ = auto_place_anthropic_cache_control(&mut body);++ // Strip the marker we placed and compare to the original.+ let tools = body+ .get_mut("tools")+ .and_then(Value::as_array_mut)+ .expect("tools array");+ for tool in tools {+ if let Some(map) = tool.as_object_mut() {+ map.remove("cache_control");+ }+ }+ assert_eq!(+ body, original,+ "Applied path must mutate ONLY the cache_control field on the chosen slot",+ );+ }++ #[test]+ fn skip_reason_strings_are_stable() {+ // Dashboards filter on these strings. Pin them.+ assert_eq!(SkipReason::AuthMode.as_str(), "auth_mode");+ assert_eq!(SkipReason::MarkerPresent.as_str(), "marker_present");+ }++ #[test]+ fn any_marker_walker_scans_system_array_form_only() {+ // String-form `system` cannot carry a marker — walker should+ // not flag it even when the string contains the substring+ // "cache_control".+ let body = json!({+ "system": "Note: cache_control is an Anthropic concept.",+ "messages": [],+ });+ assert!(!any_anthropic_cache_control(&body));++ // Array-form `system` with a marker — walker DOES flag it.+ let body_with_marker = json!({+ "system": [+ {"type": "text", "text": "x", "cache_control": {"type": "ephemeral"}}+ ],+ "messages": [],+ });+ assert!(any_anthropic_cache_control(&body_with_marker));+ }++ #[test]+ fn any_marker_walker_does_not_descend_into_input_schema() {+ // Customer's tool input_schema happens to declare a property+ // literally named `cache_control`. That's NOT a real Anthropic+ // marker — it's a JSON Schema property name. Walker must NOT+ // false-positive.+ let body = json!({+ "tools": [{+ "name": "configure",+ "description": "configure something",+ "input_schema": {+ "type": "object",+ "properties": {+ "cache_control": {"type": "string"}+ }+ }+ }],+ "messages": [{"role": "user", "content": "hi"}],+ });+ assert!(+ !any_anthropic_cache_control(&body),+ "walker must scope to documented Anthropic surfaces; \+ schema property keys do not count as markers",+ );+ }++ #[test]+ fn malformed_tool_entry_does_not_panic() {+ // Defensive: an Anthropic request with a non-object tool would+ // get a 400 from upstream, but we never panic on a malformed+ // body. Skip the slot instead.+ let mut body = json!({+ "tools": ["not-an-object"],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let before = body.clone();+ let outcome = auto_place_anthropic_cache_control(&mut body);+ assert_eq!(+ outcome,+ AutoPlaceOutcome::Applied {+ placed_count: 0,+ locations: Vec::new(),+ }+ );+ assert_eq!(body, before, "malformed-tool path must not mutate");+ }+}diff --git a/crates/headroom-proxy/src/cache_stabilization/mod.rs b/crates/headroom-proxy/src/cache_stabilization/mod.rsindex f894c89b9..cbf17df17 100644--- a/crates/headroom-proxy/src/cache_stabilization/mod.rs+++ b/crates/headroom-proxy/src/cache_stabilization/mod.rs@@ -20,6 +20,14 @@//! `cache_drift_first_request` on first sight and//! `cache_drift_observed` when consecutive requests on the same//! session disagree on any of the three dimensions.+//! - [`anthropic_cache_control`] — PR-E3: on PAYG-classified+//! requests where the customer hasn't placed any `cache_control`+//! marker, auto-inserts one ephemeral marker on the last tool+//! definition so unsophisticated callers (hand-rolled SDK code,+//! smaller agents, plain `curl`) get prompt-cache hits without+//! learning Anthropic's marker API. **Mutates request bytes**;+//! gated on auth_mode == PAYG and the absence of any pre-existing+//! marker.//!//! Future PRs (E1 — tool-array sort, E2 — JSON Schema key sort, E3 —//! `cache_control` auto-placement, E4 — `prompt_cache_key` injection)@@ -28,5 +36,6 @@//! each detector lives in its own file, the only shared surface is//! this `mod.rs`'s `pub mod` list.+pub mod anthropic_cache_control;pub mod drift_detector;pub mod volatile_detector;diff --git a/crates/headroom-proxy/src/compression/live_zone_anthropic.rs b/crates/headroom-proxy/src/compression/live_zone_anthropic.rsindex 7c4cb5597..c33c41ce5 100644--- a/crates/headroom-proxy/src/compression/live_zone_anthropic.rs+++ b/crates/headroom-proxy/src/compression/live_zone_anthropic.rs@@ -39,12 +39,16 @@//! SHA-256 prefix-and-suffix invariant in CI.use bytes::Bytes;+use headroom_core::auth_mode::AuthMode as RequestAuthMode;use headroom_core::transforms::live_zone::DEFAULT_MODEL;use headroom_core::transforms::{compress_anthropic_live_zone, AuthMode, BlockAction, ExclusionReason, LiveZoneError,LiveZoneOutcome,};+use crate::cache_stabilization::anthropic_cache_control::{+ auto_place_anthropic_cache_control, AutoPlaceOutcome, SkipReason,+};use crate::compression::resolve_frozen_count;use crate::config::{CacheControlAutoFrozen, CompressionMode};@@ -107,11 +111,19 @@ pub enum PassthroughReason {/// `frozen_message_count` from explicit `cache_control` markers/// in the body. Disabled → floor=0 (everything is in the live/// zone).+/// - `auth_mode`: F1's [`RequestAuthMode`] classification of the+/// inbound request. PR-E3 gates `cache_control` auto-placement+/// on `Payg` only — OAuth and Subscription modes pass through+/// byte-equal (mutating their bytes risks looking like+/// cache-evasion to the upstream). The live-zone dispatcher+/// itself still runs on every mode in PR-B/C; the auth-mode+/// gate is local to PR-E3./// - `request_id`: per-request id used for log correlation.pub fn compress_anthropic_request(body: &Bytes,mode: CompressionMode,cache_control_policy: CacheControlAutoFrozen,+ auth_mode: RequestAuthMode,request_id: &str,) -> Outcome {if matches!(mode, CompressionMode::Off) {@@ -133,7 +145,7 @@ pub fn compress_anthropic_request(// Mode is LiveZone. Resolve the cache-hot floor first; this is// the only place the body is parsed at all when the policy is// Disabled (resolve_frozen_count short-circuits).- let parsed: serde_json::Value = match serde_json::from_slice(body) {+ let mut parsed: serde_json::Value = match serde_json::from_slice(body) {Ok(v) => v,Err(_) => {tracing::warn!(@@ -154,6 +166,114 @@ pub fn compress_anthropic_request(let frozen_count = resolve_frozen_count(&parsed, cache_control_policy, request_id);+ // ── PR-E3: Anthropic cache_control auto-placement ─────────────+ //+ // Gate 1 (auth-mode): only PAYG. Mutating bytes on OAuth /+ // subscription would look like cache-evasion to the upstream.+ // Gate 2 (customer-placement-wins): handled inside+ // `auto_place_anthropic_cache_control` — if any marker exists+ // anywhere in the body we return Skipped { MarkerPresent }.+ //+ // When Applied, we re-serialize the parsed body and use the+ // new bytes for the rest of the pipeline. The live-zone+ // dispatcher will re-parse internally — this costs one extra+ // serialize on the (rare) Applied path; on the Skipped /+ // non-PAYG paths we don't touch the bytes at all.+ let mut e3_body_bytes: Option<Bytes> = None;+ let mut e3_locations: Vec<String> = Vec::new();+ let e3_skipped: bool;+ if matches!(auth_mode, RequestAuthMode::Payg) {+ match auto_place_anthropic_cache_control(&mut parsed) {+ AutoPlaceOutcome::Applied {+ placed_count,+ locations,+ } => {+ e3_skipped = false;+ if placed_count > 0 {+ match serde_json::to_vec(&parsed) {+ Ok(v) => {+ tracing::info!(+ event = "e3_applied",+ request_id = %request_id,+ path = "/v1/messages",+ placed_count = placed_count,+ locations = ?locations,+ "auto-placed anthropic cache_control marker(s)"+ );+ e3_body_bytes = Some(Bytes::from(v));+ e3_locations = locations;+ }+ Err(err) => {+ // We just parsed successfully; serialize+ // failure is unreachable in practice. If+ // it ever fires, fall back to the+ // original body bytes — never poison the+ // request. Loud log so operators notice.+ tracing::error!(+ event = "e3_serialize_failed",+ request_id = %request_id,+ path = "/v1/messages",+ error = %err,+ "auto-placement mutated parsed body but \+ serialize-back failed; forwarding original bytes"+ );+ }+ }+ } else {+ // Applied with placed_count = 0 means "ran but+ // nothing to do" (no tools array, empty array,+ // or the last tool wasn't an object). Emit a+ // distinct event so dashboards can spot the+ // we-tried-but-no-target branch.+ tracing::info!(+ event = "e3_no_target",+ request_id = %request_id,+ path = "/v1/messages",+ "auto-placement ran but found no tool slot to mark"+ );+ }+ }+ AutoPlaceOutcome::Skipped {+ reason: SkipReason::MarkerPresent,+ } => {+ e3_skipped = true;+ tracing::info!(+ event = "e3_skipped",+ request_id = %request_id,+ path = "/v1/messages",+ reason = SkipReason::MarkerPresent.as_str(),+ "customer-placed cache_control marker(s) present; auto-placement skipped"+ );+ }+ AutoPlaceOutcome::Skipped {+ reason: SkipReason::AuthMode,+ } => {+ // The function never returns AuthMode itself — that+ // gate lives in this caller. Defensive arm so the+ // match is exhaustive across the public enum.+ e3_skipped = true;+ }+ }+ } else {+ e3_skipped = true;+ tracing::info!(+ event = "e3_skipped",+ request_id = %request_id,+ path = "/v1/messages",+ reason = SkipReason::AuthMode.as_str(),+ auth_mode = auth_mode.as_str(),+ "non-PAYG auth mode; cache_control auto-placement skipped"+ );+ }+ // Suppress dead-code warnings on the local; we keep the variable+ // so future telemetry can surface the OAuth/Subscription pass+ // counts without re-deriving them.+ let _ = e3_skipped;++ // For the rest of the pipeline, use the E3-modified bytes when+ // E3 applied, else the original buffer.+ let working_body: Bytes = e3_body_bytes.clone().unwrap_or_else(|| body.clone());+// PR-B4: extract `body["model"]` so the live-zone dispatcher can// route the tokenizer registry to the right backend for the// per-block token-count rejection gate. Anthropic@@ -175,7 +295,7 @@ pub fn compress_anthropic_request(// `NoChange` otherwise (live zone empty, every compressor// declined, or every compressor produced output whose token// count was not strictly less than the input's).- match compress_anthropic_live_zone(body, frozen_count, AuthMode::Payg, model) {+ match compress_anthropic_live_zone(&working_body, frozen_count, AuthMode::Payg, model) {Ok(LiveZoneOutcome::NoChange { manifest }) => {let block_count = manifest.block_outcomes.len();let blocks_excluded = manifest@@ -205,7 +325,23 @@ pub fn compress_anthropic_request(live_zone_blocks_excluded = blocks_excluded,"anthropic live-zone dispatch");- Outcome::NoCompression+ // If E3 applied, we still need to forward the modified+ // bytes even though the live-zone dispatcher made no+ // additional changes. Translate to `Compressed` so the+ // proxy substitutes the body — `tokens_*` are zero+ // because no token-bearing block was rewritten;+ // `markers_inserted` carries the E3 placement locations.+ if let Some(new_body) = e3_body_bytes {+ Outcome::Compressed {+ body: new_body,+ tokens_before: 0,+ tokens_after: 0,+ strategies_applied: vec!["e3_anthropic_cache_control"],+ markers_inserted: e3_locations,+ }+ } else {+ Outcome::NoCompression+ }}Ok(LiveZoneOutcome::Modified { new_body, manifest }) => {// Aggregate manifest into the proxy's `Compressed` payload.@@ -320,6 +456,7 @@ mod tests {&body,CompressionMode::Off,CacheControlAutoFrozen::Disabled,+ RequestAuthMode::Payg,"req-1",);match out {@@ -337,6 +474,7 @@ mod tests {&body,CompressionMode::LiveZone,CacheControlAutoFrozen::Enabled,+ RequestAuthMode::Payg,"req-2",);match out {@@ -354,6 +492,7 @@ mod tests {&body,CompressionMode::LiveZone,CacheControlAutoFrozen::Enabled,+ RequestAuthMode::Payg,"req-3",);match out {@@ -379,6 +518,7 @@ mod tests {&body,CompressionMode::LiveZone,CacheControlAutoFrozen::Disabled,+ RequestAuthMode::Payg,"req-4",);match out {@@ -394,6 +534,7 @@ mod tests {&body,CompressionMode::LiveZone,CacheControlAutoFrozen::Enabled,+ RequestAuthMode::Payg,"req-5",);match out {@@ -411,6 +552,11 @@ mod tests {// dispatcher will treat the entire array as live zone.// (PR-B2: still returns NoCompression — this test pins the// policy plumbing rather than compression behaviour.)+ //+ // The body carries a cache_control marker on a message+ // block, so PR-E3's `MarkerPresent` gate also fires —+ // result: still NoCompression (no E3 placement, no+ // live-zone change).let body = body_of(serde_json::json!({"messages": [{@@ -425,6 +571,7 @@ mod tests {&body,CompressionMode::LiveZone,CacheControlAutoFrozen::Disabled,+ RequestAuthMode::Payg,"req-6",);match out {@@ -432,4 +579,138 @@ mod tests {other => panic!("expected NoCompression, got {other:?}"),}}++ #[test]+ fn pr_e3_payg_with_tools_and_no_markers_returns_compressed_with_marker() {+ // PR-E3 happy path: PAYG body with one tool and no markers+ // anywhere → dispatcher inserts a marker on the last tool+ // and returns Compressed with the new bytes.+ let original = serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "tools": [+ {"name": "search", "description": "search the web"}+ ],+ "messages": [+ {"role": "user", "content": "hi"}+ ],+ });+ let body = body_of(original);+ let out = compress_anthropic_request(+ &body,+ CompressionMode::LiveZone,+ CacheControlAutoFrozen::Disabled,+ RequestAuthMode::Payg,+ "req-e3-1",+ );+ match out {+ Outcome::Compressed {+ body: new_body,+ strategies_applied,+ markers_inserted,+ ..+ } => {+ assert_eq!(strategies_applied, vec!["e3_anthropic_cache_control"]);+ assert_eq!(markers_inserted, vec!["tools[0]".to_string()]);+ let parsed: serde_json::Value =+ serde_json::from_slice(&new_body).expect("re-parse new body");+ assert_eq!(+ parsed.pointer("/tools/0/cache_control"),+ Some(&serde_json::json!({"type": "ephemeral"})),+ "marker must be present on last tool",+ );+ }+ other => panic!("expected Compressed{{e3_…}}, got {other:?}"),+ }+ }++ #[test]+ fn pr_e3_oauth_skips_auto_placement() {+ // OAuth → mutating bytes is unsafe → never auto-place. With+ // no other reason for the dispatcher to mutate, we get+ // NoCompression.+ let body = body_of(serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "tools": [{"name": "search", "description": "search"}],+ "messages": [{"role": "user", "content": "hi"}],+ }));+ let out = compress_anthropic_request(+ &body,+ CompressionMode::LiveZone,+ CacheControlAutoFrozen::Disabled,+ RequestAuthMode::OAuth,+ "req-e3-2",+ );+ match out {+ Outcome::NoCompression => {}+ other => panic!("expected NoCompression on OAuth, got {other:?}"),+ }+ }++ #[test]+ fn pr_e3_subscription_skips_auto_placement() {+ let body = body_of(serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "tools": [{"name": "search", "description": "search"}],+ "messages": [{"role": "user", "content": "hi"}],+ }));+ let out = compress_anthropic_request(+ &body,+ CompressionMode::LiveZone,+ CacheControlAutoFrozen::Disabled,+ RequestAuthMode::Subscription,+ "req-e3-3",+ );+ match out {+ Outcome::NoCompression => {}+ other => panic!("expected NoCompression on Subscription, got {other:?}"),+ }+ }++ #[test]+ fn pr_e3_payg_with_existing_marker_skips() {+ // Customer placed a marker on the only tool. Skip E3.+ let body = body_of(serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "tools": [+ {+ "name": "search",+ "description": "search",+ "cache_control": {"type": "ephemeral"}+ }+ ],+ "messages": [{"role": "user", "content": "hi"}],+ }));+ let out = compress_anthropic_request(+ &body,+ CompressionMode::LiveZone,+ CacheControlAutoFrozen::Disabled,+ RequestAuthMode::Payg,+ "req-e3-4",+ );+ match out {+ Outcome::NoCompression => {}+ other => panic!("expected NoCompression on customer-placed marker, got {other:?}"),+ }+ }++ #[test]+ fn pr_e3_payg_no_tools_returns_no_compression() {+ // PAYG, no markers, no tools → E3 has nothing to place.+ // No bytes mutated → NoCompression.+ let body = body_of(serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "messages": [{"role": "user", "content": "hi"}],+ }));+ let out = compress_anthropic_request(+ &body,+ CompressionMode::LiveZone,+ CacheControlAutoFrozen::Disabled,+ RequestAuthMode::Payg,+ "req-e3-5",+ );+ match out {+ Outcome::NoCompression => {}+ other => panic!("expected NoCompression on no-tools PAYG body, got {other:?}"),+ }+ }}diff --git a/crates/headroom-proxy/src/proxy.rs b/crates/headroom-proxy/src/proxy.rsindex 0dce82ecb..bcd62bf58 100644--- a/crates/headroom-proxy/src/proxy.rs+++ b/crates/headroom-proxy/src/proxy.rs@@ -630,10 +630,15 @@ pub(crate) async fn forward_http(}let outcome = match endpoint {compression::CompressibleEndpoint::AnthropicMessages => {+ // PR-E3: thread the F1-classified auth_mode into the+ // dispatcher so cache_control auto-placement gates on+ // PAYG only. Pulled from request extensions where it+ // was stashed at request entry (line ~325 above).compression::compress_anthropic_request(&buffered,state.config.compression_mode,state.config.cache_control_auto_frozen,+ auth_mode,&request_id,)}diff --git a/crates/headroom-proxy/src/vertex/raw_predict.rs b/crates/headroom-proxy/src/vertex/raw_predict.rsindex 6f46a7bfb..b6892a81e 100644--- a/crates/headroom-proxy/src/vertex/raw_predict.rs+++ b/crates/headroom-proxy/src/vertex/raw_predict.rs@@ -220,10 +220,16 @@ pub(crate) async fn forward_vertex_request(// (and any other non-`messages` top-level field) round-trips// byte-equal. Compression off → buffered bytes used unchanged.let body_to_send = if state.config.compression {+ // PR-E3: Vertex uses GCP ADC bearer-token auth downstream, not+ // Anthropic credentials, so the PAYG/OAuth/subscription+ // classification doesn't apply. Hard-code `AuthMode::OAuth` to+ // skip E3 cache_control auto-placement (and any other PAYG-only+ // mutation). Live-zone compression itself continues to run.let outcome = compression::compress_anthropic_request(&buffered,state.config.compression_mode,state.config.cache_control_auto_frozen,+ headroom_core::auth_mode::AuthMode::OAuth,&request_id,);match outcome {diff --git a/crates/headroom-proxy/tests/integration_e3_anthropic_cache_control.rs b/crates/headroom-proxy/tests/integration_e3_anthropic_cache_control.rsnew file mode 100644index 000000000..168e40c12--- /dev/null+++ b/crates/headroom-proxy/tests/integration_e3_anthropic_cache_control.rs@@ -0,0 +1,400 @@+//! Integration tests for PR-E3 Anthropic cache_control auto-placement.+//!+//! Boots a real Rust proxy in front of a wiremock upstream and+//! exercises the three branches of the safety contract:+//!+//! 1. **PAYG body without markers** — proxy auto-places a marker on+//! the last tool, upstream receives the modified body, every+//! other byte is preserved.+//! 2. **PAYG body with a customer-placed marker** — proxy passes+//! through byte-equal (SHA-256 match) and emits an+//! `e3_skipped` event with `reason = "marker_present"`.+//! 3. **Non-PAYG body** (OAuth bearer here) — proxy passes through+//! byte-equal and emits an `e3_skipped` event with `reason =+//! "auth_mode"`.+//!+//! The tracing assertions are scoped to a single test in this binary+//! so we don't fight the global subscriber with other tests in the+//! same crate (mirrors the pattern in `integration_volatile_detector.rs`).++mod common;++use common::start_proxy_with;+use sha2::{Digest, Sha256};+use std::sync::{Arc, Mutex};+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++/// Mount a `/v1/messages` handler that captures the upstream-received+/// request body. Returns a shared handle the test can read after the+/// request lands.+async fn mount_anthropic_capture(upstream: &MockServer) -> Arc<Mutex<Option<Vec<u8>>>> {+ let captured: Arc<Mutex<Option<Vec<u8>>>> = Arc::new(Mutex::new(None));+ let captured_clone = captured.clone();+ Mock::given(method("POST"))+ .and(path("/v1/messages"))+ .respond_with(move |req: &wiremock::Request| {+ *captured_clone.lock().unwrap() = Some(req.body.clone());+ ResponseTemplate::new(200).set_body_string(r#"{"ok":true}"#)+ })+ .mount(upstream)+ .await;+ captured+}++fn sha256_hex(bytes: &[u8]) -> String {+ let mut hasher = Sha256::new();+ hasher.update(bytes);+ let digest = hasher.finalize();+ let mut s = String::with_capacity(digest.len() * 2);+ for b in digest {+ s.push_str(&format!("{b:02x}"));+ }+ s+}++#[tokio::test]+async fn payg_body_without_markers_gets_marker_on_last_tool() {+ let upstream = MockServer::start().await;+ let captured = mount_anthropic_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // Three tools, one short user message, plain-string system. No+ // markers anywhere. Use a PAYG-shaped header (`x-api-key`).+ let payload = serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "max_tokens": 32,+ "system": "You are helpful.",+ "tools": [+ {"name": "alpha", "description": "alpha tool"},+ {"name": "beta", "description": "beta tool"},+ {"name": "gamma", "description": "gamma tool"}+ ],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let body = serde_json::to_vec(&payload).unwrap();++ let resp = reqwest::Client::new()+ .post(format!("{}/v1/messages", proxy.url()))+ .header("content-type", "application/json")+ .header("x-api-key", "sk-ant-api01-fake-key")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let upstream_received = captured+ .lock()+ .unwrap()+ .clone()+ .expect("upstream captured a body");+ let upstream_parsed: serde_json::Value =+ serde_json::from_slice(&upstream_received).expect("upstream body is JSON");++ // Marker landed on the LAST tool only.+ assert_eq!(+ upstream_parsed.pointer("/tools/2/cache_control"),+ Some(&serde_json::json!({"type": "ephemeral"})),+ "expected cache_control on last tool; upstream body: {upstream_parsed}",+ );+ assert!(+ upstream_parsed.pointer("/tools/0/cache_control").is_none(),+ "tools[0] must NOT have cache_control",+ );+ assert!(+ upstream_parsed.pointer("/tools/1/cache_control").is_none(),+ "tools[1] must NOT have cache_control",+ );++ // Every other field is preserved exactly.+ assert_eq!(+ upstream_parsed.get("model"),+ payload.get("model"),+ "model field preserved",+ );+ assert_eq!(+ upstream_parsed.get("system"),+ payload.get("system"),+ "system field preserved",+ );+ assert_eq!(+ upstream_parsed.get("messages"),+ payload.get("messages"),+ "messages field preserved",+ );+ assert_eq!(+ upstream_parsed.pointer("/tools/0/name"),+ payload.pointer("/tools/0/name"),+ );+ assert_eq!(+ upstream_parsed.pointer("/tools/2/name"),+ payload.pointer("/tools/2/name"),+ );++ proxy.shutdown().await;+}++#[tokio::test]+async fn payg_body_with_existing_marker_passes_through_byte_equal() {+ let upstream = MockServer::start().await;+ let captured = mount_anthropic_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // PAYG-shaped headers, but the body already carries a customer+ // cache_control marker on tools[0]. Customer-placement-wins+ // gate fires → proxy passes through byte-equal.+ let payload = serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "max_tokens": 32,+ "tools": [+ {+ "name": "alpha",+ "description": "alpha tool",+ "cache_control": {"type": "ephemeral"}+ },+ {"name": "beta", "description": "beta tool"}+ ],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let body_sha = sha256_hex(&body);++ let resp = reqwest::Client::new()+ .post(format!("{}/v1/messages", proxy.url()))+ .header("content-type", "application/json")+ .header("x-api-key", "sk-ant-api01-fake-key")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let upstream_received = captured+ .lock()+ .unwrap()+ .clone()+ .expect("upstream captured a body");+ let upstream_sha = sha256_hex(&upstream_received);+ assert_eq!(+ upstream_sha, body_sha,+ "byte-equal passthrough required when customer marker present; \+ body sha {body_sha}, upstream sha {upstream_sha}",+ );++ proxy.shutdown().await;+}++#[tokio::test]+async fn oauth_body_passes_through_byte_equal() {+ let upstream = MockServer::start().await;+ let captured = mount_anthropic_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // OAuth-shaped header (`Bearer sk-ant-oat-...`). F1 classifies as+ // OAuth → E3 must skip mutation entirely. The body has no+ // markers, so the customer-placement-wins gate is irrelevant —+ // the auth-mode gate is the load-bearing one for this test.+ let payload = serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "max_tokens": 32,+ "tools": [{"name": "alpha", "description": "alpha tool"}],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let body_sha = sha256_hex(&body);++ let resp = reqwest::Client::new()+ .post(format!("{}/v1/messages", proxy.url()))+ .header("content-type", "application/json")+ .header("authorization", "Bearer sk-ant-oat-fake-oauth-token")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let upstream_received = captured+ .lock()+ .unwrap()+ .clone()+ .expect("upstream captured a body");+ let upstream_sha = sha256_hex(&upstream_received);+ assert_eq!(+ upstream_sha, body_sha,+ "byte-equal passthrough required for non-PAYG (OAuth) requests; \+ body sha {body_sha}, upstream sha {upstream_sha}",+ );++ // Sanity: upstream did NOT receive a marker.+ let upstream_parsed: serde_json::Value =+ serde_json::from_slice(&upstream_received).expect("upstream body is JSON");+ assert!(+ upstream_parsed.pointer("/tools/0/cache_control").is_none(),+ "OAuth path must not insert cache_control; got {upstream_parsed}",+ );++ proxy.shutdown().await;+}++#[tokio::test]+async fn subscription_body_passes_through_byte_equal() {+ let upstream = MockServer::start().await;+ let captured = mount_anthropic_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // Subscription-shaped headers: a Claude Code-like `User-Agent`+ // is enough for F1 to classify as Subscription. E3 must skip+ // mutation.+ let payload = serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "max_tokens": 32,+ "tools": [{"name": "alpha", "description": "alpha tool"}],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let body_sha = sha256_hex(&body);++ let resp = reqwest::Client::new()+ .post(format!("{}/v1/messages", proxy.url()))+ .header("content-type", "application/json")+ .header("user-agent", "claude-code/1.0.0")+ .header("x-api-key", "sk-ant-api01-fake-key")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let upstream_received = captured+ .lock()+ .unwrap()+ .clone()+ .expect("upstream captured a body");+ let upstream_sha = sha256_hex(&upstream_received);+ assert_eq!(+ upstream_sha, body_sha,+ "byte-equal passthrough required for Subscription requests; \+ body sha {body_sha}, upstream sha {upstream_sha}",+ );++ proxy.shutdown().await;+}++/// Tracing-capture test: confirm the `e3_applied` event fires with+/// the expected fields when we auto-place a marker. Lives in its own+/// module to scope the global subscriber installation.+mod tracing_capture {+ use super::*;+ 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)+ // INFO is required — `e3_applied` is logged at INFO.+ .with_max_level(tracing::Level::INFO)+ .finish();+ // Best-effort install: tests in other binaries may have+ // already set a default subscriber. We only need *some*+ // subscriber active for our `tracing::info!` to surface.+ let _ = tracing::subscriber::set_global_default(subscriber);+ buf+ })+ }++ #[tokio::test]+ async fn payg_apply_emits_e3_applied_event() {+ let buf = buffer();+ buf.lock().unwrap().clear();++ let upstream = MockServer::start().await;+ let _captured = mount_anthropic_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ c.log_level = "info".into();+ })+ .await;++ let payload = serde_json::json!({+ "model": "claude-3-5-sonnet-20241022",+ "max_tokens": 32,+ "tools": [{"name": "alpha", "description": "alpha tool"}],+ "messages": [{"role": "user", "content": "hi"}],+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/messages", proxy.url()))+ .header("content-type", "application/json")+ .header("x-api-key", "sk-ant-api01-fake-key")+ .body(body)+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ // Let the async tracing emitter flush.+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;++ let logs = String::from_utf8(buf.lock().unwrap().clone()).expect("logs are utf-8");+ assert!(+ logs.contains("e3_applied"),+ "expected e3_applied event in logs; got: {logs}",+ );+ assert!(+ logs.contains(r#""placed_count":1"#),+ "expected placed_count=1 in logs; got: {logs}",+ );+ assert!(+ logs.contains("tools[0]"),+ "expected location tools[0] in logs; got: {logs}",+ );++ proxy.shutdown().await;+ }+}