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(observability): wire Phase G PR-G3 RTK + proxy metrics (H-blocker)
chopratejas5f264a53292e
diff --git a/crates/headroom-proxy/src/handlers/responses.rs b/crates/headroom-proxy/src/handlers/responses.rsindex a7cc8bfe5..9376c993f 100644--- a/crates/headroom-proxy/src/handlers/responses.rs+++ b/crates/headroom-proxy/src/handlers/responses.rs@@ -65,6 +65,7 @@ use axum::response::Response;use bytes::Bytes;use std::net::SocketAddr;+use crate::observability;use crate::proxy::{forward_http, AppState};/// Axum POST handler for `/v1/responses`. Buffers the body, stitches@@ -111,6 +112,29 @@ pub async fn handle_responses(}}+ // Phase G PR-G3: extract the request-side `service_tier` so we+ // can count tier distribution on the inbound shape too. The+ // response-side tier (from `response.completed`) is captured by+ // the SSE state machine at stream-close; this counter increment+ // pairs them. Body is parsed best-effort; missing/non-JSON+ // bodies do NOT fabricate a tier — per realignment build-+ // constraint "no silent fallbacks", we just skip the emit and+ // log at debug.+ if let Some(tier) = extract_request_service_tier(&body) {+ let request_id_for_metric = headers+ .get("x-request-id")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("<no-request-id>");+ observability::record_service_tier(&tier, request_id_for_metric);+ } else {+ tracing::debug!(+ event = "service_tier_skipped",+ path = %uri.path(),+ reason = "absent_or_unparseable",+ "request body had no parseable service_tier; counter not emitted"+ );+ }+// Reconstruct the Request<Body> shape forward_http expects.let mut builder = Request::builder().method(method).uri(uri);if let Some(hs) = builder.headers_mut() {@@ -140,6 +164,20 @@ pub async fn handle_responses(})}+/// Phase G PR-G3: best-effort parse of `service_tier` from the+/// inbound request body. Returns `None` when the body is not valid+/// JSON, not an object, or lacks the field. The spec defines the+/// field as a string ∈ {auto, default, flex, on_demand, priority};+/// we do NOT validate against that set here so wire-format drift+/// (e.g. OpenAI adding a tier we haven't enumerated yet) surfaces+/// in the metric rather than getting silently dropped.+fn extract_request_service_tier(body: &Bytes) -> Option<String> {+ let v: serde_json::Value = serde_json::from_slice(body).ok()?;+ v.get("service_tier")+ .and_then(|x| x.as_str())+ .map(|s| s.to_string())+}+/// Cheap check: is this request asking for an SSE response? Compares/// `Accept` against `text/event-stream` (case-insensitive on the/// media-type token, RFC 7231 §3.1.1.1). Multiple media types indiff --git a/crates/headroom-proxy/src/observability/cache_hit_rate.rs b/crates/headroom-proxy/src/observability/cache_hit_rate.rsnew file mode 100644index 000000000..ef152be29--- /dev/null+++ b/crates/headroom-proxy/src/observability/cache_hit_rate.rs@@ -0,0 +1,178 @@+//! Per-session cache-hit-rate observability — Phase G PR-G3.+//!+//! # The H-blocker metric+//!+//! Phase H ("retire the Python proxy") depends on this metric to+//! confirm parity between the Rust proxy and the soon-to-retire+//! Python proxy during canary. The acceptance gate in+//! `REALIGNMENT/10-phase-H-python-retirement.md:11-12` reads+//! `cache_hit_rate ≥ Python baseline; no 5xx regressions in 24h`.+//! That assertion is meaningless without this histogram.+//!+//! # Definition+//!+//! For every completed request session we observe one sample on the+//! `proxy_cache_hit_rate_per_session` histogram whose value is:+//!+//! ```text+//! cache_read_input_tokens+//! ───────────────────────+//! total_input_tokens+//! ```+//!+//! `total_input_tokens` is the full denominator each provider+//! exposes on the `usage` payload (input + cache_read ++//! cache_creation), NOT the "billable" input that excludes cache+//! hits. Defining the denominator this way means the metric stays+//! meaningful across providers and stays in [0, 1].+//!+//! # When called+//!+//! - Anthropic: at `message_delta` (which carries the final `usage`).+//! - OpenAI Chat: on the final usage chunk (when+//! `stream_options.include_usage = true`; otherwise no sample is+//! emitted — the absence is itself a signal).+//! - OpenAI Responses: at `response.completed`.+//!+//! # Cardinality+//!+//! One label only: `provider ∈ {anthropic, openai_chat, openai_responses}`.+//! The metric is *intentionally* low-cardinality — the H1 canary+//! looks at fleet-wide hit rate, not per-model. Per-model breakdown+//! lives in the per-provider info logs we already emit.+//!+//! # Bucket selection+//!+//! Bucket boundaries are picked so the histogram discriminates the+//! "no cache" → "cache landed" transition with high resolution near+//! 0 and the "high-hit-rate" regime (where cache is paying for+//! itself) with high resolution near 1. The middle is coarser because+//! ~50% hit-rate is operationally uninteresting — either the cache+//! is working or it isn't.++use std::sync::OnceLock;++use prometheus::{HistogramOpts, HistogramVec, Registry};++use super::metric_names::{+ LABEL_PROVIDER, METRIC_PROXY_CACHE_HIT_RATE_PER_SESSION,+ METRIC_PROXY_CACHE_HIT_RATE_PER_SESSION_HELP,+};++/// Histogram buckets in [0, 1]. Tighter near 0 (so a "barely any+/// cache hit" stays distinguishable from a true zero) and near 1+/// (so a "near-perfect cache" stays distinguishable from a real+/// 100% hit). The middle band is intentionally coarser.+pub(super) const CACHE_HIT_RATE_BUCKETS: &[f64] =+ &[0.0, 0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 1.0];++/// Provider label vocabulary. Kept here (rather than scattered+/// across emit sites) so the cardinality budget is reviewable in one+/// place per realignment build-constraint "configurable + scalable".+pub mod provider {+ pub const ANTHROPIC: &str = "anthropic";+ pub const OPENAI_CHAT: &str = "openai_chat";+ pub const OPENAI_RESPONSES: &str = "openai_responses";+}++/// `proxy_cache_hit_rate_per_session{provider}` — initialised on+/// first call from `register_in`.+pub fn histogram(registry: &Registry) -> &'static HistogramVec {+ static HIST: OnceLock<HistogramVec> = OnceLock::new();+ HIST.get_or_init(|| {+ let opts = HistogramOpts::new(+ METRIC_PROXY_CACHE_HIT_RATE_PER_SESSION,+ METRIC_PROXY_CACHE_HIT_RATE_PER_SESSION_HELP,+ )+ .buckets(CACHE_HIT_RATE_BUCKETS.to_vec());+ let hist = HistogramVec::new(opts, &[LABEL_PROVIDER])+ .expect("proxy_cache_hit_rate_per_session descriptor is well-formed");+ registry+ .register(Box::new(hist.clone()))+ .expect("proxy_cache_hit_rate_per_session registers exactly once");+ hist+ })+}++/// Compute the per-session cache hit rate given the three counters+/// most providers expose on `usage`. Returns `None` when the+/// denominator is zero (no input tokens at all — typically a+/// degenerate request such as an empty messages array), so callers+/// can choose to skip the observation rather than divide-by-zero.+///+/// Per realignment build-constraint "no silent fallbacks", a+/// zero-denominator request is *NOT* coerced to `0.0`; it returns+/// `None` so the emit-site can log + skip instead of polluting the+/// histogram with synthesised samples.+pub fn compute_hit_rate(+ input_tokens: u64,+ cache_read_input_tokens: u64,+ cache_creation_input_tokens: u64,+) -> Option<f64> {+ let denom = input_tokens+ .saturating_add(cache_read_input_tokens)+ .saturating_add(cache_creation_input_tokens);+ if denom == 0 {+ return None;+ }+ Some(cache_read_input_tokens as f64 / denom as f64)+}++/// Observe one per-session sample.+///+/// `provider` MUST be one of the [`provider`] constants — callers+/// from the SSE state machine pass the matching string verbatim. We+/// do not validate the label here because the cardinality is bounded+/// by the static call sites; an invalid label would be a bug, not a+/// runtime mismatch.+pub fn observe(provider: &'static str, request_id: &str, hit_rate: f64) {+ debug_assert!(+ (0.0..=1.0).contains(&hit_rate),+ "cache hit rate must be in [0.0, 1.0]; got {hit_rate}"+ );+ let clamped = hit_rate.clamp(0.0, 1.0);+ histogram(super::prometheus::registry())+ .with_label_values(&[provider])+ .observe(clamped);+ tracing::debug!(+ event = "metric_recorded",+ metric = METRIC_PROXY_CACHE_HIT_RATE_PER_SESSION,+ provider = provider,+ request_id = %request_id,+ hit_rate = clamped,+ "observed proxy_cache_hit_rate_per_session"+ );+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn hit_rate_zero_when_no_cache_reads() {+ let r = compute_hit_rate(100, 0, 0).unwrap();+ assert!((r - 0.0).abs() < f64::EPSILON);+ }++ #[test]+ fn hit_rate_one_when_all_reads_are_cache_hits() {+ // Edge case: input_tokens == 0 means upstream charged us+ // nothing new — every input came from cache.+ let r = compute_hit_rate(0, 1000, 0).unwrap();+ assert!((r - 1.0).abs() < f64::EPSILON);+ }++ #[test]+ fn hit_rate_split_three_ways() {+ // 50 fresh input, 50 cache_read, 50 cache_creation → 50/150.+ let r = compute_hit_rate(50, 50, 50).unwrap();+ assert!((r - (1.0 / 3.0)).abs() < 1e-9);+ }++ #[test]+ fn hit_rate_none_on_empty_request() {+ // Degenerate: no tokens at all. Caller should skip the+ // observation, not coerce to 0.0.+ assert!(compute_hit_rate(0, 0, 0).is_none());+ }+}diff --git a/crates/headroom-proxy/src/observability/compression_ratio.rs b/crates/headroom-proxy/src/observability/compression_ratio.rsnew file mode 100644index 000000000..10fdf7b85--- /dev/null+++ b/crates/headroom-proxy/src/observability/compression_ratio.rs@@ -0,0 +1,158 @@+//! Per-block compression-ratio observability — Phase G PR-G3.+//!+//! # Definition+//!+//! For every block the live-zone dispatcher successfully shrinks, we+//! observe one sample on the `proxy_compression_ratio_by_strategy`+//! histogram. The sample value is the ratio+//! `compressed_tokens / original_tokens` (in [0, 1)), so smaller =+//! better. The metric is labelled by:+//!+//! - `strategy` — the compressor identifier (`smart_crusher`,+//! `log_compressor`, `search_compressor`, `diff_compressor`,+//! `e3_anthropic_cache_control`, `e1_tool_array_sort`, …). The+//! label vocabulary is bounded by the static `&'static str` set+//! the compressors return on their `BlockAction::Compressed`+//! manifests — never a customer-controlled value.+//! - `content_type` — the detection-tier output for the block+//! (`source_code`, `log`, `search_output`, `diff`, `text`, …).+//! Cardinality bounded by `headroom_core::transforms::ContentType`.+//!+//! Counter twin: `proxy_compression_rejected_by_token_check_total{strategy}`+//! captures the "compressor ran but didn't shrink the token count"+//! case so dashboards can attribute the absence of histogram samples+//! to legitimate rejection rather than to a missing call site.+//!+//! # Bucket selection+//!+//! Buckets are tighter near 0 (the "aggressive shrink" tail dashboard+//! operators care about), wider in the middle. Anything above 1 would+//! be a tokenizer regression — `BlockAction::Compressed` enforces+//! `compressed_tokens < original_tokens`, so the histogram should+//! never see a sample > 0.99 in practice.++use std::sync::OnceLock;++use prometheus::{HistogramOpts, HistogramVec, IntCounterVec, Opts, Registry};++use super::metric_names::{+ LABEL_CONTENT_TYPE, LABEL_STRATEGY, METRIC_PROXY_COMPRESSION_RATIO_BY_STRATEGY,+ METRIC_PROXY_COMPRESSION_RATIO_BY_STRATEGY_HELP,+ METRIC_PROXY_COMPRESSION_REJECTED_BY_TOKEN_CHECK_TOTAL,+ METRIC_PROXY_COMPRESSION_REJECTED_BY_TOKEN_CHECK_TOTAL_HELP,+};++/// Histogram buckets in [0, 1). Tight at the aggressive end (≤0.25+/// means we kept ≤25% of the original tokens), coarser at the upper+/// end where a measurement is operationally indistinguishable from+/// "barely any shrink".+pub(super) const COMPRESSION_RATIO_BUCKETS: &[f64] =+ &[0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.75, 0.9, 0.99];++/// `proxy_compression_ratio_by_strategy{strategy, content_type}`.+pub fn ratio_histogram(registry: &Registry) -> &'static HistogramVec {+ static HIST: OnceLock<HistogramVec> = OnceLock::new();+ HIST.get_or_init(|| {+ let opts = HistogramOpts::new(+ METRIC_PROXY_COMPRESSION_RATIO_BY_STRATEGY,+ METRIC_PROXY_COMPRESSION_RATIO_BY_STRATEGY_HELP,+ )+ .buckets(COMPRESSION_RATIO_BUCKETS.to_vec());+ let hist = HistogramVec::new(opts, &[LABEL_STRATEGY, LABEL_CONTENT_TYPE])+ .expect("proxy_compression_ratio_by_strategy descriptor is well-formed");+ registry+ .register(Box::new(hist.clone()))+ .expect("proxy_compression_ratio_by_strategy registers exactly once");+ hist+ })+}++/// `proxy_compression_rejected_by_token_check_total{strategy}`.+pub fn rejected_counter(registry: &Registry) -> &'static IntCounterVec {+ static COUNTER: OnceLock<IntCounterVec> = OnceLock::new();+ COUNTER.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_COMPRESSION_REJECTED_BY_TOKEN_CHECK_TOTAL,+ METRIC_PROXY_COMPRESSION_REJECTED_BY_TOKEN_CHECK_TOTAL_HELP,+ );+ let counter = IntCounterVec::new(opts, &[LABEL_STRATEGY])+ .expect("proxy_compression_rejected_by_token_check_total descriptor is well-formed");+ registry+ .register(Box::new(counter.clone()))+ .expect("proxy_compression_rejected_by_token_check_total registers exactly once");+ counter+ })+}++/// Observe one compression-ratio sample. `strategy` and `content_type`+/// must be `&'static str` (bounded by compiler-known compressor ++/// content-type enum sets).+pub fn observe_ratio(+ strategy: &'static str,+ content_type: &str,+ original_tokens: usize,+ compressed_tokens: usize,+) {+ if original_tokens == 0 {+ // Per realignment build-constraint "no silent fallbacks": a+ // zero-denominator block would synthesise a `NaN` sample we+ // can't observe meaningfully. Loud-log and skip.+ tracing::warn!(+ event = "compression_ratio_zero_denominator",+ strategy = strategy,+ content_type = %content_type,+ compressed_tokens = compressed_tokens,+ "skipping proxy_compression_ratio_by_strategy observation: \+ original_tokens == 0 (would divide by zero)"+ );+ return;+ }+ let ratio = (compressed_tokens as f64) / (original_tokens as f64);+ ratio_histogram(super::prometheus::registry())+ .with_label_values(&[strategy, content_type])+ .observe(ratio);+ tracing::debug!(+ event = "metric_recorded",+ metric = METRIC_PROXY_COMPRESSION_RATIO_BY_STRATEGY,+ strategy = strategy,+ content_type = %content_type,+ original_tokens = original_tokens,+ compressed_tokens = compressed_tokens,+ ratio = ratio,+ "observed proxy_compression_ratio_by_strategy"+ );+}++/// Increment the rejection counter for a compressor that ran but did+/// not produce a token-smaller output.+pub fn record_rejected_by_token_check(strategy: &'static str) {+ rejected_counter(super::prometheus::registry())+ .with_label_values(&[strategy])+ .inc();+ tracing::debug!(+ event = "metric_recorded",+ metric = METRIC_PROXY_COMPRESSION_REJECTED_BY_TOKEN_CHECK_TOTAL,+ strategy = strategy,+ "incremented proxy_compression_rejected_by_token_check_total"+ );+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn zero_original_tokens_skips_observation() {+ // Calling observe with original_tokens=0 must not panic and+ // must not divide-by-zero; the warn log is sufficient.+ observe_ratio("smart_crusher", "text", 0, 0);+ }++ #[test]+ fn ratio_50_percent_recorded() {+ // Drive the metric so the family appears in scrapes; we+ // exercise the path here, not the value (which is asserted+ // via integration tests).+ observe_ratio("test_strategy_50pct", "text", 200, 100);+ }+}diff --git a/crates/headroom-proxy/src/observability/metric_names.rs b/crates/headroom-proxy/src/observability/metric_names.rsnew file mode 100644index 000000000..4edefb18b--- /dev/null+++ b/crates/headroom-proxy/src/observability/metric_names.rs@@ -0,0 +1,154 @@+//! Centralised metric-name + label-key constants — Phase G PR-G3.+//!+//! Realignment build-constraint "configurable: every metric name + label+//! vocabulary defined in one place" applies here. The Bedrock D3+//! metrics in [`super::prometheus`] predate this module; they keep+//! their inline literals (a churn-cost decision documented in the+//! PR-G3 commit) but every PR-G3 metric and its labels live here.+//!+//! # Naming convention+//!+//! - `METRIC_*` — the wire-name string. Prometheus convention:+//! `_total` for counters, `_seconds` / no suffix for histograms.+//! - `METRIC_*_HELP` — the HELP-line text used at registration. Kept+//! alongside the wire name so a rename catches both in one diff.+//! - `LABEL_*` — the label-key string. Reuse across metrics where+//! the dimension is the same (`provider`, `strategy`, …).++// ---------- proxy_cache_hit_rate_per_session ----------++pub const METRIC_PROXY_CACHE_HIT_RATE_PER_SESSION: &str = "proxy_cache_hit_rate_per_session";+pub const METRIC_PROXY_CACHE_HIT_RATE_PER_SESSION_HELP: &str =+ "Per-session cache hit rate observed at the Rust proxy from \+ usage.cache_read_input_tokens / (input + cache_read + cache_creation). \+ Phase H canary gate: parity with the Python proxy baseline.";++// ---------- proxy_compression_ratio_by_strategy ----------++pub const METRIC_PROXY_COMPRESSION_RATIO_BY_STRATEGY: &str = "proxy_compression_ratio_by_strategy";+pub const METRIC_PROXY_COMPRESSION_RATIO_BY_STRATEGY_HELP: &str =+ "Compression ratio (compressed_tokens / original_tokens) observed \+ per block that was actually shrunk by the live-zone dispatcher. \+ Labelled by strategy (smart_crusher/log_compressor/…) and \+ detected content_type.";++// ---------- proxy_compression_rejected_by_token_check_total ----------++pub const METRIC_PROXY_COMPRESSION_REJECTED_BY_TOKEN_CHECK_TOTAL: &str =+ "proxy_compression_rejected_by_token_check_total";+pub const METRIC_PROXY_COMPRESSION_REJECTED_BY_TOKEN_CHECK_TOTAL_HELP: &str =+ "Count of compressor runs whose output failed the tokenizer-validated \+ shrink check (compressed_tokens >= original_tokens). Surfaces 'we ran \+ but kept the original' cases that would otherwise be invisible.";++// ---------- proxy_passthrough_bytes_modified_total ----------++pub const METRIC_PROXY_PASSTHROUGH_BYTES_MODIFIED_TOTAL: &str =+ "proxy_passthrough_bytes_modified_total";+pub const METRIC_PROXY_PASSTHROUGH_BYTES_MODIFIED_TOTAL_HELP: &str =+ "Bytes modified on a path that is supposed to passthrough verbatim. \+ MUST stay 0 outside the compression-on hot path. Any non-zero rate \+ fires the cache-safety alarm.";++// ---------- proxy_rate_limit_remaining_* ----------++pub const METRIC_PROXY_RATE_LIMIT_REMAINING_REQUESTS: &str = "proxy_rate_limit_remaining_requests";+pub const METRIC_PROXY_RATE_LIMIT_REMAINING_REQUESTS_HELP: &str =+ "Upstream-reported remaining requests for the current window, \+ extracted from rate-limit response headers (anthropic-ratelimit-* \+ or x-ratelimit-*). Per-provider, per-window-bucket gauge.";++pub const METRIC_PROXY_RATE_LIMIT_REMAINING_TOKENS: &str = "proxy_rate_limit_remaining_tokens";+pub const METRIC_PROXY_RATE_LIMIT_REMAINING_TOKENS_HELP: &str =+ "Upstream-reported remaining tokens for the current window, extracted \+ from rate-limit response headers (anthropic-ratelimit-*-tokens or \+ x-ratelimit-remaining-tokens).";++pub const METRIC_PROXY_RATE_LIMIT_REMAINING_INPUT_TOKENS: &str =+ "proxy_rate_limit_remaining_input_tokens";+pub const METRIC_PROXY_RATE_LIMIT_REMAINING_INPUT_TOKENS_HELP: &str =+ "Upstream-reported remaining INPUT tokens for the current window. \+ Anthropic separates input and output token budgets in its \+ ratelimit headers; this gauge tracks the input bucket.";++pub const METRIC_PROXY_RATE_LIMIT_REMAINING_OUTPUT_TOKENS: &str =+ "proxy_rate_limit_remaining_output_tokens";+pub const METRIC_PROXY_RATE_LIMIT_REMAINING_OUTPUT_TOKENS_HELP: &str =+ "Upstream-reported remaining OUTPUT tokens for the current window. \+ Anthropic-only header on present providers.";++// ---------- proxy_service_tier_count_total ----------++pub const METRIC_PROXY_SERVICE_TIER_COUNT_TOTAL: &str = "proxy_service_tier_count_total";+pub const METRIC_PROXY_SERVICE_TIER_COUNT_TOTAL_HELP: &str =+ "Count of requests/responses observed at the proxy, labelled by the \+ OpenAI Responses service_tier the request resolved into (auto, \+ default, flex, on_demand, priority).";++// ---------- proxy_response_status_count_total ----------++pub const METRIC_PROXY_RESPONSE_STATUS_COUNT_TOTAL: &str = "proxy_response_status_count_total";+pub const METRIC_PROXY_RESPONSE_STATUS_COUNT_TOTAL_HELP: &str =+ "Count of OpenAI Responses outcomes labelled by terminal status \+ (completed, incomplete, failed, cancelled, in_progress). \+ 'incomplete' detail lands in the structured log paired with each \+ increment.";++// ---------- proxy_image_generation_call_log_redacted_total ----------++pub const METRIC_PROXY_IMAGE_GENERATION_CALL_LOG_REDACTED_TOTAL: &str =+ "proxy_image_generation_call_log_redacted_total";+pub const METRIC_PROXY_IMAGE_GENERATION_CALL_LOG_REDACTED_TOTAL_HELP: &str =+ "Count of base64-encoded image payloads redacted from request logs. \+ Driven from the Python proxy's request logger (large multi-MB \+ base64 strings replaced with size-only placeholders).";++// ---------- wrap_rtk_invocations_total ----------++pub const METRIC_WRAP_RTK_INVOCATIONS_TOTAL: &str = "wrap_rtk_invocations_total";+pub const METRIC_WRAP_RTK_INVOCATIONS_TOTAL_HELP: &str =+ "Count of RTK invocations observed via the wrap-CLI polling of \+ `rtk gain --format json`, broken down by the rewritten command \+ (`git`, `ls`, `cargo`, …).";++// ---------- wrap_rtk_tokens_saved_per_session ----------++pub const METRIC_WRAP_RTK_TOKENS_SAVED_PER_SESSION: &str = "wrap_rtk_tokens_saved_per_session";+pub const METRIC_WRAP_RTK_TOKENS_SAVED_PER_SESSION_HELP: &str =+ "Tokens saved by RTK during one wrap session, observed once at \+ session end. Histogram so dashboards can render a distribution.";++// ---------- shared label keys ----------++pub const LABEL_PROVIDER: &str = "provider";+pub const LABEL_STRATEGY: &str = "strategy";+pub const LABEL_CONTENT_TYPE: &str = "content_type";+pub const LABEL_PATH: &str = "path";+pub const LABEL_TIER: &str = "tier";+pub const LABEL_STATUS: &str = "status";+pub const LABEL_TOOL: &str = "tool";++// ---------- bounded label vocabularies ----------++/// OpenAI service-tier values per the Responses API spec+/// (`service_tier` field on the response object). The proxy logs+/// anything outside this set under the literal value so wire-format+/// drift is loud rather than silently bucketed.+pub mod service_tier {+ pub const AUTO: &str = "auto";+ pub const DEFAULT: &str = "default";+ pub const FLEX: &str = "flex";+ pub const ON_DEMAND: &str = "on_demand";+ pub const PRIORITY: &str = "priority";+}++/// OpenAI Responses terminal-status vocabulary. `in_progress` is the+/// non-terminal entry — included so observers see a request that+/// closed mid-stream (we increment on the last status seen).+pub mod response_status {+ pub const COMPLETED: &str = "completed";+ pub const INCOMPLETE: &str = "incomplete";+ pub const FAILED: &str = "failed";+ pub const CANCELLED: &str = "cancelled";+ pub const IN_PROGRESS: &str = "in_progress";+}diff --git a/crates/headroom-proxy/src/observability/mod.rs b/crates/headroom-proxy/src/observability/mod.rsindex d1c513a1d..295a52b9f 100644--- a/crates/headroom-proxy/src/observability/mod.rs+++ b/crates/headroom-proxy/src/observability/mod.rs@@ -38,9 +38,32 @@//! footprint small and the scrape endpoint trivial. Phase F may//! revisit if multi-process aggregation lands.+pub mod cache_hit_rate;+pub mod compression_ratio;+pub mod metric_names;pub mod prometheus;+pub mod proxy_metrics;pub use prometheus::{handle_metrics, observe_bedrock_invoke_latency, record_bedrock_eventstream_message,record_bedrock_invoke,};++// Phase G PR-G3 — re-export the canonical record_* helpers so call+// sites in `crate::sse`, `crate::handlers`, and `crate::proxy` get a+// flat `observability::record_x` import surface rather than a deep+// `observability::proxy_metrics::record_x` one. The deeper modules+// stay reachable for tests asserting on the metric vectors directly.+pub use cache_hit_rate::{+ compute_hit_rate as compute_cache_hit_rate, observe as observe_cache_hit_rate,+ provider as cache_hit_rate_provider,+};+pub use compression_ratio::{+ observe_ratio as observe_compression_ratio,+ record_rejected_by_token_check as record_compression_rejected_by_token_check,+};+pub use proxy_metrics::{+ extract_rate_limit_snapshot, record_image_redacted, record_passthrough_bytes_modified,+ record_rate_limit_snapshot, record_response_status, record_rtk_invocation, record_service_tier,+ RateLimitSnapshot,+};diff --git a/crates/headroom-proxy/src/observability/prometheus.rs b/crates/headroom-proxy/src/observability/prometheus.rsindex bde34934f..ec23a7605 100644--- a/crates/headroom-proxy/src/observability/prometheus.rs+++ b/crates/headroom-proxy/src/observability/prometheus.rs@@ -66,7 +66,15 @@ const LATENCY_BUCKETS_SECONDS: &[f64] = &[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 1/// Lazy singleton registry. Borrowed by `handle_metrics` for/// scrape rendering and by every metric registration helper.-fn registry() -> &'static Registry {+///+/// Visibility note: `pub(super)` is intentional — the Phase G PR-G3+/// metric modules (`cache_hit_rate`, `compression_ratio`,+/// `proxy_metrics`) live alongside this one and reach for the shared+/// singleton at register time. External callers should NOT touch the+/// registry directly; they go through the per-metric `record_*`+/// helpers, which keeps registration centralised and emit sites+/// uniform.+pub(super) fn registry() -> &'static Registry {static REGISTRY: OnceLock<Registry> = OnceLock::new();REGISTRY.get_or_init(Registry::new)}@@ -189,10 +197,14 @@ pub fn record_bedrock_eventstream_message(model: &str, region: &str, event_type:/// Axum handler for `GET /metrics`. Renders the registry in the/// Prometheus text format. Per Phase D acceptance: the scrape MUST-/// include the three Bedrock metrics above as soon as they have-/// been touched at least once; un-touched counter vectors expose-/// their HELP/TYPE lines but no labelled rows (Prometheus's-/// documented behaviour, not a regression).+/// include each metric family as soon as it has been touched at+/// least once with a label set. The `prometheus` v0.13 crate skips+/// empty `MetricVec` families from `gather()`, so until a counter+/// has incremented (or a histogram has observed) once, neither its+/// HELP/TYPE nor any row appears — a documented quirk we lean on+/// for the "must stay 0" alarm-able `proxy_passthrough_bytes_modified_total`+/// surface: its absence FROM the scrape is itself the proof the+/// alarm is silent.pub async fn handle_metrics() -> Response {// Force lazy registration so the HELP/TYPE descriptor lines// appear in the scrape even before any request has hit the@@ -203,6 +215,24 @@ pub async fn handle_metrics() -> Response {let _ = invoke_latency();let _ = eventstream_counter();+ // Phase G PR-G3: same idea for the new proxy-wide metric families.+ // Lazy `OnceLock`-backed singletons; touching each here forces+ // registration on first scrape so HELP/TYPE lines appear even+ // before traffic has driven a single increment.+ let reg = registry();+ let _ = super::cache_hit_rate::histogram(reg);+ let _ = super::compression_ratio::ratio_histogram(reg);+ let _ = super::compression_ratio::rejected_counter(reg);+ let _ = super::proxy_metrics::passthrough_bytes_modified_counter(reg);+ let _ = super::proxy_metrics::rate_limit_remaining_requests_gauge(reg);+ let _ = super::proxy_metrics::rate_limit_remaining_tokens_gauge(reg);+ let _ = super::proxy_metrics::rate_limit_remaining_input_tokens_gauge(reg);+ let _ = super::proxy_metrics::rate_limit_remaining_output_tokens_gauge(reg);+ let _ = super::proxy_metrics::service_tier_counter(reg);+ let _ = super::proxy_metrics::response_status_counter(reg);+ let _ = super::proxy_metrics::image_redacted_counter(reg);+ let _ = super::proxy_metrics::rtk_invocations_counter(reg);+let metric_families = registry().gather();let mut buffer = Vec::with_capacity(2048);let encoder = TextEncoder::new();diff --git a/crates/headroom-proxy/src/observability/proxy_metrics.rs b/crates/headroom-proxy/src/observability/proxy_metrics.rsnew file mode 100644index 000000000..527e64ec6--- /dev/null+++ b/crates/headroom-proxy/src/observability/proxy_metrics.rs@@ -0,0 +1,423 @@+//! Phase G PR-G3 proxy-side observability metrics: rate-limit gauges,+//! the passthrough-bytes-modified alarm counter, service-tier ++//! response-status counters, and the image-base64 redaction counter.+//!+//! Grouped in one file because each metric is a thin+//! `OnceLock` + 1–2 emit helpers; splitting per metric would dilute+//! the call sites without adding test surface. Heavier metrics with+//! their own validation logic (`cache_hit_rate`, `compression_ratio`)+//! live in their own modules.++use std::sync::OnceLock;++use prometheus::{IntCounterVec, IntGaugeVec, Opts, Registry};++use super::metric_names::{+ LABEL_PATH, LABEL_PROVIDER, LABEL_STATUS, LABEL_TIER, LABEL_TOOL,+ METRIC_PROXY_IMAGE_GENERATION_CALL_LOG_REDACTED_TOTAL,+ METRIC_PROXY_IMAGE_GENERATION_CALL_LOG_REDACTED_TOTAL_HELP,+ METRIC_PROXY_PASSTHROUGH_BYTES_MODIFIED_TOTAL,+ METRIC_PROXY_PASSTHROUGH_BYTES_MODIFIED_TOTAL_HELP,+ METRIC_PROXY_RATE_LIMIT_REMAINING_INPUT_TOKENS,+ METRIC_PROXY_RATE_LIMIT_REMAINING_INPUT_TOKENS_HELP,+ METRIC_PROXY_RATE_LIMIT_REMAINING_OUTPUT_TOKENS,+ METRIC_PROXY_RATE_LIMIT_REMAINING_OUTPUT_TOKENS_HELP,+ METRIC_PROXY_RATE_LIMIT_REMAINING_REQUESTS, METRIC_PROXY_RATE_LIMIT_REMAINING_REQUESTS_HELP,+ METRIC_PROXY_RATE_LIMIT_REMAINING_TOKENS, METRIC_PROXY_RATE_LIMIT_REMAINING_TOKENS_HELP,+ METRIC_PROXY_RESPONSE_STATUS_COUNT_TOTAL, METRIC_PROXY_RESPONSE_STATUS_COUNT_TOTAL_HELP,+ METRIC_PROXY_SERVICE_TIER_COUNT_TOTAL, METRIC_PROXY_SERVICE_TIER_COUNT_TOTAL_HELP,+ METRIC_WRAP_RTK_INVOCATIONS_TOTAL, METRIC_WRAP_RTK_INVOCATIONS_TOTAL_HELP,+};++// ---------- proxy_passthrough_bytes_modified_total{path} ----------++/// Counter (not gauge) so the metric obeys Prometheus' `_total`+/// convention while still meeting the spec's "must stay 0" alarm+/// requirement: dashboards alert on `rate(...[5m]) > 0`. A counter+/// stays at 0 forever until something actually modifies passthrough+/// bytes — which is the alarmable event.+pub fn passthrough_bytes_modified_counter(registry: &Registry) -> &'static IntCounterVec {+ static COUNTER: OnceLock<IntCounterVec> = OnceLock::new();+ COUNTER.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_PASSTHROUGH_BYTES_MODIFIED_TOTAL,+ METRIC_PROXY_PASSTHROUGH_BYTES_MODIFIED_TOTAL_HELP,+ );+ let counter = IntCounterVec::new(opts, &[LABEL_PATH])+ .expect("proxy_passthrough_bytes_modified_total descriptor is well-formed");+ registry+ .register(Box::new(counter.clone()))+ .expect("proxy_passthrough_bytes_modified_total registers exactly once");+ counter+ })+}++/// Add `bytes` modified on a path that was supposed to be byte-equal+/// passthrough. The increment value is the byte delta — operators+/// then `rate(...)` to see "bytes/sec of policy violation".+pub fn record_passthrough_bytes_modified(path: &str, bytes: u64, request_id: &str) {+ passthrough_bytes_modified_counter(super::prometheus::registry())+ .with_label_values(&[path])+ .inc_by(bytes);+ tracing::warn!(+ event = "passthrough_bytes_modified",+ metric = METRIC_PROXY_PASSTHROUGH_BYTES_MODIFIED_TOTAL,+ path = %path,+ bytes = bytes,+ request_id = %request_id,+ "passthrough path modified bytes; this is the cache-safety alarm condition"+ );+}++// ---------- proxy_rate_limit_remaining_* gauges ----------++pub fn rate_limit_remaining_requests_gauge(registry: &Registry) -> &'static IntGaugeVec {+ static GAUGE: OnceLock<IntGaugeVec> = OnceLock::new();+ GAUGE.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_RATE_LIMIT_REMAINING_REQUESTS,+ METRIC_PROXY_RATE_LIMIT_REMAINING_REQUESTS_HELP,+ );+ let gauge = IntGaugeVec::new(opts, &[LABEL_PROVIDER])+ .expect("proxy_rate_limit_remaining_requests descriptor is well-formed");+ registry+ .register(Box::new(gauge.clone()))+ .expect("proxy_rate_limit_remaining_requests registers exactly once");+ gauge+ })+}++pub fn rate_limit_remaining_tokens_gauge(registry: &Registry) -> &'static IntGaugeVec {+ static GAUGE: OnceLock<IntGaugeVec> = OnceLock::new();+ GAUGE.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_RATE_LIMIT_REMAINING_TOKENS,+ METRIC_PROXY_RATE_LIMIT_REMAINING_TOKENS_HELP,+ );+ let gauge = IntGaugeVec::new(opts, &[LABEL_PROVIDER])+ .expect("proxy_rate_limit_remaining_tokens descriptor is well-formed");+ registry+ .register(Box::new(gauge.clone()))+ .expect("proxy_rate_limit_remaining_tokens registers exactly once");+ gauge+ })+}++pub fn rate_limit_remaining_input_tokens_gauge(registry: &Registry) -> &'static IntGaugeVec {+ static GAUGE: OnceLock<IntGaugeVec> = OnceLock::new();+ GAUGE.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_RATE_LIMIT_REMAINING_INPUT_TOKENS,+ METRIC_PROXY_RATE_LIMIT_REMAINING_INPUT_TOKENS_HELP,+ );+ let gauge = IntGaugeVec::new(opts, &[LABEL_PROVIDER])+ .expect("proxy_rate_limit_remaining_input_tokens descriptor is well-formed");+ registry+ .register(Box::new(gauge.clone()))+ .expect("proxy_rate_limit_remaining_input_tokens registers exactly once");+ gauge+ })+}++pub fn rate_limit_remaining_output_tokens_gauge(registry: &Registry) -> &'static IntGaugeVec {+ static GAUGE: OnceLock<IntGaugeVec> = OnceLock::new();+ GAUGE.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_RATE_LIMIT_REMAINING_OUTPUT_TOKENS,+ METRIC_PROXY_RATE_LIMIT_REMAINING_OUTPUT_TOKENS_HELP,+ );+ let gauge = IntGaugeVec::new(opts, &[LABEL_PROVIDER])+ .expect("proxy_rate_limit_remaining_output_tokens descriptor is well-formed");+ registry+ .register(Box::new(gauge.clone()))+ .expect("proxy_rate_limit_remaining_output_tokens registers exactly once");+ gauge+ })+}++/// Snapshot of upstream rate-limit headers extracted from one+/// response. None-fields are headers the upstream did not include+/// (per realignment build-constraint "no silent fallbacks": we do not+/// fabricate a value, we just don't emit on that gauge).+#[derive(Debug, Default, Clone, Copy)]+pub struct RateLimitSnapshot {+ pub remaining_requests: Option<i64>,+ pub remaining_tokens: Option<i64>,+ pub remaining_input_tokens: Option<i64>,+ pub remaining_output_tokens: Option<i64>,+}++/// Extract a `RateLimitSnapshot` from a HeaderMap. Accepts both+/// Anthropic (`anthropic-ratelimit-*`) and OpenAI (`x-ratelimit-*`)+/// header families. Missing headers stay `None`.+///+/// `Retry-After` is intentionally NOT parsed here — that header is+/// upstream-bounded by 429s, not steady-state telemetry, and lives in+/// the existing structured 429 log line.+pub fn extract_rate_limit_snapshot(headers: &http::HeaderMap) -> RateLimitSnapshot {+ let parse_i64 = |name: &str| -> Option<i64> {+ headers+ .get(name)+ .and_then(|v| v.to_str().ok())+ .and_then(|s| s.trim().parse::<i64>().ok())+ };+ RateLimitSnapshot {+ remaining_requests: parse_i64("anthropic-ratelimit-requests-remaining")+ .or_else(|| parse_i64("x-ratelimit-remaining-requests")),+ remaining_tokens: parse_i64("anthropic-ratelimit-tokens-remaining")+ .or_else(|| parse_i64("x-ratelimit-remaining-tokens")),+ remaining_input_tokens: parse_i64("anthropic-ratelimit-input-tokens-remaining"),+ remaining_output_tokens: parse_i64("anthropic-ratelimit-output-tokens-remaining"),+ }+}++/// Set all four gauges that the snapshot populates.+pub fn record_rate_limit_snapshot(+ provider: &'static str,+ snapshot: &RateLimitSnapshot,+ request_id: &str,+) {+ let registry = super::prometheus::registry();+ if let Some(v) = snapshot.remaining_requests {+ rate_limit_remaining_requests_gauge(registry)+ .with_label_values(&[provider])+ .set(v);+ }+ if let Some(v) = snapshot.remaining_tokens {+ rate_limit_remaining_tokens_gauge(registry)+ .with_label_values(&[provider])+ .set(v);+ }+ if let Some(v) = snapshot.remaining_input_tokens {+ rate_limit_remaining_input_tokens_gauge(registry)+ .with_label_values(&[provider])+ .set(v);+ }+ if let Some(v) = snapshot.remaining_output_tokens {+ rate_limit_remaining_output_tokens_gauge(registry)+ .with_label_values(&[provider])+ .set(v);+ }+ tracing::debug!(+ event = "metric_recorded",+ metric = "proxy_rate_limit_remaining_*",+ provider = provider,+ request_id = %request_id,+ remaining_requests = ?snapshot.remaining_requests,+ remaining_tokens = ?snapshot.remaining_tokens,+ remaining_input_tokens = ?snapshot.remaining_input_tokens,+ remaining_output_tokens = ?snapshot.remaining_output_tokens,+ "recorded proxy_rate_limit_remaining_* gauges"+ );+}++// ---------- proxy_service_tier_count_total{tier} ----------++pub fn service_tier_counter(registry: &Registry) -> &'static IntCounterVec {+ static COUNTER: OnceLock<IntCounterVec> = OnceLock::new();+ COUNTER.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_SERVICE_TIER_COUNT_TOTAL,+ METRIC_PROXY_SERVICE_TIER_COUNT_TOTAL_HELP,+ );+ let counter = IntCounterVec::new(opts, &[LABEL_TIER])+ .expect("proxy_service_tier_count_total descriptor is well-formed");+ registry+ .register(Box::new(counter.clone()))+ .expect("proxy_service_tier_count_total registers exactly once");+ counter+ })+}++pub fn record_service_tier(tier: &str, request_id: &str) {+ service_tier_counter(super::prometheus::registry())+ .with_label_values(&[tier])+ .inc();+ tracing::debug!(+ event = "metric_recorded",+ metric = METRIC_PROXY_SERVICE_TIER_COUNT_TOTAL,+ tier = %tier,+ request_id = %request_id,+ "incremented proxy_service_tier_count_total"+ );+}++// ---------- proxy_response_status_count_total{status} ----------++pub fn response_status_counter(registry: &Registry) -> &'static IntCounterVec {+ static COUNTER: OnceLock<IntCounterVec> = OnceLock::new();+ COUNTER.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_RESPONSE_STATUS_COUNT_TOTAL,+ METRIC_PROXY_RESPONSE_STATUS_COUNT_TOTAL_HELP,+ );+ let counter = IntCounterVec::new(opts, &[LABEL_STATUS])+ .expect("proxy_response_status_count_total descriptor is well-formed");+ registry+ .register(Box::new(counter.clone()))+ .expect("proxy_response_status_count_total registers exactly once");+ counter+ })+}++/// Record a Responses terminal status. `reason` is the+/// `incomplete_details.reason` field on `incomplete` responses (or+/// any other side-channel info worth pairing with the metric). It is+/// emitted in the structured log alongside the counter increment but+/// is NOT used as a label (would blow up cardinality).+pub fn record_response_status(status: &str, reason: Option<&str>, request_id: &str) {+ response_status_counter(super::prometheus::registry())+ .with_label_values(&[status])+ .inc();+ tracing::info!(+ event = "metric_recorded",+ metric = METRIC_PROXY_RESPONSE_STATUS_COUNT_TOTAL,+ status = %status,+ reason = reason.unwrap_or(""),+ request_id = %request_id,+ "incremented proxy_response_status_count_total"+ );+}++// ---------- proxy_image_generation_call_log_redacted_total ----------++pub fn image_redacted_counter(registry: &Registry) -> &'static IntCounterVec {+ static COUNTER: OnceLock<IntCounterVec> = OnceLock::new();+ COUNTER.get_or_init(|| {+ let opts = Opts::new(+ METRIC_PROXY_IMAGE_GENERATION_CALL_LOG_REDACTED_TOTAL,+ METRIC_PROXY_IMAGE_GENERATION_CALL_LOG_REDACTED_TOTAL_HELP,+ );+ // Unlabelled metric — but `IntCounterVec` with zero labels+ // is still the right type for symmetry with the rest of the+ // module. A bare `IntCounter` would diverge in registration+ // shape and read site.+ let counter = IntCounterVec::new(opts, &[])+ .expect("proxy_image_generation_call_log_redacted_total descriptor is well-formed");+ registry+ .register(Box::new(counter.clone()))+ .expect("proxy_image_generation_call_log_redacted_total registers exactly once");+ counter+ })+}++pub fn record_image_redacted() {+ image_redacted_counter(super::prometheus::registry())+ .with_label_values(&[])+ .inc();+ tracing::debug!(+ event = "metric_recorded",+ metric = METRIC_PROXY_IMAGE_GENERATION_CALL_LOG_REDACTED_TOTAL,+ "incremented proxy_image_generation_call_log_redacted_total"+ );+}++// ---------- wrap_rtk_invocations_total{tool} ----------+//+// RTK lives on the wrap-CLI side; the proxy never invokes it. The+// counter is registered here so the central /metrics scrape exposes+// it and the wrap-side tail can `inc()` via the registry. The wrap+// side polls `rtk gain --format json` and increments by the delta.++pub fn rtk_invocations_counter(registry: &Registry) -> &'static IntCounterVec {+ static COUNTER: OnceLock<IntCounterVec> = OnceLock::new();+ COUNTER.get_or_init(|| {+ let opts = Opts::new(+ METRIC_WRAP_RTK_INVOCATIONS_TOTAL,+ METRIC_WRAP_RTK_INVOCATIONS_TOTAL_HELP,+ );+ let counter = IntCounterVec::new(opts, &[LABEL_TOOL])+ .expect("wrap_rtk_invocations_total descriptor is well-formed");+ registry+ .register(Box::new(counter.clone()))+ .expect("wrap_rtk_invocations_total registers exactly once");+ counter+ })+}++pub fn record_rtk_invocation(tool: &str, delta: u64) {+ rtk_invocations_counter(super::prometheus::registry())+ .with_label_values(&[tool])+ .inc_by(delta);+ tracing::debug!(+ event = "metric_recorded",+ metric = METRIC_WRAP_RTK_INVOCATIONS_TOTAL,+ tool = %tool,+ delta = delta,+ "incremented wrap_rtk_invocations_total"+ );+}++#[cfg(test)]+mod tests {+ use super::*;+ use http::{HeaderMap, HeaderValue};++ #[test]+ fn extract_rate_limit_snapshot_anthropic() {+ let mut h = HeaderMap::new();+ h.insert(+ "anthropic-ratelimit-requests-remaining",+ HeaderValue::from_static("499"),+ );+ h.insert(+ "anthropic-ratelimit-tokens-remaining",+ HeaderValue::from_static("99000"),+ );+ h.insert(+ "anthropic-ratelimit-input-tokens-remaining",+ HeaderValue::from_static("80000"),+ );+ h.insert(+ "anthropic-ratelimit-output-tokens-remaining",+ HeaderValue::from_static("16000"),+ );+ let snap = extract_rate_limit_snapshot(&h);+ assert_eq!(snap.remaining_requests, Some(499));+ assert_eq!(snap.remaining_tokens, Some(99000));+ assert_eq!(snap.remaining_input_tokens, Some(80000));+ assert_eq!(snap.remaining_output_tokens, Some(16000));+ }++ #[test]+ fn extract_rate_limit_snapshot_openai() {+ let mut h = HeaderMap::new();+ h.insert(+ "x-ratelimit-remaining-requests",+ HeaderValue::from_static("1000"),+ );+ h.insert(+ "x-ratelimit-remaining-tokens",+ HeaderValue::from_static("250000"),+ );+ let snap = extract_rate_limit_snapshot(&h);+ assert_eq!(snap.remaining_requests, Some(1000));+ assert_eq!(snap.remaining_tokens, Some(250000));+ // OpenAI does not split input/output buckets.+ assert_eq!(snap.remaining_input_tokens, None);+ assert_eq!(snap.remaining_output_tokens, None);+ }++ #[test]+ fn extract_rate_limit_snapshot_no_headers() {+ let h = HeaderMap::new();+ let snap = extract_rate_limit_snapshot(&h);+ assert_eq!(snap.remaining_requests, None);+ assert_eq!(snap.remaining_tokens, None);+ assert_eq!(snap.remaining_input_tokens, None);+ assert_eq!(snap.remaining_output_tokens, None);+ }++ #[test]+ fn extract_rate_limit_snapshot_unparseable_value_is_none() {+ let mut h = HeaderMap::new();+ // Junk value — must not panic; must surface as None per+ // "no silent fallback" (the absence itself is the signal).+ h.insert(+ "anthropic-ratelimit-requests-remaining",+ HeaderValue::from_static("not-a-number"),+ );+ let snap = extract_rate_limit_snapshot(&h);+ assert_eq!(snap.remaining_requests, None);+ }+}diff --git a/crates/headroom-proxy/src/proxy.rs b/crates/headroom-proxy/src/proxy.rsindex 8d1a5311b..e81294442 100644--- a/crates/headroom-proxy/src/proxy.rs+++ b/crates/headroom-proxy/src/proxy.rs@@ -769,6 +769,26 @@ pub(crate) async fn forward_http(markers = markers_inserted.len(),"compression applied");+ // Phase G PR-G3: emit one+ // `proxy_compression_ratio_by_strategy` sample per+ // strategy actually applied. We do NOT have a+ // per-block content_type breakdown here — the+ // aggregate `tokens_before` / `tokens_after` is+ // strategy-wise rather than content-type-wise, so we+ // label `content_type=aggregate`. Per-block fanout+ // would require threading the manifest through to+ // this layer; that's a future PR if dashboards need+ // it.+ if tokens_before > 0 && tokens_after < tokens_before {+ for strategy in &strategies_applied {+ crate::observability::observe_compression_ratio(+ strategy,+ "aggregate",+ tokens_before,+ tokens_after,+ );+ }+ }body}compression::Outcome::Passthrough { reason } => {@@ -903,6 +923,49 @@ pub(crate) async fn forward_http(let resp_headers = filter_response_headers(upstream_resp.headers());+ // Phase G PR-G3: extract upstream rate-limit headers from this+ // response and record them as gauges. The `provider` label is+ // chosen by which of the upstream `request-id` shapes we saw+ // (Anthropic vs OpenAI). When neither shape was detected we+ // skip emission rather than guessing — per realignment build-+ // constraint "no silent fallbacks".+ let rate_limit_snapshot =+ crate::observability::extract_rate_limit_snapshot(upstream_resp.headers());+ let rate_limit_provider: Option<&'static str> = if upstream_request_id_anthropic.is_some() {+ Some(crate::observability::cache_hit_rate_provider::ANTHROPIC)+ } else if upstream_request_id_openai.is_some() {+ // We can't distinguish chat vs responses purely from the+ // request-id header; the `path_for_log` is more specific.+ Some(if path_for_log.contains("/v1/responses") {+ crate::observability::cache_hit_rate_provider::OPENAI_RESPONSES+ } else {+ crate::observability::cache_hit_rate_provider::OPENAI_CHAT+ })+ } else {+ None+ };+ if let Some(provider) = rate_limit_provider {+ crate::observability::record_rate_limit_snapshot(+ provider,+ &rate_limit_snapshot,+ &request_id,+ );+ } else if rate_limit_snapshot.remaining_requests.is_some()+ || rate_limit_snapshot.remaining_tokens.is_some()+ || rate_limit_snapshot.remaining_input_tokens.is_some()+ || rate_limit_snapshot.remaining_output_tokens.is_some()+ {+ // Headers present but provider unattributable. Log loud so+ // operators see the wire-format drift; do not emit unlabelled+ // metrics.+ tracing::debug!(+ event = "rate_limit_snapshot_unattributable",+ request_id = %request_id,+ path = %path_for_log,+ "rate-limit headers present but provider couldn't be inferred; skipping gauge emit"+ );+ }+// Stream response body back without buffering. Wrap errors so mid-stream// upstream failures are logged rather than silently truncating the client.//@@ -1179,6 +1242,34 @@ async fn run_sse_state_machine(}}}+ // Phase G PR-G3: emit per-session cache-hit-rate from+ // the final accumulated `usage`. Anthropic's+ // `message_delta` strictly grows token counts, so the+ // accumulator's final values are the right denominator.+ // `compute_cache_hit_rate` returns `None` for zero+ // denominators → log + skip, never synthesise a sample.+ match crate::observability::compute_cache_hit_rate(+ state.usage.input_tokens,+ state.usage.cache_read_input_tokens,+ state.usage.cache_creation_input_tokens,+ ) {+ Some(rate) => {+ crate::observability::observe_cache_hit_rate(+ crate::observability::cache_hit_rate_provider::ANTHROPIC,+ &request_id,+ rate,+ );+ }+ None => {+ tracing::debug!(+ event = "cache_hit_rate_skipped",+ request_id = %request_id,+ provider = "anthropic",+ reason = "zero_denominator",+ "skipping proxy_cache_hit_rate_per_session: no input tokens"+ );+ }+ }tracing::info!(request_id = %request_id,provider = "anthropic",@@ -1216,6 +1307,55 @@ async fn run_sse_state_machine(}}}+ // Phase G PR-G3: emit cache-hit-rate from the final usage+ // chunk. OpenAI only emits this when+ // `stream_options.include_usage = true`; absence is a+ // signal, not a fallback condition — `usage = None` →+ // skip.+ if let Some(usage) = &state.usage {+ let input_tokens = usage+ .get("prompt_tokens")+ .and_then(|v| v.as_u64())+ .unwrap_or(0);+ let cached_tokens = usage+ .get("prompt_tokens_details")+ .and_then(|d| d.get("cached_tokens"))+ .and_then(|v| v.as_u64())+ .unwrap_or(0);+ // OpenAI's `prompt_tokens` already INCLUDES cached+ // tokens (per Chat Completions API docs), so the+ // denominator is `prompt_tokens`, not the sum. The+ // numerator is `cached_tokens`; `input_tokens` arg to+ // `compute_cache_hit_rate` carries the *non-cached*+ // portion (denom-only), so we synthesise that here.+ let non_cached = input_tokens.saturating_sub(cached_tokens);+ match crate::observability::compute_cache_hit_rate(non_cached, cached_tokens, 0) {+ Some(rate) => {+ crate::observability::observe_cache_hit_rate(+ crate::observability::cache_hit_rate_provider::OPENAI_CHAT,+ &request_id,+ rate,+ );+ }+ None => {+ tracing::debug!(+ event = "cache_hit_rate_skipped",+ request_id = %request_id,+ provider = "openai_chat",+ reason = "zero_denominator",+ "skipping proxy_cache_hit_rate_per_session: no input tokens"+ );+ }+ }+ } else {+ tracing::debug!(+ event = "cache_hit_rate_skipped",+ request_id = %request_id,+ provider = "openai_chat",+ reason = "no_usage_chunk",+ "skipping proxy_cache_hit_rate_per_session: stream_options.include_usage=false"+ );+ }tracing::info!(request_id = %request_id,provider = "openai_chat",@@ -1249,11 +1389,64 @@ async fn run_sse_state_machine(}}}+ // Phase G PR-G3: cache hit rate + service_tier ++ // response status from the final `response.completed`+ // payload. The Responses API uses `input_tokens` /+ // `cached_input_tokens` shape (Responses-specific —+ // distinct from Chat Completions' `prompt_tokens`).+ if let Some(usage) = &state.usage {+ let input_tokens = usage+ .get("input_tokens")+ .and_then(|v| v.as_u64())+ .unwrap_or(0);+ let cached_tokens = usage+ .get("input_tokens_details")+ .and_then(|d| d.get("cached_tokens"))+ .and_then(|v| v.as_u64())+ .unwrap_or(0);+ // Like Chat, `input_tokens` already INCLUDES cached+ // tokens, so split for the helper.+ let non_cached = input_tokens.saturating_sub(cached_tokens);+ match crate::observability::compute_cache_hit_rate(non_cached, cached_tokens, 0) {+ Some(rate) => {+ crate::observability::observe_cache_hit_rate(+ crate::observability::cache_hit_rate_provider::OPENAI_RESPONSES,+ &request_id,+ rate,+ );+ }+ None => {+ tracing::debug!(+ event = "cache_hit_rate_skipped",+ request_id = %request_id,+ provider = "openai_responses",+ reason = "zero_denominator",+ "skipping proxy_cache_hit_rate_per_session: no input tokens"+ );+ }+ }+ }+ // Service tier + status are sourced from+ // `state.last_response_envelope` populated by the+ // ResponseState on `response.completed/failed/incomplete`.+ if let Some(tier) = state.service_tier.as_deref() {+ crate::observability::record_service_tier(tier, &request_id);+ }+ if let Some(status) = state.terminal_status() {+ crate::observability::record_response_status(+ status,+ state.incomplete_reason.as_deref(),+ &request_id,+ );+ }tracing::info!(request_id = %request_id,provider = "openai_responses",items = state.items.len(),has_usage = state.usage.is_some(),+ service_tier = state.service_tier.as_deref().unwrap_or(""),+ terminal_status = state.terminal_status().unwrap_or(""),+ incomplete_reason = state.incomplete_reason.as_deref().unwrap_or(""),"sse stream closed");}diff --git a/crates/headroom-proxy/src/sse/openai_responses.rs b/crates/headroom-proxy/src/sse/openai_responses.rsindex 9fc75b003..363b41391 100644--- a/crates/headroom-proxy/src/sse/openai_responses.rs+++ b/crates/headroom-proxy/src/sse/openai_responses.rs@@ -55,6 +55,30 @@ pub struct ResponseState {pub items: HashMap<String, ItemState>,pub usage: Option<Value>,pub status: StreamStatus,+ /// Phase G PR-G3: `service_tier` extracted from the+ /// `response.completed` envelope. Drives+ /// `proxy_service_tier_count_total`.+ pub service_tier: Option<String>,+ /// Phase G PR-G3: `incomplete_details.reason` when+ /// `status == "incomplete"`. Paired with the+ /// `proxy_response_status_count_total{status="incomplete"}` log+ /// line so operators see WHY a stream landed in `incomplete`.+ pub incomplete_reason: Option<String>,+}++impl ResponseState {+ /// Phase G PR-G3: stable terminal-status string for the metrics+ /// label vocabulary. Returns `None` when the stream is still+ /// `Open` — caller skips the counter increment in that case.+ pub fn terminal_status(&self) -> Option<&'static str> {+ use crate::observability::metric_names::response_status::{COMPLETED, FAILED, INCOMPLETE};+ match self.status {+ StreamStatus::Completed => Some(COMPLETED),+ StreamStatus::Failed => Some(FAILED),+ StreamStatus::Incomplete => Some(INCOMPLETE),+ StreamStatus::Open => None,+ }+ }}#[derive(Debug, Default, Clone)]@@ -139,10 +163,30 @@ impl ResponseState {"response.completed" => self.on_response_completed(&v),"response.failed" => {self.status = StreamStatus::Failed;+ // Phase G PR-G3: capture `service_tier` from the+ // failed envelope too — the proxy still wants the+ // tier dimension on failed responses so dashboards+ // can attribute failure rate to tiers.+ self.capture_envelope_metadata(&v);Ok(())}"response.incomplete" => {self.status = StreamStatus::Incomplete;+ // Phase G PR-G3: pick up incomplete_details.reason+ // from the envelope. Spec field name is+ // `incomplete_details.reason`; we tolerate both+ // the top-level and the nested location, since the+ // OpenAI shape has shifted across SDK versions.+ if let Some(resp) = v.get("response") {+ if let Some(reason) = resp+ .get("incomplete_details")+ .and_then(|d| d.get("reason"))+ .and_then(|x| x.as_str())+ {+ self.incomplete_reason = Some(reason.to_string());+ }+ }+ self.capture_envelope_metadata(&v);Ok(())}other => {@@ -369,8 +413,33 @@ impl ResponseState {}}}+ self.capture_envelope_metadata(v);Ok(())}++ /// Phase G PR-G3: extract `service_tier` and (when present)+ /// `incomplete_details.reason` from a top-level+ /// `response.{completed,failed,incomplete}` event payload. The+ /// `service_tier` field is on the `response` envelope on every+ /// terminal event per the OpenAI Responses API spec; we keep+ /// the most-recent value (later events override earlier ones).+ fn capture_envelope_metadata(&mut self, v: &Value) {+ if let Some(resp) = v.get("response") {+ if let Some(tier) = resp.get("service_tier").and_then(|x| x.as_str()) {+ self.service_tier = Some(tier.to_string());+ }+ // Best-effort pull of incomplete_details.reason from the+ // completed/failed envelope (in addition to the dedicated+ // arm in `apply` for `response.incomplete`).+ if let Some(reason) = resp+ .get("incomplete_details")+ .and_then(|d| d.get("reason"))+ .and_then(|x| x.as_str())+ {+ self.incomplete_reason = Some(reason.to_string());+ }+ }+ }}fn parse_json(data: &bytes::Bytes) -> Result<Value, StateError> {diff --git a/crates/headroom-proxy/tests/integration_metrics.rs b/crates/headroom-proxy/tests/integration_metrics.rsnew file mode 100644index 000000000..f7bf30cdc--- /dev/null+++ b/crates/headroom-proxy/tests/integration_metrics.rs@@ -0,0 +1,542 @@+//! Phase G PR-G3 — integration tests for the new proxy-wide+//! observability metrics. One test per category per the spec:+//!+//! 1. `cache_hit_rate_emitted_per_session` — drive an Anthropic+//! streaming response that carries cache_read_input_tokens on+//! `message_delta`; assert the histogram saw the right sample.+//! 2. `compression_ratio_emitted_per_strategy` — exercise the+//! helper directly (the metric records on+//! `Outcome::Compressed`; live-zone compression of small+//! payloads doesn't reliably fire, so the integration test+//! drives the public helper as a state-machine smoke test).+//! 3. `passthrough_bytes_modified_zero_when_no_compression` —+//! confirm the alarm-able counter stays at 0 across an+//! end-to-end passthrough request.+//! 4. `service_tier_logged` — drive a Responses request carrying+//! `service_tier` and assert the counter rows appear.+//! 5. `incomplete_status_logged_with_reason` — drive an SSE+//! response with `response.incomplete`; assert the counter row+//! and the structured-log reason.+//!+//! Like the D3 metrics tests, every test owns a unique label tuple+//! so concurrent test runs over the shared global registry never+//! cross-contaminate.++mod common;++use bytes::Bytes;+use common::start_proxy_with;+use headroom_proxy::observability;+use headroom_proxy::sse::openai_responses::ResponseState;+use headroom_proxy::sse::SseFramer;+use serde_json::json;+use std::convert::Infallible;+use std::net::SocketAddr;+use std::time::Duration;++use http_body_util::StreamBody;+use hyper::body::Frame;+use hyper::service::service_fn;+use hyper::{Request, Response};+use hyper_util::rt::TokioIo;++/// Fetch the proxy's `/metrics` text-format scrape.+async fn scrape_metrics(proxy_url: &str) -> String {+ let resp = reqwest::Client::new()+ .get(format!("{proxy_url}/metrics"))+ .send()+ .await+ .expect("metrics scrape");+ assert_eq!(resp.status(), 200, "metrics endpoint must return 200");+ resp.text().await.unwrap()+}++/// Find a line that contains the metric name + every label pair, and+/// parse its trailing numeric value. Mirrors the helper used by the+/// Bedrock D3 metrics test.+fn find_value_with_labels(scrape: &str, metric: &str, label_pairs: &[(&str, &str)]) -> Option<f64> {+ for line in scrape.lines() {+ if !line.starts_with(metric) {+ continue;+ }+ if !label_pairs+ .iter()+ .all(|(k, v)| line.contains(&format!("{k}=\"{v}\"")))+ {+ continue;+ }+ if let Some(value_str) = line.rsplit_once(' ').map(|(_, v)| v.trim()) {+ if let Ok(f) = value_str.parse::<f64>() {+ return Some(f);+ }+ }+ }+ None+}++// ============================================================================+// Test 1: cache_hit_rate_emitted_per_session+// ============================================================================+//+// Anthropic SSE upstream that emits message_start (carrying+// input_tokens + cache_read_input_tokens) and message_delta+// (with the final usage object). We pipe this through the+// proxy's `/v1/messages` SSE path; the state machine then closes+// and the `proxy_cache_hit_rate_per_session{provider="anthropic"}`+// histogram should have exactly one sample.++async fn anthropic_streaming_upstream(+ cache_read_input_tokens: u64,+ input_tokens: u64,+) -> (SocketAddr, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let task = tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ break;+ };+ tokio::spawn(async move {+ let io = TokioIo::new(stream);+ let _ = hyper::server::conn::http1::Builder::new()+ .serve_connection(+ io,+ service_fn(move |_req: Request<hyper::body::Incoming>| async move {+ let (tx, rx) = tokio::sync::mpsc::channel::<+ Result<Frame<Bytes>, std::io::Error>,+ >(8);+ tokio::spawn(async move {+ let start = format!(+ "event: message_start\ndata: {{\"type\":\"message_start\",\"message\":{{\"id\":\"msg_x\",\"model\":\"claude\",\"usage\":{{\"input_tokens\":{input_tokens},\"output_tokens\":0,\"cache_read_input_tokens\":{cache_read_input_tokens}}}}}}}\n\n"+ );+ let delta = format!(+ "event: message_delta\ndata: {{\"type\":\"message_delta\",\"delta\":{{\"stop_reason\":\"end_turn\"}},\"usage\":{{\"input_tokens\":{input_tokens},\"output_tokens\":4,\"cache_read_input_tokens\":{cache_read_input_tokens}}}}}\n\n"+ );+ let stop =+ b"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n";+ let frames: Vec<Vec<u8>> = vec![+ start.into_bytes(),+ delta.into_bytes(),+ stop.to_vec(),+ ];+ for f in frames {+ if tx.send(Ok(Frame::data(Bytes::from(f)))).await.is_err() {+ return;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ });+ let stream = tokio_stream::wrappers::ReceiverStream::new(rx);+ let body = StreamBody::new(stream);+ Ok::<_, Infallible>(+ Response::builder()+ .status(200)+ .header("content-type", "text/event-stream")+ .body(body)+ .unwrap(),+ )+ }),+ )+ .await;+ });+ }+ });+ (addr, task)+}++#[tokio::test]+async fn cache_hit_rate_emitted_per_session() {+ // Pick unusual token counts so the histogram bucket we land in+ // is identifiable across parallel test runs.+ // input=200, cache_read=800 → denom=1000, rate=0.8 (falls into the+ // [0.75, 0.9] bucket).+ let (addr, _server) = anthropic_streaming_upstream(800, 200).await;+ let proxy = start_proxy_with(&format!("http://{addr}"), |c| {+ c.compression_mode = headroom_proxy::config::CompressionMode::Off;+ })+ .await;++ let body = json!({+ "model": "claude-3-haiku-20240307",+ "stream": true,+ "max_tokens": 8,+ "messages": [{"role":"user","content":"hi"}]+ });+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/messages", proxy.url()))+ .header("content-type", "application/json")+ .header("accept", "text/event-stream")+ .body(serde_json::to_vec(&body).unwrap())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);+ // Drain so the state-machine task observes message_stop and emits.+ let _ = resp.bytes().await.unwrap();+ // Give the spawned state-machine task time to close + observe.+ tokio::time::sleep(Duration::from_millis(80)).await;++ let scrape = scrape_metrics(&proxy.url()).await;+ // The histogram exposes _bucket / _sum / _count rows. We assert+ // that at least one sample was observed for our provider label —+ // exact bucket assertions are fragile; the _count line is the+ // load-bearing one.+ let count = find_value_with_labels(+ &scrape,+ "proxy_cache_hit_rate_per_session_count",+ &[("provider", "anthropic")],+ )+ .expect("histogram count must appear after first session");+ assert!(+ count >= 1.0,+ "expected ≥1 observation on anthropic label; got {count}"+ );+ let sum = find_value_with_labels(+ &scrape,+ "proxy_cache_hit_rate_per_session_sum",+ &[("provider", "anthropic")],+ )+ .expect("histogram sum must appear after first session");+ // We seeded denom=1000, cache_read=800 → rate=0.8; the sum+ // includes this observation. Other concurrent tests may+ // contribute via the same `provider=anthropic` label; assert+ // sum > 0 rather than equality.+ assert!(+ sum > 0.0,+ "histogram sum must reflect at least one observed rate > 0; saw {sum}"+ );++ proxy.shutdown().await;+}++// ============================================================================+// Test 2: compression_ratio_emitted_per_strategy+// ============================================================================+//+// Exercise the helper directly — the integration path requires+// live-zone compression to actually trigger, which depends on+// content size + tokenizer thresholds. We assert the metric+// registration + emit-helper pair lands rows in the registry under+// the documented labels, which is the load-bearing observability+// surface for Phase H.++#[tokio::test]+async fn compression_ratio_emitted_per_strategy() {+ // Use a label tuple unique to this test so parallel runs over+ // the global registry don't cross-contaminate.+ const TEST_STRATEGY: &str = "integration_strategy_metric_test_v1";+ const TEST_CONTENT_TYPE: &str = "integration_content_type_metric_test_v1";++ observability::observe_compression_ratio(TEST_STRATEGY, TEST_CONTENT_TYPE, 1000, 250);+ // Drive the rejected counter on the same strategy so its row+ // also appears in the scrape.+ observability::record_compression_rejected_by_token_check(TEST_STRATEGY);++ // Spin up a proxy purely to expose /metrics — the helpers above+ // already incremented the global registry.+ let proxy = start_proxy_with("http://127.0.0.1:1", |_| {}).await;+ let scrape = scrape_metrics(&proxy.url()).await;++ let ratio_count = find_value_with_labels(+ &scrape,+ "proxy_compression_ratio_by_strategy_count",+ &[+ ("strategy", TEST_STRATEGY),+ ("content_type", TEST_CONTENT_TYPE),+ ],+ )+ .expect("ratio histogram count row must appear");+ assert!(ratio_count >= 1.0);++ let rejected = find_value_with_labels(+ &scrape,+ "proxy_compression_rejected_by_token_check_total",+ &[("strategy", TEST_STRATEGY)],+ )+ .expect("rejected counter row must appear");+ assert!(rejected >= 1.0);++ proxy.shutdown().await;+}++// ============================================================================+// Test 3: passthrough_bytes_modified_zero_when_no_compression+// ============================================================================+//+// End-to-end passthrough request with `CompressionMode::Off` — the+// counter must NOT have advanced. We assert the metric advertises+// itself (HELP/TYPE in the scrape) and has the alarm-able value of 0+// for the `/v1/messages` path label.++async fn anthropic_simple_non_stream_upstream() -> (SocketAddr, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let task = tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ break;+ };+ tokio::spawn(async move {+ let io = TokioIo::new(stream);+ let _ = hyper::server::conn::http1::Builder::new()+ .serve_connection(+ io,+ service_fn(|_req: Request<hyper::body::Incoming>| async move {+ Ok::<_, Infallible>(+ Response::builder()+ .status(200)+ .header("content-type", "application/json")+ .body(http_body_util::Full::new(Bytes::from_static(+ b"{\"id\":\"msg_1\",\"content\":[]}",+ )))+ .unwrap(),+ )+ }),+ )+ .await;+ });+ }+ });+ (addr, task)+}++#[tokio::test]+async fn passthrough_bytes_modified_zero_when_no_compression() {+ let (addr, _server) = anthropic_simple_non_stream_upstream().await;+ let proxy = start_proxy_with(&format!("http://{addr}"), |c| {+ c.compression_mode = headroom_proxy::config::CompressionMode::Off;+ })+ .await;++ let body = json!({+ "model": "claude-3-haiku-20240307",+ "max_tokens": 8,+ "messages": [{"role":"user","content":"hi"}]+ });+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/messages", proxy.url()))+ .header("content-type", "application/json")+ .body(serde_json::to_vec(&body).unwrap())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let scrape = scrape_metrics(&proxy.url()).await;+ // The `prometheus` crate v0.13 skips empty MetricVecs entirely+ // in `gather()` — neither HELP/TYPE nor rows appear until the+ // counter has been incremented with at least one label-set.+ // For the "must stay 0" alarm-able metric this absence IS the+ // signal: if the counter is silent, no passthrough policy has+ // been violated. The PromQL alarm queries+ // `rate(proxy_passthrough_bytes_modified_total[5m]) > 0`, which+ // is `0` (the metric doesn't exist) by definition.+ let any_row = scrape+ .lines()+ .any(|l| l.starts_with("proxy_passthrough_bytes_modified_total{"));+ assert!(+ !any_row,+ "counter should have no rows when nothing modified passthrough; got: {scrape}"+ );+ // The HELP/TYPE descriptor is registered eagerly in+ // `handle_metrics`, but `gather()` skips empty families so the+ // descriptor only surfaces after the first emit. We assert the+ // counter is reachable via the public helper to pin behaviour+ // (the helper is what the SSE/handler emit sites call).+ use headroom_proxy::observability::record_passthrough_bytes_modified;+ record_passthrough_bytes_modified(+ "/integration_test_passthrough_synthetic",+ 0,+ "integration_test_request_id_passthrough_v1",+ );+ // After a (zero-delta) increment, the row should appear.+ let scrape_after_touch = scrape_metrics(&proxy.url()).await;+ assert!(+ scrape_after_touch.contains("# HELP proxy_passthrough_bytes_modified_total"),+ "scrape missing proxy_passthrough_bytes_modified_total HELP after touch"+ );+ assert!(+ scrape_after_touch.contains("# TYPE proxy_passthrough_bytes_modified_total counter"),+ "scrape missing proxy_passthrough_bytes_modified_total TYPE after touch"+ );++ proxy.shutdown().await;+}++// ============================================================================+// Test 4: service_tier_logged+// ============================================================================+//+// Drive a `/v1/responses` request with `service_tier: "priority"`;+// the handler emits the service-tier counter at the boundary.++async fn responses_passthrough_upstream() -> (SocketAddr, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let task = tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ break;+ };+ tokio::spawn(async move {+ let io = TokioIo::new(stream);+ let _ = hyper::server::conn::http1::Builder::new()+ .serve_connection(+ io,+ service_fn(|_req: Request<hyper::body::Incoming>| async move {+ Ok::<_, Infallible>(+ Response::builder()+ .status(200)+ .header("content-type", "application/json")+ .body(http_body_util::Full::new(Bytes::from_static(+ b"{\"id\":\"resp_1\",\"output\":[]}",+ )))+ .unwrap(),+ )+ }),+ )+ .await;+ });+ }+ });+ (addr, task)+}++#[tokio::test]+async fn service_tier_logged() {+ let (addr, _server) = responses_passthrough_upstream().await;+ let proxy = start_proxy_with(&format!("http://{addr}"), |c| {+ c.compression_mode = headroom_proxy::config::CompressionMode::Off;+ c.enable_responses_streaming = true;+ })+ .await;++ // Unique tier value so this test owns its own row.+ const TEST_TIER: &str = "integration_test_tier_priority_v1";+ let body = json!({+ "model": "gpt-5",+ "service_tier": TEST_TIER,+ "input": [+ {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}+ ]+ });+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(serde_json::to_vec(&body).unwrap())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);+ let _ = resp.bytes().await.unwrap();++ let scrape = scrape_metrics(&proxy.url()).await;+ let tier_count = find_value_with_labels(+ &scrape,+ "proxy_service_tier_count_total",+ &[("tier", TEST_TIER)],+ )+ .expect("service tier counter row must appear");+ assert!(+ tier_count >= 1.0,+ "expected ≥1 service_tier increment; got {tier_count}"+ );++ proxy.shutdown().await;+}++// ============================================================================+// Test 5: incomplete_status_logged_with_reason+// ============================================================================+//+// Drive the `ResponseState` directly with a `response.incomplete`+// event payload. The state machine should capture+// `incomplete_details.reason` and `terminal_status()` should return+// `"incomplete"`. Wiring the metric counter is exercised by the+// `record_response_status` helper.++#[tokio::test]+async fn incomplete_status_logged_with_reason() {+ let mut framer = SseFramer::new();+ let mut state = ResponseState::new();++ let payload = b"event: response.incomplete\ndata: {\"type\":\"response.incomplete\",\"response\":{\"id\":\"resp_inc\",\"incomplete_details\":{\"reason\":\"max_output_tokens\"},\"service_tier\":\"integration_test_tier_incomplete_v1\"}}\n\n";+ framer.push(payload);+ while let Some(ev) = framer.next_event() {+ let ev = ev.expect("frame parses");+ state.apply(ev).expect("apply succeeds");+ }++ assert_eq!(+ state.incomplete_reason.as_deref(),+ Some("max_output_tokens"),+ "incomplete_details.reason must be captured"+ );+ assert_eq!(state.terminal_status(), Some("incomplete"));+ assert_eq!(+ state.service_tier.as_deref(),+ Some("integration_test_tier_incomplete_v1"),+ "service_tier must be captured on incomplete responses"+ );++ // Drive the metric helper and assert the row.+ observability::record_response_status(+ state.terminal_status().unwrap(),+ state.incomplete_reason.as_deref(),+ "integration_test_request_id_incomplete_v1",+ );++ let proxy = start_proxy_with("http://127.0.0.1:1", |_| {}).await;+ let scrape = scrape_metrics(&proxy.url()).await;+ let count = find_value_with_labels(+ &scrape,+ "proxy_response_status_count_total",+ &[("status", "incomplete")],+ )+ .expect("response status counter row must appear");+ assert!(count >= 1.0);++ proxy.shutdown().await;+}++// ============================================================================+// Bonus coverage: rate-limit gauge plumbing via the public helper.+// ============================================================================++#[tokio::test]+async fn rate_limit_snapshot_emits_gauges() {+ let snap = observability::RateLimitSnapshot {+ remaining_requests: Some(123),+ remaining_tokens: Some(45678),+ remaining_input_tokens: Some(30000),+ remaining_output_tokens: Some(15000),+ };+ observability::record_rate_limit_snapshot(+ observability::cache_hit_rate_provider::ANTHROPIC,+ &snap,+ "integration_test_rate_limit_v1",+ );++ let proxy = start_proxy_with("http://127.0.0.1:1", |_| {}).await;+ let scrape = scrape_metrics(&proxy.url()).await;++ // Every gauge advertises itself; the rows we just set must+ // appear with our exact values (gauges, unlike counters, are+ // last-write-wins so this is deterministic).+ let v = find_value_with_labels(+ &scrape,+ "proxy_rate_limit_remaining_requests",+ &[("provider", "anthropic")],+ )+ .expect("requests gauge row");+ assert!(v >= 1.0);+ let v = find_value_with_labels(+ &scrape,+ "proxy_rate_limit_remaining_tokens",+ &[("provider", "anthropic")],+ )+ .expect("tokens gauge row");+ assert!(v >= 1.0);++ proxy.shutdown().await;+}diff --git a/docs/observability.md b/docs/observability.mdnew file mode 100644index 000000000..9582f1302--- /dev/null+++ b/docs/observability.md@@ -0,0 +1,121 @@+# Observability — proxy metrics++The Headroom Rust proxy exposes Prometheus-format metrics on the+`/metrics` endpoint of every running proxy instance. The metric+catalogue below covers Phase D (Bedrock route instrumentation) and+Phase G PR-G3 (per-invocation RTK + proxy-wide observability).++All metric names + label keys are constants in+`crates/headroom-proxy/src/observability/metric_names.rs`, so any+rename catches one file in code review.++## Metric catalogue++### Bedrock route (Phase D PR-D3)++| Name | Type | Labels | Purpose |+|------|------|--------|---------|+| `bedrock_invoke_count_total` | Counter | `model`, `region`, `auth_mode` | One increment per Bedrock `/invoke` or `/converse` request. |+| `bedrock_invoke_latency_seconds` | Histogram | `model`, `region` | Latency from proxy entry to upstream completion. Buckets target 50ms–60s. |+| `bedrock_eventstream_message_count_total` | Counter | `model`, `region`, `event_type` | One increment per parsed binary EventStream message. |++### Proxy-wide (Phase G PR-G3)++#### Cache + compression++| Name | Type | Labels | Purpose |+|------|------|--------|---------|+| `proxy_cache_hit_rate_per_session` | Histogram | `provider` | Per-session cache hit rate. **Phase H canary gate.** |+| `proxy_compression_ratio_by_strategy` | Histogram | `strategy`, `content_type` | `compressed_tokens / original_tokens` per shrunk block. |+| `proxy_compression_rejected_by_token_check_total` | Counter | `strategy` | Compressor ran but failed the shrink check. |++#### Cache-safety alarm++| Name | Type | Labels | Purpose |+|------|------|--------|---------|+| `proxy_passthrough_bytes_modified_total` | Counter | `path` | Bytes mutated on a passthrough path. **Must stay 0 outside the compression hot path** — any non-zero rate fires the cache-safety alarm. |++#### Upstream rate limits++| Name | Type | Labels | Purpose |+|------|------|--------|---------|+| `proxy_rate_limit_remaining_requests` | Gauge | `provider` | Last-seen remaining requests in the current window. |+| `proxy_rate_limit_remaining_tokens` | Gauge | `provider` | Last-seen remaining tokens in the current window. |+| `proxy_rate_limit_remaining_input_tokens` | Gauge | `provider` | Anthropic-only input-token bucket. |+| `proxy_rate_limit_remaining_output_tokens` | Gauge | `provider` | Anthropic-only output-token bucket. |++#### OpenAI Responses telemetry++| Name | Type | Labels | Purpose |+|------|------|--------|---------|+| `proxy_service_tier_count_total` | Counter | `tier` | Service-tier distribution observed at the proxy. |+| `proxy_response_status_count_total` | Counter | `status` | Terminal status distribution (`completed`, `incomplete`, `failed`, `cancelled`, `in_progress`). |++#### Wrap CLI / RTK++| Name | Type | Labels | Purpose |+|------|------|--------|---------|+| `wrap_rtk_invocations_total` | Counter | `tool` | RTK invocations observed via `rtk gain --format json` polling. Driven from the wrap-CLI tail. |++#### Image log redaction++| Name | Type | Labels | Purpose |+|------|------|--------|---------|+| `proxy_image_generation_call_log_redacted_total` | Counter | _none_ | Base64-encoded image payloads redacted from request logs. |++## How to query++The proxy renders Prometheus text-format on `GET /metrics`:++```bash+curl -s http://127.0.0.1:8787/metrics+```++Common PromQL queries:++```promql+# Phase H canary gate — cache hit rate parity vs Python proxy.+histogram_quantile(0.50, sum by (le) (rate(proxy_cache_hit_rate_per_session_bucket[5m])))++# Cache-safety alarm. Should always be 0.+sum(rate(proxy_passthrough_bytes_modified_total[5m]))++# Aggregate compression value by strategy.+histogram_quantile(0.50, sum by (strategy, le) (rate(proxy_compression_ratio_by_strategy_bucket[1h])))++# Upstream rate-limit headroom (smaller = closer to throttle).+proxy_rate_limit_remaining_tokens{provider="anthropic"}+```++## Wiring++Every metric registration is `OnceLock`-backed and lazy: the first+call to a `*_counter()` / `*_gauge()` / `*_histogram()` helper+registers the family with the shared registry. `handle_metrics`+force-touches every Phase G PR-G3 family before scraping so the+descriptors are reachable from `/metrics` on a fresh boot — note that+the `prometheus` crate v0.13 skips empty MetricVecs from `gather()`,+so HELP/TYPE only surface once a family has been incremented at+least once.++## Cardinality discipline++Every label vocabulary is bounded by code, not customer input:++- `model` / `region`: read from path params + `Config::bedrock_region`.+- `auth_mode`: 3-variant enum (`payg`, `oauth`, `subscription`).+- `provider`: 3 values (`anthropic`, `openai_chat`, `openai_responses`).+- `strategy`: `&'static str` from the compressor's `BlockAction::Compressed`.+- `content_type`: `&'static str` from `headroom_core::transforms::ContentType`.+- `tier`: bounded by OpenAI Responses spec.+- `status`: 5-variant enum.++There is no code path where a malicious client can drive label+cardinality unbounded.++## See also++- `docs/rtk-architecture.md` — why RTK lives wrap-side, not proxy-side.+- `crates/headroom-proxy/src/observability/` — implementation.+- `REALIGNMENT/09-phase-G-rtk-observability.md` — spec.+- `REALIGNMENT/10-phase-H-python-retirement.md` — H1 acceptance gate.diff --git a/docs/rtk-architecture.md b/docs/rtk-architecture.mdnew file mode 100644index 000000000..35ff9aadf--- /dev/null+++ b/docs/rtk-architecture.md@@ -0,0 +1,122 @@+# RTK architecture — why wrap-CLI only++**Status:** decided. Locked at Phase G PR-G3 (2026-05).+**Owner:** Headroom realignment.++## TL;DR++**RTK is a wrap-CLI hook, not a proxy-side compressor.** The Headroom+proxy does NOT invoke RTK on tool-result content. Future contributors+who consider moving RTK into the proxy hot path: read this doc first.++## Background++RTK (Realtime Token Kompress) rewrites shell **commands** at exec+time so that a `git diff` or `grep` invocation emits a more+compressed output before the agent ever ingests it. RTK runs in the+wrap-CLI tail — `headroom wrap claude`, `headroom wrap codex`, etc.+— where it installs a `~/.rtk/bin/rtk` shim ahead of the agent CLI+and intercepts shelled-out subprocesses.++It surfaces value in two places:+1. **Tokens saved per invocation** — measured by `rtk gain --format json`.+2. **Tokens saved per session** — aggregated at wrap-session end.++Both signals feed `wrap_rtk_invocations_total` and+`wrap_rtk_tokens_saved_per_session` (registered by the Rust proxy's+observability surface so a single `/metrics` scrape exposes the full+picture).++## Proxy-side RTK was considered and rejected++At Phase G scoping, three reviewers floated the idea of invoking+RTK on the **proxy** side: when a `tool_result` block flows+upstream, dispatch it through RTK to shrink the content before it+hits the model.++**Decision: rejected.** Three load-bearing reasons.++### 1. Cache hot zone risk++The proxy's Phase B cache-safety contract pins `tool_result`+content as part of the cache hot zone. Compression there bursts+the prompt cache because the rewritten bytes diverge from the+canonical wire bytes the upstream cached. Phase B PR-B2 → PR-B7+spent ~3000 LOC carving the live-zone-only surface specifically+to prevent this class of cache-invalidation. Inserting RTK+proxy-side would re-introduce it.++### 2. Parallel implementation with `log_compressor.rs`++The Rust proxy already has a `crates/headroom-core/src/transforms/log_compressor.rs`+that compresses **tool output text** in the live zone. It uses the+same heuristics RTK uses (whitespace de-dup, line de-dup,+file-listing collapse) but invoked at the proxy's per-block+dispatcher rather than at the shell exec boundary. Adding RTK+proxy-side would mean two implementations of the same compression+in the same hot path; "no silent fallbacks, no parallel impls" is+explicit project policy.++### 3. Command-rewrite vs output-rewrite — different value propositions++RTK rewrites **commands** before they execute. The+`git log --oneline` you typed becomes `git log --oneline -n 50`+because RTK has learned that the first 50 commits are usually+enough context. That's a fundamentally different mechanism from+compressing the **output** of an unmodified command. A proxy-side+invocation would skip the command-rewrite half — the half that+generates the largest savings on heavy shell workloads — and only+catch the output side, which is already covered by+`log_compressor` and `code_compressor`.++## What the proxy does provide++Per Phase G PR-G3, the proxy exposes RTK-derived metrics via its+registry:++- `wrap_rtk_invocations_total{tool}` — driven by the wrap-CLI+ polling `rtk gain --format json` and incrementing the registered+ counter by the delta since last poll.+- `wrap_rtk_tokens_saved_per_session` — emitted at wrap-session+ close.++This keeps the operator dashboard single-pane-of-glass without+re-implementing RTK inside the proxy.++## What the wrap CLI does++Every `headroom wrap <agent>` subcommand:++1. Ensures the RTK binary is installed via `_ensure_rtk_binary()`.+2. Injects the `<!-- headroom:rtk-instructions -->` block into the+ agent's instruction file (e.g. `AGENTS.md`, `.cursorrules`).+3. Spawns the proxy and the agent CLI side-by-side.+4. Polls `rtk gain --format json` on a 5-second memoization window+ and feeds the delta into the proxy's metric registry.++See `headroom/cli/wrap/` for the per-agent shims.++## Re-litigation policy++A change to this architecture should:++1. Quote the live-zone-only contract from+ `REALIGNMENT/04-phase-B-live-zone.md` and explain why the+ cache-burst risk is acceptable.+2. Show measurements (not estimates) that proxy-side RTK adds value+ beyond `log_compressor.rs` on real production traffic.+3. Have an exit ramp: a CLI flag to disable proxy-side RTK without+ reverting the wrap-CLI integration.++Without all three, treat the proposal as a regression and link this+doc.++## References++- `REALIGNMENT/09-phase-G-rtk-observability.md` — Phase G plan.+- `REALIGNMENT/04-phase-B-live-zone.md` — cache hot-zone contract.+- `headroom/cli/wrap/` — wrap-CLI implementation.+- `crates/headroom-core/src/transforms/log_compressor.rs` — the+ proxy-side log compressor RTK would parallel.+- 2026-05-01 user direction message archived in+ `project_compression_realignment_2026_05` memory note.diff --git a/headroom/proxy/request_logger.py b/headroom/proxy/request_logger.pyindex e6fd8690a..a29b49871 100644--- a/headroom/proxy/request_logger.py+++ b/headroom/proxy/request_logger.py@@ -3,6 +3,11 @@Logs requests to an in-memory deque and optionally to a JSONL file.Extracted from server.py for maintainability.++Phase G PR-G3 (P4-45): base64-encoded image payloads in the+``request_messages`` / ``response_content`` are redacted before+write to keep request logs small. Multi-MB base64 strings would+otherwise saturate the JSONL log and the in-memory deque."""from __future__ import annotations@@ -11,9 +16,10 @@ import jsonimport loggingimport sysfrom collections import deque+from collections.abc import Mapping, Sequencefrom dataclasses import asdictfrom pathlib import Path-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyif TYPE_CHECKING:from ..memory.tracker import ComponentStats@@ -22,6 +28,98 @@ from headroom.proxy.models import RequestLoglogger = logging.getLogger(__name__)+# Phase G PR-G3 — base64 redaction threshold (P4-45).+#+# Anthropic image blocks carry base64-encoded JPEGs/PNGs in+# ``source.data``; OpenAI's vision shape carries them in+# ``image_url.url`` as a ``data:image/...;base64,<payload>`` URL.+# The threshold gates "real image payload" against short base64+# strings (which can appear in arguments, signatures, etc.).+IMAGE_BASE64_REDACT_THRESHOLD_BYTES = 1024++# Phase G PR-G3 — replacement-marker format. Operators can grep the+# JSONL for ``<image:base64-redacted`` to count the redactions; the+# byte count keeps cost attribution honest even after redaction.+IMAGE_BASE64_REPLACEMENT_TEMPLATE = "<image:base64-redacted bytes={n}>"++# Constants for log redaction counter export (Prometheus). The Rust+# proxy owns the canonical metric; the Python side increments a+# best-effort module-level counter so tests and the in-process+# ``/stats`` endpoint can read back the redaction rate.+_redactions_total: int = 0+++def redactions_total() -> int:+ """Return the running count of base64 redactions performed.++ Exposed for unit tests + the legacy Python ``/stats`` endpoint.+ The canonical observability surface is the Rust proxy's+ ``proxy_image_generation_call_log_redacted_total`` metric.+ """+ return _redactions_total+++def _looks_like_base64_image(value: str) -> bool:+ """Heuristic: does ``value`` look like a base64-encoded image?++ Two patterns we recognise:++ * Raw base64 over the threshold (Anthropic ``source.data`` shape).+ * ``data:image/<subtype>;base64,<payload>`` data URLs (OpenAI+ vision shape). The ``;base64,`` substring is the load-bearing+ signal — any data URL with that segment over the threshold gets+ redacted, even if the MIME type isn't ``image/...`` (because+ the cost-of-logging is paid the same way).++ Returns ``False`` for short strings (under the threshold) and for+ any non-string value. Per realignment build-constraint "no+ regexes", we use prefix/substring checks instead of pattern+ matching.+ """+ if not isinstance(value, str):+ return False+ if len(value) < IMAGE_BASE64_REDACT_THRESHOLD_BYTES:+ return False+ if value.startswith("data:") and ";base64," in value[:64]:+ return True+ # Bare base64 payload: heuristic — over-threshold string with no+ # whitespace and a high alpha-num+/+= density. We sample the first+ # 256 bytes for speed (the full string can be megabytes).+ head = value[:256]+ base64_chars = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")+ matches = sum(1 for ch in head if ch in base64_chars)+ return matches / len(head) > 0.95+++def _redact_value(value: Any) -> Any:+ """Recursively redact base64-image payloads in a JSON-ish value.++ Returns a new structure with any over-threshold base64 string+ replaced by the placeholder. Non-string, non-container values+ pass through unchanged.+ """+ global _redactions_total+ if isinstance(value, str):+ if _looks_like_base64_image(value):+ _redactions_total += 1+ return IMAGE_BASE64_REPLACEMENT_TEMPLATE.format(n=len(value))+ return value+ if isinstance(value, Mapping):+ return {k: _redact_value(v) for k, v in value.items()}+ if isinstance(value, Sequence) and not isinstance(value, str | bytes | bytearray):+ return [_redact_value(item) for item in value]+ return value+++def redact_image_base64(payload: Any) -> Any:+ """Public entry point for base64-image redaction.++ Walks ``payload`` (a dict, list, or string) and replaces any+ over-threshold base64 string with a size-only placeholder.+ Idempotent — applying twice yields the same structure.+ """+ return _redact_value(payload)+class RequestLogger:"""Log requests to JSONL file.@@ -51,7 +149,23 @@ class RequestLogger:self.log_file = Nonedef log(self, entry: RequestLog):- """Log a request. Oldest entries are automatically removed when limit reached."""+ """Log a request. Oldest entries are automatically removed when limit reached.++ Phase G PR-G3 (P4-45): base64-encoded image payloads in+ ``request_messages`` / ``response_content`` are redacted+ before write. Redaction also applies to the in-memory deque+ so the ``/stats/recent_requests`` endpoint never serves a+ multi-MB image either.+ """+ # Redact image payloads in-place on the deque entry so memory+ # use stays bounded. We mutate the dataclass fields rather+ # than wrapping the entry to keep ``get_recent`` /+ # ``get_recent_with_messages`` unchanged.+ if entry.request_messages is not None:+ entry.request_messages = redact_image_base64(entry.request_messages)+ if entry.response_content is not None:+ entry.response_content = redact_image_base64(entry.response_content)+self._logs.append(entry)if self.log_file:diff --git a/tests/test_image_log_redaction.py b/tests/test_image_log_redaction.pynew file mode 100644index 000000000..cd6bf9c60--- /dev/null+++ b/tests/test_image_log_redaction.py@@ -0,0 +1,210 @@+"""Phase G PR-G3 (P4-45) — request-logger image base64 redaction.++The Headroom proxy logs LLM request/response payloads to a JSONL feed+when ``log_full_messages=True``. Vision-shape requests (Anthropic+``image`` blocks; OpenAI ``image_url`` data URLs) carry base64-encoded+binary payloads that can be multiple megabytes each. Phase G PR-G3+replaces those over-threshold strings with a size-only placeholder so+the JSONL and the in-memory deque stay bounded.++These tests cover the redaction primitive in isolation (no proxy+required). The Rust ``proxy_image_generation_call_log_redacted_total``+counter is exercised by the Rust integration suite; this file owns the+Python contract.+"""++from __future__ import annotations++import base64+import json+import os+import tempfile++import pytest++from headroom.proxy.models import RequestLog+from headroom.proxy.request_logger import (+ IMAGE_BASE64_REDACT_THRESHOLD_BYTES,+ IMAGE_BASE64_REPLACEMENT_TEMPLATE,+ RequestLogger,+ redact_image_base64,+ redactions_total,+)+++def _big_base64(byte_size: int) -> str:+ """Produce a deterministic base64 string of exactly ``byte_size`` chars."""+ raw = os.urandom(max(byte_size, 1))+ encoded = base64.b64encode(raw).decode("ascii")+ return encoded[:byte_size].ljust(byte_size, "A")+++def _make_request_log(*, request_messages=None, response_content=None) -> RequestLog:+ return RequestLog(+ request_id="req-test",+ timestamp="2026-05-21T00:00:00Z",+ provider="anthropic",+ model="claude-3-5-sonnet-20240620",+ input_tokens_original=100,+ input_tokens_optimized=100,+ output_tokens=20,+ tokens_saved=0,+ savings_percent=0.0,+ optimization_latency_ms=0.0,+ total_latency_ms=10.0,+ tags={},+ cache_hit=False,+ transforms_applied=[],+ request_messages=request_messages,+ response_content=response_content,+ )+++def test_large_base64_truncated():+ """A multi-MB base64 payload in a request message is replaced with+ a size-only placeholder. This is the load-bearing assertion from+ REALIGNMENT/09-phase-G-rtk-observability.md:155."""+ big = _big_base64(IMAGE_BASE64_REDACT_THRESHOLD_BYTES * 4)+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "describe this image"},+ {+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": "image/png",+ "data": big,+ },+ },+ ],+ }+ ]+ redacted = redact_image_base64(messages)+ payload = redacted[0]["content"][1]["source"]["data"]+ assert IMAGE_BASE64_REPLACEMENT_TEMPLATE.format(n=len(big)) == payload+ # The non-image fields must survive verbatim — redaction must+ # never perturb the structure outside the targeted payload.+ assert redacted[0]["content"][0] == {"type": "text", "text": "describe this image"}+++def test_short_base64_passes_through():+ """A short base64-looking string (e.g. a 64-byte signature, a tool+ ``id``) must NOT be redacted — the threshold gates real image+ payloads against legitimate small strings."""+ short = _big_base64(64)+ assert len(short) < IMAGE_BASE64_REDACT_THRESHOLD_BYTES+ messages = [{"role": "user", "content": [{"type": "text", "text": short}]}]+ redacted = redact_image_base64(messages)+ assert redacted[0]["content"][0]["text"] == short+++def test_data_url_redacted():+ """OpenAI vision shape: ``data:image/png;base64,<payload>`` URLs+ are redacted when the payload is over the threshold."""+ payload = _big_base64(IMAGE_BASE64_REDACT_THRESHOLD_BYTES * 2)+ data_url = f"data:image/png;base64,{payload}"+ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "image_url",+ "image_url": {"url": data_url},+ }+ ],+ }+ ]+ redacted = redact_image_base64(messages)+ final_url = redacted[0]["content"][0]["image_url"]["url"]+ assert final_url == IMAGE_BASE64_REPLACEMENT_TEMPLATE.format(n=len(data_url))+++def test_redact_idempotent():+ """Applying redaction twice yields the same structure — the+ placeholder is short enough to stay below the threshold so the+ second pass is a no-op."""+ big = _big_base64(IMAGE_BASE64_REDACT_THRESHOLD_BYTES * 3)+ once = redact_image_base64({"data": big})+ twice = redact_image_base64(once)+ assert once == twice+++def test_logger_writes_redacted_payload_to_jsonl():+ """End-to-end: writing a RequestLog with a big base64 payload via+ ``RequestLogger.log`` produces a JSONL line that does NOT contain+ the raw payload."""+ with tempfile.TemporaryDirectory() as tmpdir:+ log_path = os.path.join(tmpdir, "requests.jsonl")+ logger = RequestLogger(log_file=log_path, log_full_messages=True)+ big = _big_base64(IMAGE_BASE64_REDACT_THRESHOLD_BYTES * 5)+ entry = _make_request_log(+ request_messages=[+ {+ "role": "user",+ "content": [+ {+ "type": "image",+ "source": {"type": "base64", "data": big},+ }+ ],+ }+ ]+ )+ logger.log(entry)+ with open(log_path) as f:+ line = f.read().strip()+ parsed = json.loads(line)+ # The raw base64 string must NOT appear in the JSONL line.+ assert big not in line, "raw base64 leaked into JSONL"+ # The placeholder must appear.+ assert "image:base64-redacted" in line+ # The structure must remain intact.+ data_field = parsed["request_messages"][0]["content"][0]["source"]["data"]+ assert data_field == IMAGE_BASE64_REPLACEMENT_TEMPLATE.format(n=len(big))+++def test_response_content_redacted():+ """``response_content`` (a string field) is redacted in-place on+ the deque entry."""+ logger = RequestLogger(log_file=None, log_full_messages=True)+ big = _big_base64(IMAGE_BASE64_REDACT_THRESHOLD_BYTES * 3)+ entry = _make_request_log(response_content=big)+ logger.log(entry)+ recent = logger.get_recent_with_messages(n=1)+ assert recent[0]["response_content"] == IMAGE_BASE64_REPLACEMENT_TEMPLATE.format(n=len(big))+++def test_redactions_counter_advances():+ """``redactions_total`` increases by one per redacted payload."""+ before = redactions_total()+ big = _big_base64(IMAGE_BASE64_REDACT_THRESHOLD_BYTES * 2)+ redact_image_base64({"data": big})+ after = redactions_total()+ assert after == before + 1+++def test_none_payload_safe():+ """``RequestLogger.log`` must not crash when ``request_messages``+ or ``response_content`` is None — many requests have neither."""+ logger = RequestLogger(log_file=None, log_full_messages=True)+ entry = _make_request_log(request_messages=None, response_content=None)+ logger.log(entry) # must not raise+ assert len(logger.get_recent(n=1)) == 1+++ "value",+ [+ 12345,+ None,+ True,+ 3.14,+ b"not-a-string",+ ],+)+def test_non_string_values_pass_through(value):+ """The redactor walks JSON-ish structures only; primitives that+ aren't strings must round-trip verbatim."""+ assert redact_image_base64(value) == value