Merge branch 'main' into fix/neo4j-relationship-type

This commit is contained in:
JD Davis
2026-11-17 01:49:07 -06:00
committed by GitHub
95 changed files with 6132 additions and 656 deletions
+44 -9
View File
@@ -54,9 +54,8 @@ at it; end users notice nothing.
make build-proxy
./target/release/headroom-proxy --help
# Run against a local upstream
# Run against a local upstream (listens on 127.0.0.1:8787 by default)
./target/release/headroom-proxy \
--listen 0.0.0.0:8787 \
--upstream http://127.0.0.1:8788
# Health checks
@@ -70,7 +69,10 @@ curl -s http://127.0.0.1:8787/healthz/upstream # => 200 if upstream reachable
# 1. Move the Python proxy to a private port (e.g. 8788)
HEADROOM_HOST=127.0.0.1 HEADROOM_PORT=8788 python -m headroom.proxy & # or your existing launcher
# 2. Run the Rust proxy on the previously-public port (8787) pointing at it
# 2. Run the Rust proxy on the previously-public port (8787) pointing at it.
# The Python proxy sees every relayed request as coming from 127.0.0.1,
# so the Rust proxy enforces HEADROOM_PROXY_TOKEN itself (see below).
export HEADROOM_PROXY_TOKEN="$(openssl rand -hex 32)"
./target/release/headroom-proxy --listen 0.0.0.0:8787 --upstream http://127.0.0.1:8788 &
# 3. End users keep hitting :8787 unchanged.
@@ -83,7 +85,8 @@ curl -si http://127.0.0.1:8787/v1/models
| Flag | Env var | Default | Notes |
| --- | --- | --- | --- |
| `--listen` | `HEADROOM_PROXY_LISTEN` | `0.0.0.0:8787` | bind address |
| `--listen` | `HEADROOM_PROXY_LISTEN` | `127.0.0.1:8787` | bind address; a non-loopback address refuses to start without `HEADROOM_PROXY_TOKEN` unless `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1` |
| `--proxy-token` | `HEADROOM_PROXY_TOKEN` | (unset) | inbound token required from non-loopback peers (below); prefer the env var |
| `--metrics-require-loopback` | `HEADROOM_PROXY_METRICS_REQUIRE_LOOPBACK` | `false` | when set, `/metrics` is served only to loopback peers (403 otherwise); recommended on non-loopback binds |
| `--upstream` | `HEADROOM_PROXY_UPSTREAM` | (required) | base URL the proxy forwards to |
| `--upstream-timeout` | | `600s` | end-to-end request timeout (long for streams) |
@@ -94,13 +97,43 @@ curl -si http://127.0.0.1:8787/v1/models
| `--graceful-shutdown-timeout` | | `30s` | wait for in-flight on SIGTERM/SIGINT |
| `--stats` | `HEADROOM_PROXY_STATS` | `true` | native savings stats + `/dashboard` (below) |
| `--stats-path` | `HEADROOM_PROXY_STATS_PATH` | `~/.headroom/native_stats.json` | ledger persistence (honours `HEADROOM_WORKSPACE_DIR`) |
| `--enable-bedrock-native` | `HEADROOM_PROXY_ENABLE_BEDROCK_NATIVE` | (unset: off) | `true` or `--features native_bedrock` mounts `/model/{id}/invoke`, `/converse` and the streaming variants; they sign every request with this host's AWS credentials and do not authenticate the caller |
| `--enable-vertex-native` | `HEADROOM_PROXY_ENABLE_VERTEX_NATIVE` | `false` | mount Vertex `:rawPredict` / `:streamRawPredict`; replaces the caller's `Authorization` with this host's Google ADC bearer (scope `--vertex-adc-scope`) and does not authenticate the caller |
| `--vertex-allow-non-google-upstream` | `HEADROOM_PROXY_VERTEX_ALLOW_NON_GOOGLE_UPSTREAM` | `false` | by default the Vertex route only sends the ADC bearer when `--upstream` is `https://*.googleapis.com`, and answers 502 otherwise |
### Inbound authentication
The Rust proxy connects to the Python proxy from `127.0.0.1`, and the
Python proxy trusts loopback callers (no token needed, and access to
`/admin`, `/debug` and `/settings`). So the Rust proxy applies the same
`HEADROOM_PROXY_TOKEN` rules itself, before anything is forwarded:
- With a token set, a non-loopback peer must send it as
`X-Headroom-Proxy-Token: <token>` or `Authorization: Bearer <token>`,
or gets `401 {"error":"unauthorized"}`. Loopback peers are exempt, as
in the Python proxy. The token is removed from the request before it
is forwarded (`Authorization` only when it carries the token).
- A caller that is not local here (a non-loopback peer, or a loopback
peer whose `Host` is not a loopback name) is never forwarded with a
`Host` that may name loopback (including scoped IPv6 such as
`[::1%lo]`), whatever `--rewrite-host` is and whatever the upstream
name resolves to: that `Host` is replaced with
`headroom-remote.invalid`, so the Python proxy's local-only routes
(`/admin`, `/debug`, `/settings`, ...) stay closed to it, with or
without a token.
- `GET /healthz`, `/healthz/upstream`, `/health`, `/livez` and `/readyz`
stay reachable without the token, and `GET`/`HEAD /api/hello` is
answered locally with an empty `200`.
- A non-loopback `--listen` with no token refuses to start. Set
`HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1` only when something else
already restricts who can reach the port.
### Savings stats & dashboard (native)
The Rust proxy records per-request savings/cost telemetry on every
lane it forwards — Anthropic `/v1/messages`, OpenAI Chat/Responses,
all four native Bedrock routes, and Vertex `rawPredict` /
`streamRawPredict` — and serves it locally (never tunnelled
`streamRawPredict` when those are enabled — and serves it locally (never tunnelled
upstream):
```bash
@@ -143,13 +176,15 @@ the hot path every 10 s and on shutdown.
> the numbers start flowing on their own.
> **No auth; exposure is split by tier.** These endpoints bind
> wherever `--listen` points (default `0.0.0.0:8787`) and carry no
> auth, so the payload is split the same way the Python proxy splits
> wherever `--listen` points (default `127.0.0.1:8787`) and, for
> loopback peers or with no `HEADROOM_PROXY_TOKEN`, carry no auth, so the payload is split the same way the Python proxy splits
> its own `/stats`:
>
> - **Aggregates** — spend, tokens, per-model/provider rollups,
> history — are served to anyone, like the Prometheus `/metrics`
> endpoint next door. Same data class, same stance.
> history — are served to any caller that gets past the inbound gate
> (above), like the Prometheus `/metrics` endpoint next door: with
> `HEADROOM_PROXY_TOKEN` set, remote callers need the token for these
> too; without it, they are open to anyone who can reach the port.
> - **Per-request rows** — `recent_requests`, all of `/stats/events`
> — plus the ledger's filesystem path are served **only to local
> callers**: loopback peer *and* a loopback `Host` header (the
+11 -2
View File
@@ -78,7 +78,8 @@ impl Feature {
Self::NativeBedrock => FeatureSpec {
name: "native_bedrock",
available_in: RolloutChannel::Stable,
default_enabled_in: Some(RolloutChannel::Stable),
// Signs requests with the host's AWS credentials: opt-in only.
default_enabled_in: None,
},
Self::OpenAiResponsesStreaming => FeatureSpec {
name: "openai_responses_streaming",
@@ -365,11 +366,19 @@ mod tests {
#[test]
fn default_enabled_feature_has_default_reason() {
let rollout = RolloutSnapshot::default();
let decision = rollout.decision(Feature::NativeBedrock);
let decision = rollout.decision(Feature::OpenAiResponsesStreaming);
assert!(decision.enabled);
assert_eq!(decision.reason, FeatureDecisionReason::Default);
}
#[test]
fn native_bedrock_is_not_on_by_default() {
let rollout = RolloutSnapshot::default();
let decision = rollout.decision(Feature::NativeBedrock);
assert!(!decision.enabled);
assert_eq!(decision.reason, FeatureDecisionReason::NotRequested);
}
#[test]
fn unsafe_override_crosses_boundary_and_is_ineligible() {
let rollout = RolloutSnapshot::from_parts("stable", "canary_probe", "", true);
@@ -865,10 +865,11 @@ impl CodeAwareCompressor {
// Unknown language → fallback (Kompress) or passthrough.
if detected_lang == CodeLanguage::Unknown {
// Kompress fallback is delegated to the live-zone dispatcher in
// the Rust port (the engine doesn't own the model); fixtures are
// recorded with fallback_to_kompress=False, so this is the
// passthrough branch.
// The Rust engine does not own the Kompress model, so this is
// always the passthrough branch (fixtures are recorded with
// fallback_to_kompress=False). The live-zone dispatcher leaves
// the declined block unchanged too: code is never handed to the
// prose model, which drops keywords (#4214).
return CodeCompressionResult {
language: CodeLanguage::Unknown,
language_confidence: 0.0,
@@ -58,9 +58,9 @@
//! per-content-type byte thresholds. The gate and the threshold
//! plumbing already shipped; **this PR** completes the item by wiring
//! the two remaining compressor arms — `SourceCode` →
//! CodeAwareCompressor (falling back to cached Kompress when the
//! compressor returns its input unchanged) and `PlainText` → cached
//! Kompress — and by moving the `SourceCode` / `PlainText` thresholds
//! CodeAwareCompressor (left unchanged when the compressor returns its
//! input unchanged: code is never handed to the prose model, #4214) and
//! `PlainText` → cached Kompress — and by moving the `SourceCode` / `PlainText` thresholds
//! off their placeholder 512 to the specified 2048 / 5120. `Html`
//! stays no-op.
//! - **PR-B7** wires CCR retrieval-marker injection.
@@ -133,10 +133,8 @@ const STRATEGY_SEARCH_COMPRESSOR: &str = "search_compressor";
const STRATEGY_DIFF_COMPRESSOR: &str = "diff_compressor";
/// Strategy tag emitted when CodeAwareCompressor rewrote a source-code block.
const STRATEGY_CODE_COMPRESSOR: &str = "code_compressor";
/// Strategy tag emitted when Kompress rewrote a plain-text block (also
/// used by the SourceCode arm's passthrough fallback — see
/// [`dispatch_compressor`]). Only the `ml` build has a Kompress arm to
/// emit it.
/// Strategy tag emitted when Kompress rewrote a plain-text block. Only
/// the `ml` build has a Kompress arm to emit it.
#[cfg(feature = "ml")]
const STRATEGY_KOMPRESS: &str = "kompress";
@@ -704,14 +702,9 @@ fn kompress_cached() -> Option<&'static Kompress> {
}
/// Route `text` through Kompress when the model is cache-resident;
/// otherwise fall back to a deterministic no-op. Shared by the
/// `PlainText` arm and the `SourceCode` arm's passthrough fallback.
///
/// Not a full port of the Python router's fallback chain: that one also
/// re-runs Kompress when the code compressor returns *changed but not
/// smaller* output, whereas this arm sends only an exact passthrough
/// here and leaves the changed-but-not-smaller case to the
/// tokenizer-rejection gate in `compress_one_block`.
/// otherwise fall back to a deterministic no-op. Only the `PlainText`
/// arm calls it: source code that the code compressor declines is
/// deliberately not routed here (Kompress drops keywords from code).
#[cfg(feature = "ml")]
fn kompress_or_noop(text: &str, content_type: ContentType) -> DispatchResult {
if let Some(k) = kompress_cached() {
@@ -805,10 +798,9 @@ fn warm_kompress_blocking() -> bool {
// arms to a deterministic no-op, bypassing their compressor entirely.
//
// One operator-facing caveat: granularity is per ARM, not per
// compressor. `plain_text` alone does not stop Kompress runs reached
// through the SourceCode arm's passthrough fallback; disabling
// `source_code` as well is what removes Kompress from traffic entirely
// (at the cost of also disabling the code compressor).
// compressor. Only the `PlainText` arm reaches Kompress, so disabling
// `plain_text` removes Kompress from traffic; `source_code` governs
// the code compressor alone.
/// Parse the comma-separated arm list. Blank entries are skipped;
/// unknown names are ignored with a warning rather than failing the
@@ -1637,8 +1629,8 @@ enum DispatchResult {
/// - `BuildOutput` → LogCompressor
/// - `SearchResults` → SearchCompressor
/// - `GitDiff` → DiffCompressor
/// - `SourceCode` → CodeAwareCompressor, falling back to cached
/// Kompress on exact passthrough (PR-B4)
/// - `SourceCode` → CodeAwareCompressor; an exact passthrough stays a
/// no-op, never Kompress (PR-B4, #4214)
/// - `PlainText` → cached Kompress, cache-cold → no-op (PR-B4)
/// - `Html` → no-op (no compressor)
///
@@ -1726,21 +1718,20 @@ fn dispatch_compressor(text: &str, content_type: ContentType) -> DispatchResult
// syntax errors, a min-token floor, and a compression-ratio
// guard), so this arm only has to compare its output against
// the input; the tokenizer-rejection gate in
// `compress_one_block` applies on top of that. When the code
// compressor doesn't shrink the block (e.g. it's already
// dense, or tree-sitter reverted on a parse error), fall back
// to Kompress rather than giving up — mirrors the Python
// router's no-shrink → Kompress fallback.
// `compress_one_block` applies on top of that.
//
// When the code compressor declines (exact passthrough), the block
// is left UNCHANGED. It is deliberately NOT handed to Kompress:
// that is a prose model that drops low-salience words, and for code
// those are keywords such as `for`, `in` and `if` (#4214). Mirrors
// the Python router, which no longer falls back from code to prose
// ML compression either.
ContentType::SourceCode => {
let result = code_compressor().compress(text);
if result.compressed == text {
// Exact passthrough only: the compressor declined
// (min-token floor, unknown language, parse failure,
// ratio guard), so hand the block to Kompress. A
// rewrite that changed bytes without shrinking tokens
// is NOT retried here — `compress_one_block`'s
// tokenizer gate rejects it and forwards the original.
return kompress_or_noop(text, content_type);
return DispatchResult::NoOp {
content_type: content_type.as_str(),
};
}
DispatchResult::Compressed {
strategy: STRATEGY_CODE_COMPRESSOR,
@@ -246,14 +246,18 @@ fn cell_from_value(v: &Value, cfg: &CompactConfig, store: Option<&Arc<dyn CcrSto
CellValue::Scalar(v.clone())
}
CellClass::StringifiedJson(parsed) => {
// If the parsed JSON is an array of objects, recurse; else
// store the parsed value as a Scalar (un-escapes for free).
// If the parsed JSON is an array of objects, recurse into a nested table.
if let Value::Array(items) = &parsed {
if items.iter().all(|i| matches!(i, Value::Object(_))) && items.len() >= 2 {
return CellValue::Nested(Box::new(compact_inner(items, cfg, store)));
}
}
CellValue::Scalar(parsed)
// Keep any other container-shaped string as a string. Un-escaping it would render it
// byte-identically to the value it spells (``"[]"`` vs ``[]``), so the csv-schema decoder
// could not restore the original type. The formatter JSON-quotes ambiguous strings in
// ``json`` columns, so the round-trip comes back as the original string (same rule as the
// scalar-looking case in #4053).
CellValue::Scalar(v.clone())
}
CellClass::Opaque(kind) => {
let s = match v {
@@ -558,6 +562,38 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn stringified_container_strings_keep_their_identity() {
// A string whose text is a JSON container must not render identically to
// the container itself: the csv-schema decoder cannot tell them apart
// afterwards (remainder of #4053, which covered scalar-looking strings).
use super::super::formatter::{CsvSchemaFormatter, Formatter};
let items = vec![
json!({"id": 0, "v": []}),
json!({"id": 1, "v": "[]"}),
json!({"id": 2, "v": [1, 2]}),
json!({"id": 3, "v": "[1,2]"}),
json!({"id": 4, "v": {}}),
json!({"id": 5, "v": "{}"}),
];
let formatted = CsvSchemaFormatter::new().format(&compact(&items, &cfg()));
let cells: Vec<&str> = formatted
.lines()
.skip(1)
.map(|row| row.split_once(',').map(|(_, cell)| cell).unwrap_or(row))
.collect();
assert_eq!(cells.len(), 6, "unexpected table:\n{formatted}");
// Real values stay as their CSV-quoted JSON; the string is a JSON string literal
// (then CSV-quoted), which the decoder maps back to the string.
assert_eq!(cells[0], "\"[]\"");
assert_eq!(cells[1], "\"\"\"[]\"\"\"");
assert_eq!(cells[2], "\"[1,2]\"");
assert_eq!(cells[3], "\"\"\"[1,2]\"\"\"");
assert_eq!(cells[4], "\"{}\"");
assert_eq!(cells[5], "\"\"\"{}\"\"\"");
}
fn cfg() -> CompactConfig {
CompactConfig::default()
}
+20
View File
@@ -122,6 +122,26 @@ pub fn python_module_source(n: usize) -> String {
code
}
/// Go source the tree-sitter code compressor declines (exact
/// passthrough: the language has no elision rules), yet which the
/// detector still classifies as `SourceCode` and which clears the
/// 2048-byte threshold. This is the shape that used to fall through to
/// Kompress (#4214).
pub fn go_handlers_source(n: usize) -> String {
use std::fmt::Write as _;
let mut code = String::new();
for i in 0..n {
let _ = write!(
code,
"func Handle{i}(w http.ResponseWriter, r *http.Request) {{\n\t\
id := r.URL.Query().Get(\"id\")\n\t\
fmt.Fprintf(w, \"%s-{i}\", id)\n}}\n\n"
);
}
code
}
/// Repetitive plain prose of at least `min_bytes`, varied enough to
/// classify as `PlainText`.
pub fn plain_prose(min_bytes: usize) -> String {
@@ -14,10 +14,47 @@
mod common;
use common::{body_with_tool_result, dispatch, kompress_available, python_module_source, sha256};
use common::{
body_with_tool_result, dispatch, go_handlers_source, kompress_available, python_module_source,
sha256, tool_result_action,
};
use headroom_core::transforms::{BlockAction, LiveZoneOutcome};
use serde_json::{json, Value};
/// The script from #4214 (a fenced Python snippet whose keywords Kompress
/// deleted). The reporter's own fence is not published; this reconstruction
/// keeps the lines quoted in the issue and parses as Python.
const ISSUE_4214_SCRIPT: &str = r#"import json, collections
d = json.load(open('turns.json'))
segs=[s for s in open('segs.txt').read().split() if s]
def load(path):
try:
return json.load(open(path))
except Exception as e: return None
for i,s in enumerate(segs):
t0=(d or {}).get('turns') or []
if not t0 or len(t0) < 2:
continue
else:
label = s if s else 'unknown'
counts = collections.Counter(x.get('role') for x in t0)
for role, n in counts.items():
if n > 1 or role == 'tool':
print(i, label, role, n)
else:
print(i, label, role)
total = sum(counts.values())
if total > 10 or label == 'big':
print('large session', label, total)
out = [k for k in counts if counts[k] > 0]
print(json.dumps(out))
summary = {s: i for i, s in enumerate(segs)}
for k, v in summary.items():
if v % 2 == 0 or k.startswith('a'):
print(k, v)
print('done', len(segs))"#;
// ─── Routing tests ─────────────────────────────────────────────────────
#[test]
@@ -249,6 +286,70 @@ fn source_code_tool_result_routes_to_code_compressor() {
}
}
#[test]
fn source_code_declined_by_code_compressor_is_never_kompressed() {
// The code compressor leaves Go source untouched (exact passthrough).
// That must stay a NoOp: handing it to Kompress, a prose model, drops
// keywords such as `func`, `if` and `for` from the code (#4214). The
// warmup makes Kompress live when the model is cache-resident, so on
// such a host the old fallback would have rewritten this block.
let _ = kompress_available();
let code = go_handlers_source(30);
assert!(
code.len() > 2048,
"fixture must clear the SourceCode byte threshold (2048); got {} bytes",
code.len()
);
let (body, _) = body_with_tool_result(&code);
match dispatch(&body) {
LiveZoneOutcome::NoChange { manifest } => {
let action = manifest
.block_outcomes
.iter()
.find(|b| b.block_type == "tool_result")
.expect("tool_result block present")
.action
.clone();
assert!(
matches!(&action, BlockAction::NoCompressionApplied { content_type } if content_type == "source_code"),
"expected a source_code NoOp, got {action:?}"
);
}
LiveZoneOutcome::Modified { manifest, .. } => panic!(
"a declined source-code block must be forwarded unchanged, not rewritten. manifest: {manifest:?}"
),
}
}
#[test]
fn issue_4214_script_is_never_kompressed() {
// The Python script quoted in #4214, repeated until the block clears the
// SourceCode threshold. The code compressor may shrink it (it keeps the
// keywords) or leave it alone, but the prose model must never rewrite it.
// A guard rather than a discriminator: the code compressor already handles
// Python, so this passes before the fix too; the Go test above is the one
// that fails without it.
let _ = kompress_available();
let code = format!("{ISSUE_4214_SCRIPT}\n").repeat(3);
assert!(
code.len() > 2048,
"fixture must clear the SourceCode byte threshold"
);
let (body, _) = body_with_tool_result(&code);
match dispatch(&body) {
LiveZoneOutcome::NoChange { .. } => {}
LiveZoneOutcome::Modified { manifest, .. } => match tool_result_action(&manifest) {
BlockAction::Compressed { strategy, .. } => assert_eq!(
strategy, "code_compressor",
"only the code compressor may rewrite the #4214 script"
),
other => panic!("unexpected action {other:?}"),
},
}
}
#[test]
fn tiny_source_code_below_threshold_no_op() {
// Detector classifies this as SourceCode, but it's well under the
@@ -0,0 +1,53 @@
//! A declined source-code block never reaches the Kompress slot — dedicated
//! integration test file.
//!
//! When the code compressor declines a block (exact passthrough), the
//! dispatcher used to hand it to Kompress, a prose model that drops
//! keywords such as `for`, `in` and `if` (#4214). The Kompress slot is
//! process-global and latches on first use, so the cleanest observable of
//! "Kompress was consulted" is that the model construction never starts.
//! That holds on any host, warm cache or not, which is why this does not
//! need the model. It needs a virgin process, so this is a single-test
//! binary like `live_zone_kompress_async_init.rs`. Do NOT add more tests
//! to this file.
//!
//! Vacuity note: without the `ml` feature there is no Kompress slot and
//! `kompress_init_runs()` is always 0, so the init assertion is trivially
//! true there; the byte-identical assertion still holds.
mod common;
use std::time::{Duration, Instant};
use common::{body_with_tool_result, dispatch, go_handlers_source};
use headroom_core::transforms::live_zone;
use headroom_core::transforms::LiveZoneOutcome;
#[test]
fn declined_source_code_never_starts_kompress() {
let code = go_handlers_source(30);
assert!(
code.len() > 2048,
"fixture must clear the SourceCode byte threshold (2048); got {} bytes",
code.len()
);
let (body, _) = body_with_tool_result(&code);
assert!(
matches!(dispatch(&body), LiveZoneOutcome::NoChange { .. }),
"a block the code compressor declines must be forwarded unchanged"
);
// The slot's initializer runs on a background thread started by the
// dispatch that first consults it. Give a would-be start ample time to
// show up before asserting it never did.
let deadline = Instant::now() + Duration::from_secs(2);
while Instant::now() < deadline && live_zone::kompress_init_runs() == 0 {
std::thread::sleep(Duration::from_millis(20));
}
assert_eq!(
live_zone::kompress_init_runs(),
0,
"Kompress must not be consulted for code the code compressor declined"
);
}
+120 -16
View File
@@ -1,5 +1,6 @@
//! Configuration for the proxy: CLI flags + env vars.
use crate::inbound_auth::ProxyToken;
use clap::{Parser, ValueEnum};
use headroom_core::rollout::{
feature_names, split_feature_names, Feature, RolloutChannel, RolloutSnapshot,
@@ -272,8 +273,10 @@ pub struct CliArgs {
)]
pub unsafe_allow_unstable_features: bool,
/// Address the proxy listens on (e.g. 0.0.0.0:8787).
#[arg(long, env = "HEADROOM_PROXY_LISTEN", default_value = "0.0.0.0:8787")]
/// Address the proxy listens on. Loopback by default, like the Python
/// proxy; a non-loopback address needs `HEADROOM_PROXY_TOKEN` (or
/// `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1`) to start.
#[arg(long, env = "HEADROOM_PROXY_LISTEN", default_value = "127.0.0.1:8787")]
pub listen: SocketAddr,
/// Restrict the Prometheus `/metrics` scrape endpoint to loopback
@@ -295,6 +298,20 @@ pub struct CliArgs {
)]
pub metrics_require_loopback: bool,
/// Inbound proxy token. When set, every request from a non-loopback
/// peer must present it as `x-headroom-proxy-token` or
/// `Authorization: Bearer`, the same rules as the Python proxy, or it
/// gets 401 without reaching the upstream. Prefer the env var: a
/// command-line value is visible in the process list. A non-loopback
/// `--listen` refuses to start without it unless
/// `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1` acknowledges the open bind.
#[arg(
long = "proxy-token",
env = "HEADROOM_PROXY_TOKEN",
hide_env_values = true
)]
pub proxy_token: Option<String>,
/// Upstream base URL the proxy forwards to (e.g. http://127.0.0.1:8788).
/// REQUIRED — there is no default; we want operators to be explicit.
#[arg(long, env = "HEADROOM_PROXY_UPSTREAM")]
@@ -487,7 +504,7 @@ pub struct CliArgs {
pub enable_conversations_passthrough: bool,
/// Phase D PR-D1: enable the native Bedrock InvokeModel route.
/// When `true` (default), `POST /model/{model_id}/invoke` is
/// When `true`, `POST /model/{model_id}/invoke` is
/// handled by the Rust `bedrock::invoke` handler — Anthropic-shape
/// bodies run through the live-zone compression path and the
/// proxy re-signs the request with SigV4 before forwarding to
@@ -497,15 +514,21 @@ pub struct CliArgs {
/// re-sign — operators MUST run an unsigned upstream that
/// happens to know what to do, otherwise this fails closed).
///
/// Default `false`: the route signs every request it receives with
/// this host's AWS credentials and does not authenticate the caller,
/// so only enable it where every caller that can reach `--listen`
/// may use those credentials. `--features native_bedrock` also
/// enables it; `false` here (or `--disable-features native_bedrock`)
/// forces it off.
///
/// Source priority: CLI flag → `HEADROOM_PROXY_ENABLE_BEDROCK_NATIVE`
/// env var → default (`true`).
/// env var → rollout (`native_bedrock`, not on by default).
#[arg(
long = "enable-bedrock-native",
env = "HEADROOM_PROXY_ENABLE_BEDROCK_NATIVE",
default_value_t = true,
action = clap::ArgAction::Set,
)]
pub enable_bedrock_native: bool,
pub enable_bedrock_native: Option<bool>,
/// AWS region to use when signing Bedrock requests. Default
/// `us-east-1`. The Bedrock endpoint URL derived from this
@@ -593,6 +616,39 @@ pub struct CliArgs {
)]
pub vertex_adc_scope: String,
/// Mount the native Vertex `:rawPredict` / `:streamRawPredict`
/// route. That route replaces the caller's `Authorization` with a
/// bearer from this host's Google ADC and does not authenticate the
/// caller, so only enable it where every caller that can reach
/// `--listen` may use that identity. Default `false`: Vertex paths
/// fall through to the catch-all with the caller's own headers.
///
/// Source priority: CLI flag → `HEADROOM_PROXY_ENABLE_VERTEX_NATIVE`
/// env var → default (`false`).
#[arg(
long = "enable-vertex-native",
env = "HEADROOM_PROXY_ENABLE_VERTEX_NATIVE",
default_value_t = false,
action = clap::ArgAction::Set,
)]
pub enable_vertex_native: bool,
/// Let the native Vertex route attach the ADC bearer when
/// `--upstream` is not an `https://*.googleapis.com` host (a local
/// emulator or a gateway that forwards to Vertex). Default `false`:
/// the route refuses such requests and no token is fetched.
///
/// Source priority: CLI flag →
/// `HEADROOM_PROXY_VERTEX_ALLOW_NON_GOOGLE_UPSTREAM` env var →
/// default (`false`).
#[arg(
long = "vertex-allow-non-google-upstream",
env = "HEADROOM_PROXY_VERTEX_ALLOW_NON_GOOGLE_UPSTREAM",
default_value_t = false,
action = clap::ArgAction::Set,
)]
pub vertex_allow_non_google_upstream: bool,
/// Native savings stats: record per-request savings/cost
/// telemetry and serve `/stats`, `/stats/timeseries`,
/// `/stats/events`, and `/dashboard`. When disabled, nothing is
@@ -667,6 +723,8 @@ pub struct Config {
/// Gate the Prometheus `/metrics` endpoint to loopback clients.
/// Default `false`; recommend `true` when `listen` is non-loopback.
pub metrics_require_loopback: bool,
/// Inbound token required from non-loopback peers (`None` = no gate).
pub proxy_token: Option<ProxyToken>,
pub upstream: Url,
pub upstream_timeout: Duration,
pub upstream_connect_timeout: Duration,
@@ -712,7 +770,7 @@ pub struct Config {
/// C5+/B-phase territory).
pub enable_conversations_passthrough: bool,
/// PR-D1: enable the native Bedrock InvokeModel route. Default
/// `true`. When disabled, the explicit Rust handlers are not
/// `false`. When disabled, the explicit Rust handlers are not
/// mounted; operators relying on the Python LiteLLM converter
/// keep their existing path.
pub enable_bedrock_native: bool,
@@ -736,6 +794,11 @@ pub struct Config {
/// PR-D4: GCP ADC OAuth scope used when fetching the bearer
/// token. Default `https://www.googleapis.com/auth/cloud-platform`.
pub vertex_adc_scope: String,
/// Mount the native Vertex route. Default `false`.
pub enable_vertex_native: bool,
/// Attach the ADC bearer even when `upstream` is not a Google API
/// host. Default `false`.
pub vertex_allow_non_google_upstream: bool,
/// Native savings stats: record per-request telemetry and serve
/// `/stats`, `/stats/timeseries`, `/stats/events`, `/dashboard`.
pub stats: bool,
@@ -749,17 +812,17 @@ impl Config {
if args.enable_responses_streaming {
explicit_features.push(Feature::OpenAiResponsesStreaming);
}
if args.enable_bedrock_native {
if args.enable_bedrock_native == Some(true) {
explicit_features.push(Feature::NativeBedrock);
}
// Preserve the pre-rollout rollback controls as legacy disables. Both
// features are stable defaults in the registry, so merely omitting a
// false flag from `explicit_features` would turn it straight back on.
// Preserve the pre-rollout rollback controls as legacy disables: a
// false flag must win over a default or a `--features` request.
// An omitted Bedrock flag leaves the decision to the rollout.
let mut disabled_features = split_feature_names(&args.disable_features);
if !args.enable_responses_streaming {
disabled_features.push(Feature::OpenAiResponsesStreaming.spec().name.to_owned());
}
if !args.enable_bedrock_native {
if args.enable_bedrock_native == Some(false) {
disabled_features.push(Feature::NativeBedrock.spec().name.to_owned());
}
let rollout = RolloutSnapshot::from_parts_with_explicit(
@@ -781,6 +844,7 @@ impl Config {
rollout: rollout.clone(),
listen: args.listen,
metrics_require_loopback: args.metrics_require_loopback,
proxy_token: args.proxy_token.as_deref().and_then(ProxyToken::new),
upstream: args.upstream,
upstream_timeout: args.upstream_timeout,
upstream_connect_timeout: args.upstream_connect_timeout,
@@ -800,14 +864,18 @@ impl Config {
args.enable_responses_streaming,
),
enable_conversations_passthrough: args.enable_conversations_passthrough,
enable_bedrock_native: rollout
.is_enabled(Feature::NativeBedrock, args.enable_bedrock_native),
enable_bedrock_native: rollout.is_enabled(
Feature::NativeBedrock,
args.enable_bedrock_native == Some(true),
),
bedrock_region: args.bedrock_region,
bedrock_endpoint: args.bedrock_endpoint,
aws_profile: args.aws_profile,
bedrock_validate_eventstream_crc: args.bedrock_validate_eventstream_crc,
vertex_region: args.vertex_region,
vertex_adc_scope: args.vertex_adc_scope,
enable_vertex_native: args.enable_vertex_native,
vertex_allow_non_google_upstream: args.vertex_allow_non_google_upstream,
stats: args.stats,
stats_path: args.stats_path.or_else(default_stats_path),
}
@@ -824,6 +892,7 @@ impl Config {
// carry no `ConnectInfo`. Tests that exercise the gate set
// this to `true` explicitly.
metrics_require_loopback: false,
proxy_token: None,
upstream,
upstream_timeout: Duration::from_secs(60),
upstream_connect_timeout: Duration::from_secs(5),
@@ -858,8 +927,8 @@ impl Config {
// production traffic will hit.
enable_responses_streaming: true,
enable_conversations_passthrough: true,
// PR-D1: bedrock route default-on so tests exercise
// it without per-test opt-in. Tests that set
// PR-D1: bedrock route on so tests exercise it without
// per-test opt-in (production default is off). Tests that set
// `bedrock_endpoint` to a wiremock URL get the full
// sign-and-forward path.
enable_bedrock_native: true,
@@ -873,6 +942,11 @@ impl Config {
// only; the upstream URL is `upstream`).
vertex_region: "us-central1".to_string(),
vertex_adc_scope: "https://www.googleapis.com/auth/cloud-platform".to_string(),
// Vertex route on, against the wiremock upstream, so tests
// exercise it without per-test opt-in (production default
// is off for both, see `CliArgs`).
enable_vertex_native: true,
vertex_allow_non_google_upstream: true,
// Stats on (routes mounted, recording active) but
// in-memory: tests never touch a real home directory.
stats: true,
@@ -958,6 +1032,36 @@ mod rollout_input_tests {
assert!(!config.enable_bedrock_native);
}
#[test]
fn native_bedrock_is_off_by_default_and_follows_rollout_requests() {
let parse = |extra: &[&str]| {
let mut argv = vec!["headroom-proxy", "--upstream", "http://127.0.0.1:9"];
argv.extend_from_slice(extra);
Config::from_cli(CliArgs::try_parse_from(argv).unwrap())
};
assert!(!parse(&[]).enable_bedrock_native);
assert!(parse(&["--features", "native_bedrock"]).enable_bedrock_native);
assert!(parse(&["--enable-bedrock-native", "true"]).enable_bedrock_native);
assert!(
!parse(&[
"--features",
"native_bedrock",
"--disable-features",
"native_bedrock"
])
.enable_bedrock_native
);
assert!(
!parse(&[
"--features",
"native_bedrock",
"--enable-bedrock-native",
"false"
])
.enable_bedrock_native
);
}
#[test]
fn native_stats_require_explicit_opt_in() {
let base = ["headroom-proxy", "--upstream", "http://127.0.0.1:9"];
+389
View File
@@ -0,0 +1,389 @@
//! Inbound `HEADROOM_PROXY_TOKEN` gate and startup bind policy.
//!
//! The Rust front connects to the Python proxy from `127.0.0.1`, and the
//! Python proxy exempts loopback peers from its token gate and trusts them
//! on `/admin`, `/debug` and `/settings`. So the front must apply the same
//! model itself, or every peer that reaches it is a "local" caller. Names,
//! credential rules and exemptions mirror `headroom/proxy/server.py`
//! (`_security_gate`, `read_proxy_token`) and `headroom/proxy/bind_policy.py`
//! so operators configure one token model for both processes.
use std::fmt;
use std::net::{IpAddr, SocketAddr};
use axum::body::Body;
use axum::extract::{ConnectInfo, State};
use axum::http::{header, HeaderMap, HeaderValue, Method, Request, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
/// The inbound credential. Same variable as the Python proxy.
pub const PROXY_TOKEN_ENV: &str = "HEADROOM_PROXY_TOKEN";
/// Explicit acknowledgement of an unauthenticated non-loopback bind.
/// Same variable and truthy values as the Python bind policy.
pub const OPEN_BIND_ACK_ENV: &str = "HEADROOM_ALLOW_UNAUTHENTICATED_BIND";
const PROXY_TOKEN_HEADER: &str = "x-headroom-proxy-token";
/// A configured proxy token. `Debug` never prints the value, because
/// `Config` derives `Debug`.
#[derive(Clone)]
pub struct ProxyToken(String);
impl ProxyToken {
/// `None` for an empty or whitespace-only value, which the Python bind
/// policy also treats as "not configured". A real value is kept
/// verbatim, as the Python gate compares it.
pub fn new(value: &str) -> Option<Self> {
(!value.trim().is_empty()).then(|| Self(value.to_owned()))
}
fn matches(&self, provided: &str) -> bool {
constant_time_eq(provided.as_bytes(), self.0.as_bytes())
}
}
impl fmt::Debug for ProxyToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ProxyToken(<redacted>)")
}
}
// Like Python's hmac.compare_digest: time does not depend on where the
// bytes differ (the length is not hidden, as there).
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
fn is_loopback(addr: &SocketAddr) -> bool {
addr.ip().to_canonical().is_loopback()
}
/// Outcome of the startup bind check that lets the process start.
#[derive(Debug, PartialEq, Eq)]
pub enum BindPolicy {
/// Loopback bind, or a token is configured.
Ok,
/// Non-loopback bind with no token, acknowledged via [`OPEN_BIND_ACK_ENV`].
OpenAcknowledged,
}
/// Refuse a non-loopback `listen` with no token unless acknowledged.
/// `ack` is the raw value of [`OPEN_BIND_ACK_ENV`]. The error text names
/// both remedies.
pub fn check_bind_policy(
listen: SocketAddr,
token_configured: bool,
ack: Option<&str>,
) -> Result<BindPolicy, String> {
if token_configured || is_loopback(&listen) {
return Ok(BindPolicy::Ok);
}
let acknowledged = ack.is_some_and(|v| {
matches!(
v.trim().to_ascii_lowercase().as_str(),
"1" | "true" | "yes" | "on"
)
});
if acknowledged {
return Ok(BindPolicy::OpenAcknowledged);
}
Err(format!(
"Refusing to listen on {listen}: with no {PROXY_TOKEN_ENV} this proxy would relay \
every network peer to the upstream Headroom proxy from 127.0.0.1, where it is \
treated as a trusted local caller. Either set {PROXY_TOKEN_ENV} (e.g. \
`openssl rand -hex 32`) so non-loopback callers must present it, listen on a \
loopback address (--listen 127.0.0.1:8787), or, only when the runtime already \
restricts who can reach the port (such as a container published on 127.0.0.1), \
set {OPEN_BIND_ACK_ENV}=1 to acknowledge the open bind."
))
}
/// The caller-supplied token, read exactly as Python's `read_proxy_token`:
/// the explicit header wins when present (even empty, then it is no
/// credential); otherwise a `Bearer` Authorization value.
fn read_proxy_token(headers: &HeaderMap) -> Option<&str> {
if let Some(raw) = headers.get(PROXY_TOKEN_HEADER) {
return raw.to_str().ok().filter(|v| !v.is_empty());
}
bearer(headers)
}
fn bearer(headers: &HeaderMap) -> Option<&str> {
let auth = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
let scheme = auth.get(..7)?;
if !scheme.eq_ignore_ascii_case("bearer ") {
return None;
}
Some(auth[7..].trim()).filter(|v| !v.is_empty())
}
/// Python exempts `GET /health`, `/livez` and `/readyz`; `/healthz` and
/// `/healthz/upstream` are this proxy's own probe routes.
fn is_health_probe(method: &Method, path: &str) -> bool {
*method == Method::GET
&& matches!(
path,
"/healthz" | "/healthz/upstream" | "/health" | "/livez" | "/readyz"
)
}
/// The Anthropic SDK's `GET`/`HEAD /api/hello` reachability probe (also
/// under `/p/<project>`). It never carries custom headers, so it cannot
/// hold the token.
fn is_hello_probe(method: &Method, path: &str) -> bool {
let hello = path == "/api/hello"
|| path
.strip_prefix("/p/")
.and_then(|rest| rest.split_once('/'))
.is_some_and(|(project, rest)| !project.is_empty() && rest == "api/hello");
(*method == Method::GET || *method == Method::HEAD) && hello
}
/// Request extension: the caller is not local (not a loopback peer with a
/// loopback `Host`). `forward_http` then never sends it upstream with a
/// loopback `Host`, so the upstream's local-only routes (`/admin`,
/// `/debug`, `/settings`, ...) do not treat a relayed caller as local.
/// Without it this process's own loopback connection and rewritten `Host`
/// would pass both checks those routes make.
#[derive(Clone, Copy, Debug)]
pub struct NonLocalCaller;
/// `Host` sent upstream in place of one that may name loopback, for a
/// [`NonLocalCaller`]. A reserved name (RFC 2606), never the caller's own
/// value: the caller controls that, and the upstream's parser may accept
/// loopback forms this one does not.
pub const NON_LOCAL_HOST: &str = "headroom-remote.invalid";
/// For a [`NonLocalCaller`]: [`NON_LOCAL_HOST`] when the `Host` that would
/// be sent may name loopback, else `None` (keep it). That `Host` is the
/// explicit outgoing one (`--no-rewrite-host`), else the upstream URL's
/// authority. Judged on the value, not on the upstream address, so an
/// upstream name that resolves to loopback cannot be paired with a
/// loopback `Host`.
pub(crate) fn host_override_for_non_local(
outgoing: Option<&HeaderValue>,
upstream: &url::Url,
) -> Option<HeaderValue> {
let effective = match outgoing {
Some(h) => h.to_str().ok().map(str::to_owned),
None => upstream.host_str().map(|h| match upstream.port() {
Some(port) => format!("{h}:{port}"),
None => h.to_owned(),
}),
};
may_name_loopback(effective.as_deref()).then(|| HeaderValue::from_static(NON_LOCAL_HOST))
}
/// Conservative superset of what the Python proxy treats as a loopback
/// `Host`: anything [`is_loopback_host_header`] accepts, an unreadable
/// value, and any value with an IPv6 zone (`%`), since Python's
/// `ipaddress` accepts scoped literals such as `[::1%lo]`.
fn may_name_loopback(value: Option<&str>) -> bool {
match value {
None => true,
Some(v) => v.contains('%') || is_loopback_host_header(Some(v)),
}
}
/// Same rules as Python's `loopback_guard.is_loopback_host_header`:
/// `localhost`, or a loopback IP literal, with an optional port and
/// brackets around IPv6. Missing or malformed is not loopback.
fn is_loopback_host_header(value: Option<&str>) -> bool {
let Some(candidate) = value.map(str::trim).filter(|v| !v.is_empty()) else {
return false;
};
let host = if let Some(rest) = candidate.strip_prefix('[') {
match rest.split_once(']') {
Some((h, _)) => h,
None => return false,
}
} else if candidate.matches(':').count() == 1 {
candidate.rsplit_once(':').map_or(candidate, |(h, _)| h)
} else {
candidate
};
host.eq_ignore_ascii_case("localhost")
|| host
.parse::<IpAddr>()
.is_ok_and(|ip| ip.to_canonical().is_loopback())
}
/// Router-wide middleware. Marks every caller that is not local with
/// [`NonLocalCaller`]. When a token is configured, a non-loopback (or
/// unknown) peer must also present it or gets 401 with no upstream
/// contact, and the credential is removed before forwarding.
pub async fn inbound_gate(
State(token): State<Option<ProxyToken>>,
mut req: Request<Body>,
next: Next,
) -> Response {
// No ConnectInfo is no evidence of a local caller: fail closed, as
// Python's is_loopback_host(None) does.
let peer = req
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.map(|c| c.0);
let loopback_peer = peer.as_ref().is_some_and(is_loopback);
if let Some(token) = &token {
// Answered here and empty, never relayed upstream without a
// credential: the same answer the Python proxy gives it.
if is_hello_probe(req.method(), req.uri().path()) {
return StatusCode::OK.into_response();
}
if !loopback_peer && !is_health_probe(req.method(), req.uri().path()) {
let provided = read_proxy_token(req.headers());
if !provided.is_some_and(|p| token.matches(p)) {
tracing::warn!(
event = "proxy_auth_rejected",
method = %req.method(),
path = req.uri().path(),
peer = ?peer,
reason = if provided.is_none() { "missing_token" } else { "bad_token" },
);
return (
StatusCode::UNAUTHORIZED,
Json(json!({ "error": "unauthorized" })),
)
.into_response();
}
}
let headers = req.headers_mut();
headers.remove(PROXY_TOKEN_HEADER);
if bearer(headers).is_some_and(|b| token.matches(b)) {
headers.remove(header::AUTHORIZATION);
}
}
let host = req
.headers()
.get(header::HOST)
.and_then(|h| h.to_str().ok())
.or_else(|| req.uri().authority().map(|a| a.as_str()));
if !(loopback_peer && is_loopback_host_header(host)) {
req.extensions_mut().insert(NonLocalCaller);
}
next.run(req).await
}
#[cfg(test)]
mod tests {
use super::*;
fn addr(s: &str) -> SocketAddr {
s.parse().unwrap()
}
#[test]
fn bind_policy_refuses_open_non_loopback_bind() {
let err = check_bind_policy(addr("0.0.0.0:8787"), false, None).unwrap_err();
assert!(err.contains(PROXY_TOKEN_ENV) && err.contains(OPEN_BIND_ACK_ENV));
assert!(check_bind_policy(addr("[::]:8787"), false, Some("0")).is_err());
assert!(check_bind_policy(addr("192.0.2.1:8787"), false, Some("")).is_err());
}
#[test]
fn bind_policy_allows_loopback_token_or_ack() {
assert_eq!(
check_bind_policy(addr("127.0.0.1:8787"), false, None),
Ok(BindPolicy::Ok)
);
assert_eq!(
check_bind_policy(addr("[::1]:8787"), false, None),
Ok(BindPolicy::Ok)
);
assert_eq!(
check_bind_policy(addr("0.0.0.0:8787"), true, None),
Ok(BindPolicy::Ok)
);
for ack in ["1", "TRUE", " yes ", "on"] {
assert_eq!(
check_bind_policy(addr("0.0.0.0:8787"), false, Some(ack)),
Ok(BindPolicy::OpenAcknowledged)
);
}
}
#[test]
fn token_rules_match_python() {
assert!(ProxyToken::new(" ").is_none());
let mut h = HeaderMap::new();
h.insert(header::AUTHORIZATION, "BEARER abc ".parse().unwrap());
assert_eq!(read_proxy_token(&h), Some("abc"));
h.insert(PROXY_TOKEN_HEADER, "".parse().unwrap());
assert_eq!(read_proxy_token(&h), None, "present-but-empty header wins");
assert!(constant_time_eq(b"abc", b"abc"));
assert!(!constant_time_eq(b"abc", b"abd"));
assert!(!constant_time_eq(b"abc", b"abcd"));
assert!(format!("{:?}", ProxyToken::new("abc").unwrap()).contains("redacted"));
}
#[test]
fn loopback_host_header_matches_python() {
for ok in [
"127.0.0.1:8787",
"localhost",
"LOCALHOST:1",
"[::1]:8787",
"::1",
"127.1.2.3",
] {
assert!(is_loopback_host_header(Some(ok)), "{ok}");
}
for bad in [
"",
"evil.example",
"evil.example:8787",
"10.0.0.1:8787",
"[::1",
"localhost.evil.example",
] {
assert!(!is_loopback_host_header(Some(bad)), "{bad}");
}
assert!(!is_loopback_host_header(None));
}
#[test]
fn non_local_caller_never_gets_a_loopback_host_upstream() {
let up = |u: &str| url::Url::parse(u).unwrap();
let hv = |h: &str| HeaderValue::from_str(h).unwrap();
let alias = up("http://headroom-upstream.internal:8788");
let loopback = up("http://127.0.0.1:8788");
// --no-rewrite-host: the caller's Host is what would be sent.
for host in [
"localhost",
"127.0.0.1:8787",
"[::1]:8787",
"[::1%lo]:8787",
"::1%lo",
] {
assert_eq!(
host_override_for_non_local(Some(&hv(host)), &alias).unwrap(),
NON_LOCAL_HOST,
"{host}"
);
}
// Rewritten Host on a loopback upstream: the reserved name.
assert_eq!(
host_override_for_non_local(None, &loopback).unwrap(),
NON_LOCAL_HOST
);
// Not loopback: left alone.
assert!(host_override_for_non_local(None, &alias).is_none());
assert!(host_override_for_non_local(Some(&hv("proxy.example")), &loopback).is_none());
}
#[test]
fn exemptions_match_python() {
assert!(is_health_probe(&Method::GET, "/healthz"));
assert!(is_health_probe(&Method::GET, "/readyz"));
assert!(!is_health_probe(&Method::POST, "/readyz"));
assert!(!is_health_probe(&Method::HEAD, "/readyz"));
assert!(!is_health_probe(&Method::GET, "/admin/upstream"));
assert!(!is_health_probe(&Method::GET, "/rollout/status"));
assert!(is_hello_probe(&Method::HEAD, "/api/hello"));
assert!(is_hello_probe(&Method::GET, "/p/demo/api/hello"));
assert!(!is_hello_probe(&Method::GET, "/p//api/hello"));
assert!(!is_hello_probe(&Method::POST, "/api/hello"));
}
}
+1
View File
@@ -11,6 +11,7 @@ pub mod error;
pub mod handlers;
pub mod headers;
pub mod health;
pub mod inbound_auth;
pub mod observability;
pub mod proxy;
pub mod responses_items;
+19
View File
@@ -10,6 +10,7 @@ use std::net::SocketAddr;
use clap::Parser;
use headroom_proxy::config::CliArgs;
use headroom_proxy::inbound_auth::{check_bind_policy, BindPolicy, OPEN_BIND_ACK_ENV};
use headroom_proxy::{build_app, AppState, Config};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
@@ -22,6 +23,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
init_tracing(&config.log_level);
// Same rule as the Python proxy's bind policy: no unauthenticated
// non-loopback listener unless the operator acknowledges it.
let ack = std::env::var(OPEN_BIND_ACK_ENV).ok();
match check_bind_policy(config.listen, config.proxy_token.is_some(), ack.as_deref()) {
Ok(BindPolicy::Ok) => {}
Ok(BindPolicy::OpenAcknowledged) => tracing::warn!(
event = "proxy_open_bind",
listen = %config.listen,
"non-loopback listen with no HEADROOM_PROXY_TOKEN; every peer that \
reaches this port is relayed upstream as a loopback caller. \
Acknowledged via HEADROOM_ALLOW_UNAUTHENTICATED_BIND"
),
Err(msg) => {
eprintln!("headroom-proxy: {msg}");
std::process::exit(2);
}
}
tracing::info!(
listen = %config.listen,
upstream = %config.upstream,
+42 -9
View File
@@ -132,8 +132,9 @@ impl AppState {
// PR-D4: lazy ADC token source. Provider resolution is
// deferred to first `bearer()` call so proxy startup stays
// cheap when no Vertex route is exercised.
let vertex_token_source: Arc<dyn crate::vertex::TokenSource> =
Arc::new(crate::vertex::adc::GcpAdcTokenSource::new());
let vertex_token_source: Arc<dyn crate::vertex::TokenSource> = Arc::new(
crate::vertex::adc::GcpAdcTokenSource::with_scope(config.vertex_adc_scope.clone()),
);
let stats = if config.stats {
match config.stats_path.clone() {
@@ -281,7 +282,13 @@ pub fn build_app(state: AppState) -> Router {
"/v1/responses",
post(crate::handlers::responses::handle_responses)
.layer(DefaultBodyLimit::max(state.config.max_body_bytes as usize)),
)
);
// Mounted only with `--enable-vertex-native`: the handler replaces
// the caller's Authorization with this host's ADC bearer. When off,
// Vertex paths reach the catch-all with the caller's own headers.
if state.config.enable_vertex_native {
router = router
// PR-D4: native Vertex publisher path. The Vertex AI Anthropic
// publisher endpoints look like
// `POST /v1beta1/projects/{p}/locations/{l}/publishers/anthropic/models/{m}:rawPredict`
@@ -296,6 +303,7 @@ pub fn build_app(state: AppState) -> Router {
"/v1beta1/projects/{project}/locations/{location}/publishers/anthropic/models/{model_action}",
post(crate::vertex::handle_vertex_predict_dispatch),
);
}
// PR-D3: Prometheus scrape endpoint. Renders the global registry in
// text format. The handler is stateless — no `AppState` needed — and
@@ -319,7 +327,7 @@ pub fn build_app(state: AppState) -> Router {
router = router.merge(metrics_router);
// PR-D1: native AWS Bedrock InvokeModel route. Mounts only when
// `enable_bedrock_native` is on (default). The handler runs the
// `enable_bedrock_native` is on (off by default). The handler runs the
// live-zone compressor over Anthropic-shape bodies, signs with
// SigV4, and forwards to the configured Bedrock endpoint. The
// `/converse` route mounts the same handler — the wire shape is
@@ -377,11 +385,11 @@ pub fn build_app(state: AppState) -> Router {
);
}
} else {
tracing::warn!(
tracing::info!(
event = "bedrock_native_disabled",
"Bedrock native InvokeModel route disabled by \
--enable-bedrock-native=false; Bedrock requests will fall \
through to the catch-all (no SigV4 re-signing — fails closed)"
"Bedrock native InvokeModel route not mounted \
(--enable-bedrock-native=false, the default); Bedrock requests \
fall through to the catch-all (no SigV4 re-signing)"
);
}
@@ -425,7 +433,17 @@ pub fn build_app(state: AppState) -> Router {
);
}
router.fallback(any(catch_all)).with_state(state)
// Inbound gate (caller locality + optional HEADROOM_PROXY_TOKEN).
// Applied last so it wraps every route and the fallback: the upstream
// Python proxy sees this process as a loopback caller and cannot tell
// who the real peer is itself.
let router = router
.fallback(any(catch_all))
.layer(axum::middleware::from_fn_with_state(
state.config.proxy_token.clone(),
crate::inbound_auth::inbound_gate,
));
router.with_state(state)
}
/// Catch-all handler. If the request is a WebSocket upgrade, hand off to the
@@ -647,6 +665,21 @@ pub(crate) async fn forward_http(
outgoing_headers.insert(http::header::HOST, h.clone());
}
}
// The upstream (the Python proxy) sees this process as a loopback
// peer; never also hand it a loopback Host for a caller that is not
// local here, or its local-only routes would treat that caller as local.
if req
.extensions()
.get::<crate::inbound_auth::NonLocalCaller>()
.is_some()
{
if let Some(host) = crate::inbound_auth::host_override_for_non_local(
outgoing_headers.get(http::header::HOST),
&state.config.upstream,
) {
outgoing_headers.insert(http::header::HOST, host);
}
}
// ─── COMPRESSION GATE ──────────────────────────────────────────────
//
@@ -224,6 +224,24 @@ pub(crate) async fn forward_vertex_request(
}
// ─── 4. RESOLVE BEARER TOKEN ───────────────────────────────────────
// The ADC bearer is this host's Google identity: only send it to a
// Google API host unless the operator explicitly allowed otherwise.
if !state.config.vertex_allow_non_google_upstream && !is_google_api_host(&state.config.upstream)
{
tracing::error!(
event = "vertex_upstream_not_google",
request_id = %request_id,
upstream_host = state.config.upstream.host_str().unwrap_or(""),
"native Vertex route needs --upstream on https://*.googleapis.com \
(or --vertex-allow-non-google-upstream=true); refusing to attach \
the ADC bearer"
);
capture::finalize_rejected(pending_stats.take());
return error_response(
StatusCode::BAD_GATEWAY,
"vertex upstream is not a Google API host",
);
}
let bearer = match state.vertex_token_source.bearer().await {
Ok(t) => t,
Err(e) => {
@@ -471,6 +489,14 @@ pub(crate) async fn forward_vertex_request(
response
}
/// `https://` plus a host under `googleapis.com` (regional
/// `{region}-aiplatform.googleapis.com`, global, and Private Service
/// Connect `*.p.googleapis.com` endpoints).
fn is_google_api_host(upstream: &url::Url) -> bool {
upstream.scheme() == "https"
&& matches!(upstream.host(), Some(url::Host::Domain(h)) if h.ends_with(".googleapis.com"))
}
fn error_response(status: StatusCode, msg: &'static str) -> Response {
Response::builder()
.status(status)
@@ -534,3 +560,28 @@ async fn run_anthropic_sse_state_machine(
p.finalize(capture::usage_from_anthropic_state(&state));
}
}
#[cfg(test)]
mod tests {
use super::is_google_api_host;
#[test]
fn google_api_host_check() {
for ok in [
"https://us-central1-aiplatform.googleapis.com",
"https://aiplatform.googleapis.com/",
"https://aiplatform-x.p.googleapis.com",
] {
assert!(is_google_api_host(&ok.parse().unwrap()), "{ok}");
}
for bad in [
"http://us-central1-aiplatform.googleapis.com",
"https://googleapis.com.example.net",
"https://example-googleapis.com",
"https://127.0.0.1:8788",
"http://127.0.0.1:8788",
] {
assert!(!is_google_api_host(&bad.parse().unwrap()), "{bad}");
}
}
}
@@ -0,0 +1,61 @@
//! Startup bind policy, driven through the real binary.
//!
//! Same rule as the Python proxy (`headroom/proxy/bind_policy.py`): a
//! non-loopback `--listen` with no `HEADROOM_PROXY_TOKEN` must not start
//! unless `HEADROOM_ALLOW_UNAUTHENTICATED_BIND` acknowledges it.
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Command;
fn proxy(listen: &str) -> Command {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_headroom-proxy"));
cmd.args(["--listen", listen, "--upstream", "http://127.0.0.1:9"])
.env_remove("HEADROOM_PROXY_TOKEN")
.env_remove("HEADROOM_ALLOW_UNAUTHENTICATED_BIND")
.env_remove("HEADROOM_PROXY_LISTEN")
.env("HEADROOM_PROXY_STATS", "false")
.stdout(Stdio::null())
.stderr(Stdio::piped())
.kill_on_drop(true);
cmd
}
#[tokio::test]
async fn non_loopback_listen_without_token_refuses_to_start() {
let child = proxy("0.0.0.0:0").spawn().expect("spawn proxy");
let out = tokio::time::timeout(Duration::from_secs(20), child.wait_with_output())
.await
.expect("proxy kept running on 0.0.0.0 with no inbound token")
.expect("wait");
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("HEADROOM_PROXY_TOKEN"), "{stderr}");
assert!(
stderr.contains("HEADROOM_ALLOW_UNAUTHENTICATED_BIND"),
"{stderr}"
);
}
#[tokio::test]
async fn loopback_listen_without_token_still_starts() {
let mut child = proxy("127.0.0.1:0").spawn().expect("spawn proxy");
tokio::time::sleep(Duration::from_secs(2)).await;
assert!(
child.try_wait().expect("try_wait").is_none(),
"loopback bind must start without a token"
);
let _ = child.kill().await;
}
#[test]
fn default_listen_address_is_loopback() {
use clap::Parser;
use headroom_proxy::config::CliArgs;
let args = CliArgs::try_parse_from(["headroom-proxy", "--upstream", "http://127.0.0.1:9"])
.expect("parse");
if std::env::var_os("HEADROOM_PROXY_LISTEN").is_none() {
assert!(args.listen.ip().is_loopback(), "{}", args.listen);
}
}
@@ -0,0 +1,144 @@
//! The native Bedrock and Vertex routes attach this host's cloud
//! credentials (SigV4 / Google ADC bearer) to whatever request reaches
//! them. They are mounted only on explicit opt-in, the Vertex bearer
//! goes only to a Google API host, and the ADC token source uses the
//! configured scope.
mod common;
use std::net::SocketAddr;
use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::{Request, StatusCode};
use clap::Parser;
use headroom_proxy::config::CliArgs;
use headroom_proxy::{build_app, AppState, Config};
use tower::util::ServiceExt;
use wiremock::matchers::any;
use wiremock::{Mock, MockServer, ResponseTemplate};
const HOST_BEARER: &str = "ya29.host-adc-bearer";
const VERTEX_PREFIX: &str =
"/v1beta1/projects/p/locations/us-central1/publishers/anthropic/models/m";
const BODY: &str = r#"{"anthropic_version":"vertex-2023-10-16","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}"#;
async fn upstream() -> MockServer {
let server = MockServer::start().await;
Mock::given(any())
.respond_with(ResponseTemplate::new(200).set_body_string("{}"))
.mount(&server)
.await;
server
}
/// The production defaults, as `main` builds them from the command line.
fn default_config(upstream: &MockServer) -> Config {
let args = CliArgs::try_parse_from(["headroom-proxy", "--upstream", &upstream.uri()])
.expect("parse defaults");
let mut config = Config::from_cli(args);
// Keep any Bedrock signing on the mock, and stats in memory.
config.bedrock_endpoint = Some(upstream.uri().parse().unwrap());
config.stats_path = None;
config
}
/// POST `path` with host AWS credentials and a host ADC bearer both
/// available to the proxy, as they would be on a cloud VM.
async fn post(config: Config, path: &str) -> StatusCode {
let state = AppState::new(config)
.expect("app state")
.with_bedrock_credentials(common::test_credentials());
let app = build_app(common::install_static_token_source(state, HOST_BEARER));
let mut req = Request::post(path)
.header("content-type", "application/json")
.body(Body::from(BODY))
.unwrap();
let peer: SocketAddr = "127.0.0.1:40000".parse().unwrap();
req.extensions_mut().insert(ConnectInfo(peer));
app.oneshot(req).await.unwrap().status()
}
async fn authorizations(upstream: &MockServer) -> Vec<String> {
upstream
.received_requests()
.await
.unwrap()
.iter()
.filter_map(|r| r.headers.get("authorization"))
.map(|v| v.to_str().unwrap().to_owned())
.collect()
}
#[tokio::test]
async fn default_config_does_not_sign_bedrock_requests() {
let up = upstream().await;
let verbs = [
"invoke",
"invoke-with-response-stream",
"converse",
"converse-stream",
];
for verb in verbs {
post(
default_config(&up),
&format!("/model/anthropic.claude-3-haiku-20240307-v1:0/{verb}"),
)
.await;
}
// Every request reached the upstream, so the check below is not vacuous.
assert_eq!(up.received_requests().await.unwrap().len(), verbs.len());
let auth = authorizations(&up).await;
assert!(
auth.iter().all(|a| !a.starts_with("AWS4-HMAC-SHA256")),
"host AWS credentials signed a request by default: {auth:?}"
);
}
#[tokio::test]
async fn default_config_never_attaches_host_adc_bearer() {
let up = upstream().await;
for verb in ["rawPredict", "streamRawPredict"] {
post(default_config(&up), &format!("{VERTEX_PREFIX}:{verb}")).await;
}
assert_eq!(up.received_requests().await.unwrap().len(), 2);
let auth = authorizations(&up).await;
assert!(
auth.iter().all(|a| !a.contains(HOST_BEARER)),
"host ADC bearer sent by default: {auth:?}"
);
}
#[tokio::test]
async fn vertex_bearer_is_not_sent_to_a_non_google_upstream() {
let up = upstream().await;
let mut config = default_config(&up);
config.enable_vertex_native = true;
let status = post(config, &format!("{VERTEX_PREFIX}:rawPredict")).await;
assert_eq!(status, StatusCode::BAD_GATEWAY);
assert!(up.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn vertex_opt_in_still_signs_when_non_google_upstream_is_allowed() {
let up = upstream().await;
let mut config = default_config(&up);
config.enable_vertex_native = true;
config.vertex_allow_non_google_upstream = true;
let status = post(config, &format!("{VERTEX_PREFIX}:rawPredict")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
authorizations(&up).await,
vec![format!("Bearer {HOST_BEARER}")]
);
}
#[test]
fn configured_adc_scope_reaches_token_source() {
let mut config = Config::for_test("http://127.0.0.1:9".parse().unwrap());
config.vertex_adc_scope = "https://www.googleapis.com/auth/test-narrow-scope".into();
let state = AppState::new(config).expect("app state");
// `GcpAdcTokenSource`'s Debug prints its scope; no GCP call is made.
let debug = format!("{:?}", state.vertex_token_source);
assert!(debug.contains("test-narrow-scope"), "{debug}");
}
@@ -0,0 +1,290 @@
//! Inbound `HEADROOM_PROXY_TOKEN` gate.
//!
//! The Rust front connects to the Python proxy from `127.0.0.1`, so
//! Python's own token gate (which exempts loopback peers) cannot see a
//! network caller behind it. These tests pin that the Rust proxy checks
//! the token itself, before any upstream contact, using the same
//! credential rules as the Python gate. The app is driven with
//! `oneshot` and an injected `ConnectInfo` so a non-loopback peer can be
//! simulated; a real loopback-only test listener cannot produce one.
use std::net::SocketAddr;
use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::{Request, StatusCode};
use headroom_proxy::inbound_auth::ProxyToken;
use headroom_proxy::{build_app, AppState, Config};
use tower::util::ServiceExt;
use wiremock::matchers::any;
use wiremock::{Mock, MockServer, ResponseTemplate};
const TOKEN: &str = "s3cret-token";
// 203.0.113.0/24 is TEST-NET-3 (RFC 5737): never loopback.
const REMOTE: &str = "203.0.113.7:40000";
const LOCAL: &str = "127.0.0.1:40000";
async fn upstream() -> MockServer {
let server = MockServer::start().await;
Mock::given(any())
.respond_with(ResponseTemplate::new(200).set_body_string("upstream"))
.mount(&server)
.await;
server
}
async fn send(
upstream: &MockServer,
token: Option<&str>,
peer: Option<&str>,
method: &str,
path: &str,
headers: &[(&str, &str)],
) -> StatusCode {
let mut config = Config::for_test(upstream.uri().parse().unwrap());
config.proxy_token = token.and_then(ProxyToken::new);
let app = build_app(AppState::new(config).unwrap());
let mut builder = Request::builder().method(method).uri(path);
for (k, v) in headers {
builder = builder.header(*k, *v);
}
let mut req = builder.body(Body::empty()).unwrap();
if let Some(peer) = peer {
let addr: SocketAddr = peer.parse().unwrap();
req.extensions_mut().insert(ConnectInfo(addr));
}
app.oneshot(req).await.unwrap().status()
}
#[tokio::test]
async fn remote_peer_without_token_gets_401_and_upstream_is_not_contacted() {
let up = upstream().await;
let status = send(
&up,
Some(TOKEN),
Some(REMOTE),
"GET",
"/admin/upstream",
&[],
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert!(up.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn remote_peer_with_wrong_token_gets_401() {
let up = upstream().await;
for header in [
("x-headroom-proxy-token", "wrong"),
("authorization", "Bearer wrong"),
] {
let status = send(
&up,
Some(TOKEN),
Some(REMOTE),
"POST",
"/v1/messages",
&[header],
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED, "{header:?}");
}
assert!(up.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn remote_peer_with_token_header_is_forwarded_without_it() {
let up = upstream().await;
let status = send(
&up,
Some(TOKEN),
Some(REMOTE),
"GET",
"/v1/models",
&[("x-headroom-proxy-token", TOKEN)],
)
.await;
assert_eq!(status, StatusCode::OK);
let seen = up.received_requests().await.unwrap();
assert_eq!(seen.len(), 1);
assert!(seen[0].headers.get("x-headroom-proxy-token").is_none());
}
#[tokio::test]
async fn remote_peer_with_bearer_token_is_forwarded_without_it() {
let up = upstream().await;
let bearer = format!("bearer {TOKEN}");
let status = send(
&up,
Some(TOKEN),
Some(REMOTE),
"GET",
"/v1/models",
&[("authorization", &bearer)],
)
.await;
assert_eq!(status, StatusCode::OK);
let seen = up.received_requests().await.unwrap();
assert_eq!(seen.len(), 1);
// The proxy credential is not the provider's business.
assert!(seen[0].headers.get("authorization").is_none());
}
#[tokio::test]
async fn token_header_wins_over_a_provider_bearer() {
// Same rule as Python's read_proxy_token: when the explicit header is
// present, Authorization belongs to the provider and is forwarded.
let up = upstream().await;
let status = send(
&up,
Some(TOKEN),
Some(REMOTE),
"GET",
"/v1/models",
&[
("x-headroom-proxy-token", TOKEN),
("authorization", "Bearer provider-key"),
],
)
.await;
assert_eq!(status, StatusCode::OK);
let seen = up.received_requests().await.unwrap();
assert_eq!(
seen[0].headers.get("authorization").unwrap(),
"Bearer provider-key"
);
}
#[tokio::test]
async fn loopback_peer_without_token_is_still_forwarded() {
let up = upstream().await;
let status = send(&up, Some(TOKEN), Some(LOCAL), "GET", "/v1/models", &[]).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(up.received_requests().await.unwrap().len(), 1);
}
#[tokio::test]
async fn ipv4_mapped_loopback_peer_counts_as_loopback() {
let up = upstream().await;
let status = send(
&up,
Some(TOKEN),
Some("[::ffff:127.0.0.1]:40000"),
"GET",
"/v1/models",
&[],
)
.await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn missing_peer_address_fails_closed() {
let up = upstream().await;
let status = send(&up, Some(TOKEN), None, "GET", "/v1/models", &[]).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert!(up.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn health_probes_stay_reachable_without_token() {
let up = upstream().await;
assert_eq!(
send(&up, Some(TOKEN), Some(REMOTE), "GET", "/healthz", &[]).await,
StatusCode::OK
);
assert_eq!(
send(&up, Some(TOKEN), Some(REMOTE), "GET", "/readyz", &[]).await,
StatusCode::OK
);
// Only GET is exempt, as in the Python gate: anything else on a probe
// path would fall through to the relay.
assert_eq!(
send(&up, Some(TOKEN), Some(REMOTE), "POST", "/readyz", &[]).await,
StatusCode::UNAUTHORIZED
);
}
#[tokio::test]
async fn no_token_configured_keeps_todays_passthrough() {
let up = upstream().await;
let status = send(&up, None, Some(REMOTE), "GET", "/v1/models", &[]).await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn hello_probe_is_answered_locally_without_token() {
let up = upstream().await;
for method in ["GET", "HEAD"] {
let status = send(&up, Some(TOKEN), Some(REMOTE), method, "/api/hello", &[]).await;
assert_eq!(status, StatusCode::OK, "{method}");
}
assert!(up.received_requests().await.unwrap().is_empty());
}
/// `Host` the upstream received for one request.
async fn upstream_host(
token: Option<&str>,
peer: &str,
path: &str,
headers: &[(&str, &str)],
) -> String {
let up = upstream().await;
let status = send(&up, token, Some(peer), "GET", path, headers).await;
assert_eq!(status, StatusCode::OK);
let seen = up.received_requests().await.unwrap();
seen[0]
.headers
.get("host")
.unwrap()
.to_str()
.unwrap()
.to_owned()
}
fn is_loopback_name(host: &str) -> bool {
host.starts_with("127.") || host.starts_with("localhost") || host.starts_with("[::1]")
}
#[tokio::test]
async fn local_caller_keeps_the_rewritten_upstream_host() {
let host = upstream_host(
None,
LOCAL,
"/admin/upstream",
&[("host", "127.0.0.1:8787")],
)
.await;
assert!(is_loopback_name(&host), "{host}");
}
#[tokio::test]
async fn loopback_peer_with_a_foreign_host_is_not_relayed_as_local() {
// A browser reaching the port through a name that resolves to
// 127.0.0.1: loopback peer, foreign Host.
let host = upstream_host(
None,
LOCAL,
"/admin/upstream",
&[("host", "evil.example:8787")],
)
.await;
assert_eq!(host, "headroom-remote.invalid");
}
#[tokio::test]
async fn remote_token_holder_is_not_relayed_as_local() {
// `[::1%lo]` is a scoped IPv6 literal the Python proxy accepts as
// loopback; it must not be passed through.
for client_host in ["proxy.example:8787", "localhost:8787", "[::1%lo]:8787"] {
let host = upstream_host(
Some(TOKEN),
REMOTE,
"/admin/upstream",
&[("x-headroom-proxy-token", TOKEN), ("host", client_host)],
)
.await;
assert_eq!(host, "headroom-remote.invalid", "{client_host}");
}
}
+178 -59
View File
@@ -1,7 +1,7 @@
/**
* Self-check for scheduled()'s hourly compaction. node test-rollup.mjs [dir]
* Self-check for the hourly compaction. node test-rollup.mjs [dir]
*
* The one thing that must never drift: rollupHour() and the QUALIFY in
* The one thing that must never drift: the rollup and the QUALIFY in
* headroom-beacon-stats/beacon.sh have to agree on which heartbeat wins. If
* they disagree the reports get quietly wrong rather than loudly broken, so
* this asserts the JS picks exactly the max-seq row per (install, session).
@@ -13,21 +13,21 @@
*/
import { readdirSync, readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import worker, { inflate, oldestRawDay, rollupHour } from './worker.js';
import worker, { finalizeHour, inflate, oldestRawDay, rollupSlice } from './worker.js';
// R2 returns at most 1000 keys per list page, so on a real hour (~4,000
// objects) the cursor loop in rollupHour is load-bearing. The stub paginates at
// a deliberately tiny size so that loop is exercised by every case below: with
// a single-page stub, a regression that dropped the cursor would still print
// "ok" while silently rolling up only the first page of every hour.
// R2 returns at most 1000 keys per list page, so on a real slice the cursor
// loop is load-bearing. The stub paginates at a deliberately tiny size so that
// loop is exercised by every case below: with a single-page stub, a regression
// that dropped the cursor would still print "ok" while silently rolling up only
// the first page of every slice.
const PAGE = 3;
const SLICES = '0123456789abcdef';
/** The slice of the R2 binding rollupHour uses, backed by a plain object. */
/** The slice of the R2 binding the rollup uses, backed by a plain object. */
function stubBucket(files, { failKeys = new Set() } = {}) {
const written = {};
const reads = [];
return {
written,
files,
reads,
list: async ({ prefix, cursor, delimiter }) => {
const keys = Object.keys(files)
@@ -45,7 +45,7 @@ function stubBucket(files, { failKeys = new Set() } = {}) {
const page = keys.slice(start, start + PAGE);
const next = start + PAGE;
return {
objects: page.map((key) => ({ key })),
objects: page.map((key) => ({ key, uploaded: files[key].uploaded ?? new Date(0) })),
truncated: next < keys.length,
cursor: next < keys.length ? keys[next] : undefined,
};
@@ -54,10 +54,14 @@ function stubBucket(files, { failKeys = new Set() } = {}) {
reads.push(key);
if (failKeys.has(key)) throw new Error(`simulated R2 failure: ${key}`);
if (!(key in files)) return null;
return { text: async () => files[key] };
return { text: async () => String(files[key]) };
},
head: async (key) => (key in files ? { key } : null),
put: async (key, body) => {
written[key] = body;
files[key] = body;
},
delete: async (keys) => {
for (const key of keys) delete files[key];
},
};
}
@@ -67,30 +71,31 @@ const beacon = (install, id, seq) =>
const PART = 'dt=2026-08-06/hh=14';
/** Run rollupHour against a stub bucket and decode whatever it wrote. */
/** Roll every slice of PART, merge, and decode whatever landed under rollup/. */
async function run(files, opts = {}) {
const CORPUS = stubBucket(files, opts);
const spend = { read: 0 };
const CORPUS = stubBucket({ ...files }, opts);
let threw = null;
let out = null;
try {
out = await rollupHour({ CORPUS }, PART, spend);
for (const slice of SLICES) await rollupSlice({ CORPUS }, PART, slice);
await finalizeHour({ CORPUS }, PART);
} catch (err) {
threw = err;
}
const body = CORPUS.written[`rollup/${PART}/data.ndjson`];
const body = CORPUS.files[`rollup/${PART}/data.ndjson`];
return {
threw,
spend,
wrote: out ? out.wrote : 0,
empty: `rollup/${PART}/empty` in CORPUS.written,
keys: Object.keys(CORPUS.written),
rawReads: CORPUS.reads.filter((k) => k.startsWith('sessions/')).length,
empty: `rollup/${PART}/empty` in CORPUS.files,
rolled: Object.keys(CORPUS.files).filter((k) => k.startsWith('rollup/')),
parts: Object.keys(CORPUS.files).filter((k) => k.startsWith('rollup-parts/')),
rows: body ? body.split('\n').map((l) => JSON.parse(l)) : [],
};
}
// 1. Highest seq wins, out-of-order input, one row per (install, session).
// More objects than PAGE, so the list cursor loop runs.
// 1. Highest seq wins across slices, out-of-order input, one row per
// (install, session). The names start with different hex characters, so one
// session's heartbeats land in different slices and only the merge can pick
// the winner.
{
const files = {
[`sessions/${PART}/a.json`]: [beacon('i1', 's1', 3), beacon('i1', 's2', 1)].join('\n'),
@@ -99,18 +104,21 @@ async function run(files, opts = {}) {
// Same session id under a different install must not collapse together.
[`sessions/${PART}/d.json`]: beacon('i2', 's1', 2),
[`sessions/${PART}/e.json`]: beacon('i1', 's1', 5),
// Four in one slice, so that slice spans list pages.
[`sessions/${PART}/f1.json`]: beacon('i3', 's1', 1),
[`sessions/${PART}/f2.json`]: beacon('i3', 's1', 4),
[`sessions/${PART}/f3.json`]: beacon('i3', 's1', 2),
[`sessions/${PART}/f4.json`]: beacon('i3', 's1', 3),
};
const { rows, spend, threw } = await run(files);
const { rows, rawReads, threw, parts } = await run(files);
assert.equal(threw, null);
// 5 objects at PAGE=3 is two pages: proves the cursor loop, which is
// load-bearing at the real ~4,000 objects/hour.
assert.ok(Object.keys(files).length > PAGE, 'fixture must span pages');
assert.equal(spend.read, 5, 'reads every object across every page');
assert.equal(rows.length, 3, 'one row per (install, session)');
assert.equal(rawReads, 9, 'reads every object across every slice and page');
assert.equal(rows.length, 4, 'one row per (install, session)');
const seq = Object.fromEntries(
rows.map((r) => [`${r.resource['headroom.install_id']} ${r.session.id}`, r.session.seq])
);
assert.deepEqual(seq, { 'i1 s1': 9, 'i1 s2': 1, 'i2 s1': 2 });
assert.deepEqual(seq, { 'i1 s1': 9, 'i1 s2': 1, 'i2 s1': 2, 'i3 s1': 4 });
assert.deepEqual(parts, [], 'parts are removed once the hour is merged');
}
// 2. An unparseable record loses only itself. Content this Worker wrote with
@@ -121,47 +129,143 @@ async function run(files, opts = {}) {
[`sessions/${PART}/a.json`]: '{ this is not json',
[`sessions/${PART}/b.json`]: `\n${beacon('i1', 's1', 4)}\n`,
};
const { rows, threw } = await run(files);
assert.equal(threw, null, 'corrupt content does not abandon the hour');
assert.deepEqual(rows.map((r) => r.session.seq), [4], 'survives a corrupt object');
const quiet = console.error;
console.error = () => {};
let result;
try {
result = await run(files);
} finally {
console.error = quiet;
}
assert.equal(result.threw, null, 'corrupt content does not abandon the hour');
assert.deepEqual(result.rows.map((r) => r.session.seq), [4], 'survives a corrupt object');
}
// 3. A failed get is transient, so the hour must NOT be written — a rollup is
// 3. A failed get is transient, so its slice must NOT be written — a rollup is
// built once and then trusted forever, so a short read would silently become
// the permanent record.
// the permanent record. The slices that did read keep their parts, which is
// the point: a retry redoes one slice, not the hour.
{
const files = {
[`sessions/${PART}/a.json`]: beacon('i1', 's1', 1),
[`sessions/${PART}/b.json`]: beacon('i1', 's2', 1),
};
const { threw, keys } = await run(files, {
failKeys: new Set([`sessions/${PART}/b.json`]),
});
assert.ok(threw, 'a failed get throws so the hour is retried');
assert.deepEqual(keys, [], 'nothing written on a partial read');
const CORPUS = stubBucket({ ...files }, { failKeys: new Set([`sessions/${PART}/b.json`]) });
await rollupSlice({ CORPUS }, PART, 'a');
await assert.rejects(() => rollupSlice({ CORPUS }, PART, 'b'), /simulated R2 failure/);
assert.equal(await finalizeHour({ CORPUS }, PART), false, 'no merge while a slice is missing');
const keys = Object.keys(CORPUS.files);
assert.ok(!keys.some((k) => k.startsWith('rollup/')), 'nothing published on a partial read');
assert.ok(keys.includes(`rollup-parts/${PART}/a`), 'the slice that read cleanly is kept');
assert.ok(!keys.includes(`rollup-parts/${PART}/b`), 'the failed slice wrote nothing');
}
// 4. Spend is reported even when the hour throws. Charging a flat guess instead
// lets a run that failed late overshoot the subrequest ceiling.
// 4. scheduled() enqueues one message per slice for every hour with no rollup,
// and leaves alone both finished hours and hours it enqueued recently —
// otherwise every cron run would enqueue the whole in-flight backlog again.
// queue() then turns those messages into the rollup.
{
const files = Object.fromEntries(
Array.from({ length: 7 }, (_, i) => [`sessions/${PART}/o${i}.json`, beacon('i1', `s${i}`, 1)])
);
const { threw, spend } = await run(files, {
failKeys: new Set([`sessions/${PART}/o6.json`]),
const at = Date.parse('2026-08-06T15:05:00Z');
const CORPUS = stubBucket({
'sessions/dt=2026-08-06/hh=12/a.json': beacon('i1', 's1', 1),
'sessions/dt=2026-08-06/hh=13/a.json': beacon('i1', 's2', 1),
'sessions/dt=2026-08-06/hh=14/a.json': beacon('i1', 's3', 2),
'sessions/dt=2026-08-06/hh=14/b.json': beacon('i1', 's3', 6),
'rollup/dt=2026-08-06/hh=12/data.ndjson': beacon('i1', 's1', 1),
'rollup-parts/dt=2026-08-06/hh=13/queued': Object.assign(new String(''), {
uploaded: new Date(at - 3600_000),
}),
});
assert.ok(threw);
assert.equal(spend.read, 7, 'caller sees real spend, not a guess');
const sent = [];
const env = { CORPUS, ROLLUP_QUEUE: { sendBatch: async (msgs) => sent.push(...msgs) } };
await worker.scheduled({ scheduledTime: at }, env);
const hours = (h) => sent.filter((m) => m.body.part === `dt=2026-08-06/hh=${h}`);
assert.deepEqual(hours('14').map((m) => m.body.slice).join(''), SLICES, 'every slice of the missing hour');
assert.equal(hours('12').length, 0, 'a finished hour is not enqueued');
assert.equal(hours('13').length, 0, 'an hour enqueued an hour ago is not enqueued again');
assert.equal(hours('00').length, 16, 'backfill reaches the start of the oldest raw day');
const acked = [];
const messages = hours('14').map((m) => ({
body: m.body,
ack: () => acked.push(m.body.slice),
retry: () => assert.fail(`slice ${m.body.slice} was retried`),
}));
await worker.queue({ messages }, env);
assert.equal(acked.length, 16);
const row = JSON.parse(CORPUS.files[`rollup/${PART}/data.ndjson`]);
assert.equal(row.session.seq, 6, 'the queue path publishes the merged hour');
// A redelivered message for a finished hour must not write a part: nothing
// would ever merge or remove it.
await worker.queue({ messages: [messages[0]] }, env);
assert.ok(!Object.keys(CORPUS.files).some((k) => k.startsWith(`rollup-parts/${PART}/`)));
}
// 4b. The recovery paths. An hour enqueued longer ago than the re-enqueue
// window is sent again; a slice that fails is handed back to the queue, not
// acknowledged; a second copy of a finished slice reuses its part instead
// of reading the slice again; and whatever a finished hour left under
// rollup-parts/ is swept, because nothing else would ever remove it.
{
const at = Date.parse('2026-08-06T15:05:00Z');
const stale = (hoursAgo) =>
Object.assign(new String(''), { uploaded: new Date(at - hoursAgo * 3600_000) });
const CORPUS = stubBucket(
{
'sessions/dt=2026-08-06/hh=13/a.json': beacon('i1', 's2', 1),
'sessions/dt=2026-08-06/hh=14/a.json': beacon('i1', 's3', 2),
'sessions/dt=2026-08-06/hh=14/b.json': beacon('i1', 's3', 6),
'rollup/dt=2026-08-06/hh=13/data.ndjson': beacon('i1', 's2', 1),
'rollup-parts/dt=2026-08-06/hh=13/queued': stale(1),
'rollup-parts/dt=2026-08-06/hh=13/a': beacon('i1', 's2', 1),
'rollup-parts/dt=2026-08-06/hh=14/queued': stale(4),
},
{ failKeys: new Set(['sessions/dt=2026-08-06/hh=14/b.json']) }
);
const sent = [];
const env = { CORPUS, ROLLUP_QUEUE: { sendBatch: async (msgs) => sent.push(...msgs) } };
await worker.scheduled({ scheduledTime: at }, env);
assert.equal(
sent.filter((m) => m.body.part === PART).length,
16,
'an hour enqueued four hours ago is enqueued again'
);
assert.ok(
!Object.keys(CORPUS.files).some((k) => k.startsWith('rollup-parts/dt=2026-08-06/hh=13/')),
'leftovers of a finished hour are swept'
);
const outcome = [];
const message = (slice) => ({
body: { part: PART, slice },
ack: () => outcome.push(`ack ${slice}`),
retry: (opts) => outcome.push(`retry ${slice} ${opts.delaySeconds}`),
});
const quiet = console.error;
console.error = () => {};
try {
await worker.queue({ messages: [message('a'), message('b')] }, env);
} finally {
console.error = quiet;
}
assert.deepEqual(outcome, ['ack a', 'retry b 60'], 'a failed slice goes back to the queue');
const before = CORPUS.reads.length;
await worker.queue({ messages: [message('a')] }, env);
assert.equal(CORPUS.reads.length, before, 'a finished slice is not read a second time');
}
// 5. An empty hour writes a marker, not a zero-byte NDJSON. Without it the hour
// stays "missing" and is re-listed on every run forever.
// stays "missing" and is enqueued again on every run forever.
{
const { rows, empty, keys } = await run({});
const { rows, empty, rolled } = await run({});
assert.deepEqual(rows, []);
assert.ok(empty, 'empty hour leaves a marker');
assert.ok(
keys.every((k) => !k.endsWith('.ndjson')),
rolled.every((k) => !k.endsWith('.ndjson')),
'no zero-byte ndjson for readers to special-case'
);
}
@@ -187,7 +291,7 @@ if (dir) {
for (const f of readdirSync(dir).filter((f) => f.endsWith('.json'))) {
files[`sessions/${PART}/${f}`] = readFileSync(`${dir}/${f}`, 'utf8');
}
const { rows, spend, threw } = await run(files);
const { rows, rawReads, threw } = await run(files);
assert.equal(threw, null);
const expected = new Map();
@@ -199,15 +303,14 @@ if (dir) {
expected.set(k, Math.max(expected.get(k) ?? -1, r.session?.seq ?? 0));
}
}
assert.equal(spend.read, Object.keys(files).length);
assert.equal(rawReads, Object.keys(files).length);
assert.equal(rows.length, expected.size, 'row count matches DISTINCT sessions');
for (const r of rows) {
const k = `${r.resource['headroom.install_id']} ${r.session.id}`;
assert.equal(r.session.seq, expected.get(k), `max seq for ${k}`);
}
console.log(
`real corpus: ${spend.read} objects -> ${rows.length} sessions in 1 object` +
` (${Math.ceil(spend.read / PAGE)} list pages)`
`real corpus: ${rawReads} objects -> ${rows.length} sessions in 1 object`
);
}
@@ -327,6 +430,14 @@ if (dir) {
full.errors = { count: 1, by_status: { 429: 1 } };
full.strata = [{ dim: 'arm', value: 'treatment', n: 2 }];
full.config = [{ key: 'mode', value: 'token' }];
const usage = {
n: 2, original: 9, saved: 3, tool_saved: 1, output: 2, cache_read: 4, cache_write: 1,
cache_write_inferred: 0, cache_write_5m: 1, cache_write_1h: 0, uncached: 4,
};
full.client_usage = [{ client: 'claude_code', ...usage }, { client: 'via_compress_api', ...usage }];
full.model_usage = [{ model: 'claude-haiku-4-5', ...usage }];
full.client_versions = [{ client: 'claude_code', version: '2.1.311', n: 2 }];
full.install = { age_days: 12, container: false, ci: false };
full.routing = { decisions: 3, by_model: [{ model: 'claude-haiku-4-5', n: 3 }], min_prefix: 1024 };
/** One OTLP record through fetch(); returns what would be written to R2. */
@@ -368,6 +479,11 @@ if (dir) {
injected.session.ended = { nested: 'object where a slug belongs' };
injected.routing.note = 'free text with spaces';
injected.trajectory.kinds = 'see attached transcript';
injected.client_usage[0].prompt = 'x'; // unknown key in a usage row
injected.client_usage[1].client = 'Acme Corp Billing'; // not a harness slug
injected.client_versions[0].version = '2.1.311-host.internal'; // not a release number
injected.install.hostname = 'build-7';
injected.install.age_days = 'twelve';
const hostile = [...resourceAttrs.filter((a) => a.key !== 'headroom.stack'),
{ key: 'headroom.stack', value: any({ cwd: '/home/me' }) }];
const { resource: badResource, ...dropped } = await store(injected, hostile);
@@ -375,6 +491,9 @@ if (dir) {
const expected = structuredClone(full);
delete expected.session.ended;
delete expected.trajectory.kinds;
delete expected.client_usage[1].client;
delete expected.client_versions[0].version;
delete expected.install.age_days;
expected.config.push({ key: 'endpoint' });
expected.strata.push({ dim: 'arm', n: 1 });
assert.deepEqual(dropped, expected, 'a nested field outside the allowlist was stored');
+268 -125
View File
@@ -101,6 +101,17 @@ const ALLOWED_KEYS = [
// Allowlisted, slug-validated configuration, so the corpus can tell
// "compression underperformed" from "compression was switched off".
'config',
// The session's tokens split by harness and by model. `clients` and `models`
// only say who took part, so a session that mixed two could not be divided
// or priced. `client_usage` covers every turn: traffic with no identified
// harness is a row of its own instead of a gap.
'client_usage',
'model_usage',
// The harness's own release, numeric parts only.
'client_versions',
// Age of the install id in days, and whether it runs in a container or CI
// job: separates a returning user from an id minted on every run.
'install',
];
// Resource attributes we keep. Same rule: allowlist, not denylist.
@@ -130,6 +141,16 @@ const MAP = Symbol('map');
const mapOf = (spec) => ({ [MAP]: spec });
const nums = (...keys) => Object.fromEntries(keys.map((k) => [k, 'num']));
// A harness name: the client only sends ones from a closed list, so hold the
// field to that shape instead of the wider 'str'.
const SLUG = /^[a-z][a-z0-9_]{0,31}$/;
// One turn-and-token row of `client_usage` / `model_usage`: _USAGE_FIELDS in
// session.py.
const USAGE = nums(
'n', 'original', 'saved', 'tool_saved', 'output', 'cache_read', 'cache_write',
'cache_write_inferred', 'cache_write_5m', 'cache_write_1h', 'uncached'
);
const NESTED = {
schema_version: 'num',
session: {
@@ -187,6 +208,10 @@ const NESTED = {
errors: { count: 'num', by_status: mapOf('num') },
strata: [{ dim: 'str', value: 'str', n: 'num' }],
config: [{ key: 'str', value: 'str' }],
client_usage: [{ client: SLUG, ...USAGE }],
model_usage: [{ model: 'str', ...USAGE }],
client_versions: [{ client: SLUG, version: /^\d{1,4}(?:\.\d{1,4}){0,2}$/, n: 'num' }],
install: { age_days: 'num', container: 'bool', ci: 'bool' },
};
// A key allowed at the top but given no shape would be dropped in full. Fail
@@ -349,114 +374,188 @@ function extract(payload) {
// ----------------------------------------------------------------- rollup --
//
// The corpus is one object per heartbeat, ~1KB each — 65k on 2026-08-06 and
// climbing. DuckDB reads them correctly, but a full `pull` is ~100k HTTPS round
// trips for 95MB: minutes of pure per-object latency, no real bytes or compute.
// Listing the bucket alone took 88 seconds.
// The corpus is one object per heartbeat. Analysis reads rollup/**, never
// sessions/**: each COMPLETE hour is collapsed into one object under rollup/,
// keeping only the highest-seq heartbeat per (install, session). Raw is left
// exactly as written, so any rollup can be rebuilt by deleting it.
//
// This job collapses each COMPLETE hour into one object under rollup/, keeping
// only the highest-seq heartbeat per (install, session). One measured hour
// (dt=2026-08-06/hh=14): 3,938 objects and 3,938 rows in, 1 object and 1,061
// rows out. Analysis reads rollup/**, never sessions/**. Raw is left exactly as
// written, so any rollup can be rebuilt by deleting it.
// One invocation cannot do an hour on its own, and that is measured, not
// feared. A Worker may have six requests in flight, so reads ran at ~12
// objects/s whatever the code asked for, and a cron run is stopped at 15
// minutes: ~11k objects. The fleet passed that on 2026-08-19 and by October 98%
// of hours were being killed mid-read and writing nothing.
//
// Hourly rather than daily because every R2 binding call is a subrequest: a day
// is ~65k of them against a 10k-per-invocation ceiling, an hour is ~4k.
// So an hour is cut into slices and each slice is its own queue message, which
// means its own invocation with its own six connections and its own 15 minutes:
//
// scheduled() finds hours with no rollup and enqueues one message per slice
// rollupSlice() reads one slice, writes rollup-parts/<hour>/<slice>
// finalizeHour() once every slice is in, merges them into rollup/<hour>/
//
// Slices are the first hex character of the object name. Names are
// crypto.randomUUID() (see fetch()), so the sixteen slices are even, and the
// split needs nothing but a LIST prefix — which is also why it works on every
// object already in the bucket. Raise to two characters (256 slices) when a
// slice stops fitting; the per-slice cost falls sixteen-fold.
const READ_BUDGET = 60000; // objects per run; see [limits] in wrangler.toml
// A get costs ~45ms of round trip and almost no CPU, so this is what decides
// whether a run finishes: at 20 an hour took ~3 minutes, against a 15-minute
// wall clock for a cron invocation. Raise it if an hour ever stops fitting.
const FANOUT = 100; // concurrent R2 gets
const SLICES = '0123456789abcdef';
// Requests in flight per invocation. Six is the platform's ceiling: asking for
// more only queues inside the runtime.
const POOL = 6;
// A queued hour that still has no rollup after this long is enqueued again:
// the safety net for a slice that ran out of retries. A second copy of a slice
// that did finish is cheap, because queue() reuses the part already written.
const REQUEUE_AFTER_MS = 3 * 3600_000;
// Hours enqueued per cron run, sized so they drain well inside REQUEUE_AFTER_MS
// (200 hours is 3,200 slices of a couple of minutes each, run in parallel). A
// bigger backlog is not stuck, the next run simply continues it.
const MAX_HOURS_PER_RUN = 200;
// Wait before a failed slice is tried again, so a short R2 outage does not burn
// every retry within seconds.
const RETRY_DELAY_S = 60;
// R2 deletes at most this many keys per call.
const DELETE_BATCH = 1000;
const partition = (d) =>
`dt=${d.toISOString().slice(0, 10)}/hh=${d.toISOString().slice(11, 13)}`;
/**
* One hour of heartbeats -> one deduped NDJSON object.
*
* Returns `{ read, wrote }`. Spend is reported through the mutable `spend`
* accumulator so the caller still knows it even when this throws: the budget
* has to track real spend, and a flat guess lets a run that failed late
* overshoot the subrequest ceiling and get killed inside an hour that would
* otherwise have succeeded.
*
* Writes nothing unless the whole hour read cleanly. A rollup is built once and
* then treated as done forever, so a partial read would silently become the
* permanent record — better to write nothing and let the next run retry.
*/
export async function rollupHour(env, part, spend = { read: 0 }) {
const best = new Map();
let failed = 0; // transient: retry the hour
let corrupt = 0; // permanent: record and move on
/** Every object under a prefix, following the cursor. */
async function listAll(env, options) {
const objects = [];
let cursor;
do {
const page = await env.CORPUS.list({ prefix: `sessions/${part}/`, cursor });
for (let i = 0; i < page.objects.length; i += FANOUT) {
// allSettled, not all: one transient R2 error among the ~4,000 gets in a
// real hour would otherwise reject the batch and discard the whole hour.
const settled = await Promise.allSettled(
page.objects
.slice(i, i + FANOUT)
.map((o) => env.CORPUS.get(o.key).then((r) => (r ? r.text() : null)))
);
for (const outcome of settled) {
spend.read++;
// A miss counts as a failure too. The key came from a LIST, so the
// object existed; treating it as empty would quietly shrink the rollup.
if (outcome.status !== 'fulfilled' || outcome.value === null) {
failed++;
continue;
}
for (const line of outcome.value.split('\n')) {
if (!line) continue;
let rec;
try {
rec = JSON.parse(line);
} catch {
// Counted and logged, but NOT a reason to abandon the hour. A
// failed get is transient and worth retrying; content this Worker
// itself wrote with JSON.stringify does not become valid later, so
// blocking on it would strand the hour until its raw objects
// expire and then lose the whole hour instead of one record.
corrupt++;
continue;
}
// A session heartbeats every 5 minutes carrying CUMULATIVE totals, so
// the highest seq IS the whole session and every earlier row is a
// strict subset. Sessions straddle hours, so readers still dedupe
// across rollups on this same key — this only shrinks each hour.
const id = `${rec.resource?.['headroom.install_id']} ${rec.session?.id}`;
const prev = best.get(id);
if (!prev || (rec.session?.seq ?? 0) > (prev.session?.seq ?? 0)) {
best.set(id, rec);
}
}
}
}
const page = await env.CORPUS.list({ ...options, cursor });
objects.push(...page.objects);
cursor = page.truncated ? page.cursor : undefined;
} while (cursor);
return objects;
}
if (failed) {
throw new Error(`${part}: ${failed} of ${spend.read} objects unreadable`);
/**
* Run `fn` over `items` with at most POOL calls in flight. Rejects on the first
* failure and starts nothing new after it: the slice is going to be retried
* whole, so further reads would be thrown away.
*/
async function pool(items, fn) {
let next = 0;
let failed = false;
const worker = async () => {
while (!failed && next < items.length) {
try {
await fn(items[next++]);
} catch (err) {
failed = true;
throw err;
}
}
};
await Promise.all(Array.from({ length: Math.min(POOL, items.length) }, worker));
}
/**
* Fold NDJSON `text` into `best`, keeping the highest-seq record per session.
* Returns how many lines would not parse.
*
* A session heartbeats every 5 minutes carrying CUMULATIVE totals, so the
* highest seq IS the whole session and every earlier row is a strict subset.
* Sessions straddle hours, so readers still dedupe across rollups on this same
* key — this only shrinks each hour.
*
* The winner is kept as freshly serialised text, not as a slice of `text`: a
* slice would pin the whole source string in memory, and the merge reads
* sixteen of them against a 128MB isolate.
*/
function keepBest(best, text) {
let corrupt = 0;
for (const line of text.split('\n')) {
if (!line) continue;
let rec;
try {
rec = JSON.parse(line);
} catch {
// Counted, but NOT a reason to abandon the slice. Content this Worker
// itself wrote with JSON.stringify does not become valid later, so
// blocking on it would strand the hour instead of losing one record.
corrupt++;
continue;
}
const id = `${rec.resource?.['headroom.install_id']} ${rec.session?.id}`;
const seq = rec.session?.seq ?? 0;
const prev = best.get(id);
if (!prev || seq > prev.seq) best.set(id, { seq, line: JSON.stringify(rec) });
}
return corrupt;
}
const ndjson = (best) => [...best.values()].map((r) => r.line).join('\n');
/** True once an hour has its rollup (or its `empty` marker). */
async function hourDone(env, part) {
const page = await env.CORPUS.list({ prefix: `rollup/${part}/`, limit: 1 });
return page.objects.length > 0;
}
/**
* One slice of one hour -> rollup-parts/<part>/<slice>.
*
* Throws if any listed object cannot be read, and writes nothing: the queue
* redelivers the message, and a part that was short would silently become the
* permanent record once merged. A slice with no objects still writes its (empty)
* part, because "all sixteen present" is what finalizeHour waits for.
*/
export async function rollupSlice(env, part, slice) {
const objects = await listAll(env, { prefix: `sessions/${part}/${slice}` });
const best = new Map();
let corrupt = 0;
await pool(objects, async (o) => {
const body = await env.CORPUS.get(o.key);
// The key came from a LIST, so the object existed; treating a miss as
// empty would quietly shrink the rollup.
if (!body) throw new Error(`${o.key}: listed but unreadable`);
// Folded as it arrives, so only the winners are held, never the slice.
corrupt += keepBest(best, await body.text());
});
if (corrupt) {
console.error(`rollup ${part}: skipped ${corrupt} unparseable record(s)`);
console.error(`rollup ${part}/${slice}: skipped ${corrupt} unparseable record(s)`);
}
await env.CORPUS.put(`rollup-parts/${part}/${slice}`, ndjson(best));
return { read: objects.length, kept: best.size };
}
/**
* Merge an hour's sixteen parts into rollup/<part>/, then remove the parts.
* Returns false, having written nothing, while any slice is still missing.
*
* Safe to run twice at once: both runs read the same parts and write the same
* bytes. The one that loses the race finds a part already deleted and stops.
*/
export async function finalizeHour(env, part) {
const parts = await listAll(env, { prefix: `rollup-parts/${part}/` });
const have = new Set(parts.map((o) => o.key.slice(o.key.lastIndexOf('/') + 1)));
if (![...SLICES].every((s) => have.has(s))) return false;
// One session's heartbeats are spread across slices, so the parts overlap and
// the merge is a real dedupe, not a concatenation. Read one at a time: the
// parts together are several times the size of the result.
const best = new Map();
for (const slice of SLICES) {
const body = await env.CORPUS.get(`rollup-parts/${part}/${slice}`);
if (!body) return false;
keepBest(best, await body.text());
}
// A genuinely empty hour gets a marker rather than a zero-byte NDJSON that
// every reader would have to special-case. Without it the hour stays
// "missing" and is re-listed on every run for the life of the bucket.
// "missing" and is enqueued again for the life of the bucket.
if (best.size === 0) {
await env.CORPUS.put(`rollup/${part}/empty`, '');
return { read: spend.read, wrote: 0 };
} else {
await env.CORPUS.put(`rollup/${part}/data.ndjson`, ndjson(best), {
httpMetadata: { contentType: 'application/x-ndjson' },
});
}
await env.CORPUS.put(
`rollup/${part}/data.ndjson`,
[...best.values()].map((r) => JSON.stringify(r)).join('\n'),
{ httpMetadata: { contentType: 'application/x-ndjson' } }
);
return { read: spend.read, wrote: best.size };
await env.CORPUS.delete(parts.map((o) => o.key));
return true;
}
/** Oldest `dt=` day still under sessions/, or null. One delimited LIST. */
@@ -469,59 +568,102 @@ export async function oldestRawDay(env) {
return days.length ? days[0] : null;
}
/** `dt=…/hh=…` of a key under `prefix`, i.e. everything up to its last slash. */
const partOf = (key, prefix) => key.slice(prefix.length, key.lastIndexOf('/'));
export default {
/** Hourly cron. Builds every complete hour back to the oldest raw data. */
/**
* Hourly cron. Enqueues every complete hour that has no rollup, back to the
* oldest raw data. Does none of the reading itself — see the note above.
*/
async scheduled(event, env) {
// Backfill reaches all the way to the oldest surviving raw day, NOT a fixed
// window. A fixed window silently strands everything older than it the
// moment analysis stopped reading sessions/ — the raw objects are still
// there, but nothing would ever compact them, so they vanish from every
// report. Bounding by real data instead means the floor rises only when a
// lifecycle rule actually expires the raw objects.
// moment analysis stopped reading sessions/. Bounding by real data instead
// means the floor rises only when a lifecycle rule expires the raw objects.
const oldest = await oldestRawDay(env);
if (!oldest) return;
const floorMs = Date.parse(`${oldest}T00:00:00Z`);
if (Number.isNaN(floorMs)) return;
// Only list from the floor forward. Rollups older than the oldest raw day
// can never be rebuilt, so enumerating them answers nothing — this is what
// keeps the listing bounded by retention rather than by total history.
const done = new Set();
let cursor;
do {
const page = await env.CORPUS.list({
prefix: 'rollup/',
startAfter: `rollup/dt=${oldest}`,
cursor,
});
for (const o of page.objects) {
// Tolerates both `<part>/data.ndjson` and the `<part>/empty` marker.
const rel = o.key.slice('rollup/'.length);
const cut = rel.lastIndexOf('/');
if (cut > 0) done.add(rel.slice(0, cut));
}
cursor = page.truncated ? page.cursor : undefined;
} while (cursor);
// can never be rebuilt, so enumerating them answers nothing.
const done = new Set(
(await listAll(env, { prefix: 'rollup/', startAfter: `rollup/dt=${oldest}` })).map((o) =>
partOf(o.key, 'rollup/')
)
);
const inFlight = await listAll(env, { prefix: 'rollup-parts/' });
// Newest first, so a backlog drains from the present backwards and the
// freshest hour is never the one starved by the budget. Starts one hour
// back: the current hour is still being written to.
let budget = READ_BUDGET;
for (let t = event.scheduledTime - 3600_000; t >= floorMs && budget > 0; t -= 3600_000) {
// Sweep what a finished hour left behind. finalizeHour removes its parts,
// but three things can outlive it: a duplicate slice that was still reading
// when the hour was merged, parts whose delete failed after the publish,
// and a `queued` marker written after a very small hour had already merged.
// Nothing else would ever remove them, and this prefix is listed every run.
const leftover = inFlight
.filter((o) => done.has(partOf(o.key, 'rollup-parts/')))
.map((o) => o.key);
for (let i = 0; i < leftover.length; i += DELETE_BATCH) {
await env.CORPUS.delete(leftover.slice(i, i + DELETE_BATCH));
}
// When each in-flight hour was enqueued, so an hour still being worked on
// is not enqueued again every time the cron fires.
const queuedAt = new Map(
inFlight
.filter((o) => o.key.endsWith('/queued'))
.map((o) => [partOf(o.key, 'rollup-parts/'), o.uploaded.getTime()])
);
// Newest first, so the freshest hour is never the one a backlog starves.
// Starts one hour back: the current hour is still being written to.
let enqueued = 0;
for (
let t = event.scheduledTime - 3600_000;
t >= floorMs && enqueued < MAX_HOURS_PER_RUN;
t -= 3600_000
) {
const part = partition(new Date(t));
if (done.has(part)) continue;
// Shared with rollupHour so a throw still reports what it spent.
const spend = { read: 0 };
const at = queuedAt.get(part);
if (at !== undefined && event.scheduledTime - at < REQUEUE_AFTER_MS) continue;
try {
await rollupHour(env, part, spend);
// Marker first: if the send then fails, the hour waits for the
// re-enqueue instead of being sent twice by the next run.
await env.CORPUS.put(`rollup-parts/${part}/queued`, '');
await env.ROLLUP_QUEUE.sendBatch([...SLICES].map((slice) => ({ body: { part, slice } })));
} catch (err) {
// Newest-first means an hour that always throws — one grown past the
// subrequest ceiling, say — would otherwise block every older hour
// behind it forever. Skip it and keep draining; it has no marker, so
// the next run retries it.
console.error(`rollup ${part} failed after ${spend.read} objects: ${err}`);
// One hour failing to enqueue must not end the run for the rest.
console.error(`rollup ${part}: enqueue failed: ${err}`);
}
enqueued++;
}
},
/**
* Queue consumer: one message is one slice of one hour. A slice that throws
* is retried by the queue on its own, so one bad read costs that slice a
* retry instead of costing the hour everything it had already read.
*/
async queue(batch, env) {
for (const message of batch.messages) {
const { part, slice } = message.body;
try {
// A redelivery, or a re-enqueue that raced the merge: nothing to do,
// and writing a part now would leave it behind for good.
if (!(await hourDone(env, part))) {
// The hour is closed, so a part that is already there is still
// right: a second copy of the message only has to try the merge.
if (!(await env.CORPUS.head(`rollup-parts/${part}/${slice}`))) {
await rollupSlice(env, part, slice);
}
await finalizeHour(env, part);
}
message.ack();
} catch (err) {
console.error(`rollup ${part}/${slice} failed: ${err}`);
message.retry({ delaySeconds: RETRY_DELAY_S });
}
budget -= spend.read;
}
},
@@ -600,7 +742,8 @@ export default {
// two independent spellings of this scheme would mean the writer and the
// compactor could drift apart and silently match zero objects.
// ponytail: one object per request. Compacted hourly into rollup/ by
// scheduled() above — analysis reads that, never this.
// the queue consumer above — analysis reads that, never this. The random
// UUID is load-bearing there: its first character is the slice.
const key = `sessions/${partition(new Date())}/${crypto.randomUUID()}.json`;
const ndjson = records.map((r) => JSON.stringify(r)).join('\n');
+38 -9
View File
@@ -33,20 +33,40 @@ bucket_name = "headroom-telemetry"
# Absent = R2 only, which is the right place to start.
# Hourly compaction of sessions/ into rollup/ — see scheduled() in worker.js.
# At :05 so the hour being rolled up is definitely closed. A >=1h interval also
# buys the 15-minute CPU limit instead of 30s, which the backfill run needs.
# At :05 so the hour being rolled up is definitely closed. The cron only
# enqueues; the reading is done by the queue consumer below.
[triggers]
crons = ["5 * * * *"]
# Every R2 binding call is a subrequest, and one hour is already ~4k objects.
# The paid default of 10k would cap a run at two hours and stall the backfill
# behind live traffic forever. This only raises a ceiling; a normal run spends
# ~4k. READ_BUDGET in worker.js is what actually bounds the work.
# One message is one slice (a sixteenth) of one hour. The queues must exist
# before the first deploy that names them:
# npx wrangler queues create beacon-rollup
# npx wrangler queues create beacon-rollup-dlq
# and, for `--env dev`, `npx wrangler queues create beacon-rollup-dev`.
[[queues.producers]]
binding = "ROLLUP_QUEUE"
queue = "beacon-rollup"
# max_batch_size = 1 so every slice is its own invocation: its own six
# connections and its own 15 minutes, which is the entire point of the queue.
# Concurrency is left to autoscale (up to 250), so a backlog drains in parallel.
# A slice that keeps failing lands in the dead-letter queue, where it can be
# inspected by hand until the queue's retention expires it — nothing reads or
# alerts on that queue. scheduled() enqueues the hour again after three hours
# either way, so the dead-letter queue is evidence, not the recovery path.
[[queues.consumers]]
queue = "beacon-rollup"
max_batch_size = 1
max_retries = 5
dead_letter_queue = "beacon-rollup-dlq"
# Every R2 binding call is a subrequest. A slice is ~1.5k reads today, under the
# paid default of 10k, but that default is one fleet doubling or two away. This
# only raises a ceiling.
#
# Workers Paid only — on the Free plan this key is rejected outright ("CPU
# limits are not supported for the Free plan"), and the cron could not run
# anyway: Free gives a scheduled handler 10ms of CPU, and parsing an hour of
# heartbeats is tens of ms.
# limits are not supported for the Free plan"), and Queues are a paid feature
# as well.
[limits]
subrequests = 100000
@@ -93,3 +113,12 @@ namespace_id = "1002"
[env.dev.ratelimits.simple]
limit = 600
period = 60
[[env.dev.queues.producers]]
binding = "ROLLUP_QUEUE"
queue = "beacon-rollup-dev"
[[env.dev.queues.consumers]]
queue = "beacon-rollup-dev"
max_batch_size = 1
max_retries = 5
+2 -2
View File
@@ -109,7 +109,7 @@ result = compressor.compress(code)
| `max_body_lines` | `5` | Max lines to keep per function body |
| `min_tokens_for_compression` | `100` | Skip files smaller than this |
| `language_hint` | `None` | Override language detection |
| `fallback_to_kompress` | `True` | Use Kompress for unsupported languages |
| `fallback_to_kompress` | `True` | Use Kompress for unsupported languages. `ContentRouter` (the proxy and `compress()`) always sets it to `False`, so code it routes is never sent to Kompress |
## Before and After
@@ -169,5 +169,5 @@ unload_tree_sitter()
| Syntax validity | Guaranteed |
<Callout type="info" title="Routing differs between the proxy and the library API">
ContentRouter always *detects* source code automatically, but whether it routes that code to CodeAwareCompressor depends on the entry point. `headroom proxy` enables code-aware routing by default (`HEADROOM_CODE_AWARE_ENABLED` defaults to on; disable with `--no-code-aware` or `HEADROOM_CODE_AWARE_ENABLED=0`). The one-function `compress()` API and `HeadroomClient`, however, build `ContentRouterConfig` with its own default, `enable_code_aware=False` -- there, detected code falls back to Kompress unless you construct your own pipeline with `ContentRouterConfig(enable_code_aware=True)`. Direct usage of `CodeAwareCompressor`, as shown on this page, is unaffected either way. See [How Compression Works](/docs/how-compression-works#content-type-detection).
ContentRouter always *detects* source code automatically, but whether it routes that code to CodeAwareCompressor depends on the entry point. `headroom proxy` enables code-aware routing by default (`HEADROOM_CODE_AWARE_ENABLED` defaults to on; disable with `--no-code-aware` or `HEADROOM_CODE_AWARE_ENABLED=0`). The one-function `compress()` API and `HeadroomClient`, however, build `ContentRouterConfig` with its own default, `enable_code_aware=False` -- there, detected code is left unchanged (it is never handed to the prose model, Kompress, which drops keywords) unless you construct your own pipeline with `ContentRouterConfig(enable_code_aware=True)`. Direct usage of `CodeAwareCompressor`, as shown on this page, is unaffected either way. See [How Compression Works](/docs/how-compression-works#content-type-detection).
</Callout>
+1 -1
View File
@@ -29,7 +29,7 @@ The router auto-detects content type by analyzing structure and patterns. No man
| Content Type | Detection Signal | Compressor | Typical Savings |
|---|---|---|---|
| JSON arrays | Valid JSON with array elements | SmartCrusher | Varies with redundancy -- measured 26-54% on realistic (non-duplicate) tool-output arrays of 100-10,000 items; highly repetitive arrays compress far more. See `benchmarks/compression_benchmark.py`. |
| Source code | Syntax patterns, indentation, keywords | Kompress via the library `compress()`/`HeadroomClient` path (`enable_code_aware` defaults to `False` there); CodeAwareCompressor via `headroom proxy` (`HEADROOM_CODE_AWARE_ENABLED` defaults to on) | workload-dependent |
| Source code | Syntax patterns, indentation, keywords | Left unchanged (passthrough) via the library `compress()`/`HeadroomClient` path (`enable_code_aware` defaults to `False` there); CodeAwareCompressor via `headroom proxy` (`HEADROOM_CODE_AWARE_ENABLED` defaults to on). Source code is never sent to Kompress. | workload-dependent |
| Search results | `file:line:content` format | SearchCompressor | 80-95% (measured ~91% on a synthetic 40-file ripgrep-style corpus) |
| Build/test logs | Timestamps, log levels, pytest/npm markers | LogCompressor | 85-95% (measured ~93% on a synthetic 1,000-line log with clustered errors) |
| Diffs | Unified diff format | DiffCompressor | 60-80% (measured ~70% on a multi-file diff with default `max_context_lines`/`max_hunks_per_file` limits) |
+15 -2
View File
@@ -46,7 +46,9 @@ The command:
2. starts Headroom on `127.0.0.1:8787` with the short-lived upstream token;
3. adds a marker-owned block to VS Code user settings containing
`github.copilot.advanced.debug.overrideProxyUrl` (inline completions) and
`github.copilot.advanced.debug.overrideCapiUrl` (chat);
`github.copilot.advanced.debug.overrideCapiUrl` (chat), plus
`chat.defaultToCopilotHarness` and `chat.editor.preferCopilotHarness` set to
`false` so new chats stay on VS Code's Local harness;
4. keeps running until `Ctrl+C` so the local proxy is available to VS Code.
Continue using Copilot's normal model picker. The request body—and therefore the
@@ -69,6 +71,14 @@ Copilot UI: user selects model M
-> response from model M
```
## Chat harness
A chat running on VS Code's Copilot harness (Agent Host) ignores the endpoint
overrides and bypasses Headroom, so the managed block keeps new chats on the
Local harness. A chat keeps the engine it started with: start a new chat after
running `headroom wrap vscode`. If you already set either harness setting
yourself, Headroom leaves your value alone and warns when it is `true`.
## Safe settings lifecycle
Headroom edits only a marked block in VS Code's `settings.json`. Existing JSONC
@@ -89,7 +99,7 @@ remote extension host, provide the exact user settings file:
headroom wrap vscode --settings-file /path/to/User/settings.json
```
Use `--no-configure` to print the two settings without editing a file.
Use `--no-configure` to print the settings without editing a file.
## Model coverage
@@ -183,6 +193,9 @@ or `GITHUB_COPILOT_ENTERPRISE_DOMAIN` before both `copilot-auth login` and
- If Headroom records no requests while Copilot keeps working, the window is
probably using a VS Code profile with its own settings. `wrap vscode` warns
about each such profile and prints the `--settings-file` path to configure it.
- If only some chats are missing, they are running on the Copilot harness: start
a new chat, and set `chat.defaultToCopilotHarness` and
`chat.editor.preferCopilotHarness` to `false` if you had set them to `true`.
- Use `--port 8788` when the default port is occupied; settings update safely.
- If Headroom refuses settings, repair the reported JSONC/marker conflict or use
`--no-configure` and apply the printed settings manually.
+71 -32
View File
@@ -40,6 +40,25 @@ def _is_tool_result_message(msg: dict) -> bool:
return False
def _tool_result_units(msg: dict) -> list[tuple[int | None, dict]]:
"""Expose each parallel result to the single-result shape/replay helpers.
The index identifies its block in the original Anthropic message; OpenAI
tool messages contain one result and use None. The wrappers borrow their
blocks for reading only: rewriting still goes through the copying helper.
"""
if msg.get("role") == "tool":
return [(None, msg)]
content = msg.get("content")
if not isinstance(content, list):
return []
return [
(i, {"role": msg.get("role"), "content": [block]})
for i, block in enumerate(content)
if isinstance(block, dict) and block.get("type") == "tool_result"
]
def _extract_text_from_blocks(blocks: list) -> str | None:
"""Extract joined text from a list-of-blocks content (e.g. Anthropic list-of-text-blocks).
@@ -281,8 +300,8 @@ class CompressionCache:
"""Mark all tool_result hashes in messages[:up_to] as stable."""
with self._lock:
for msg in messages[:up_to]:
if _is_tool_result_message(msg):
content = _extract_tool_result_content(msg)
for _, unit in _tool_result_units(msg):
content = _extract_tool_result_content(unit)
if content is not None:
self._mark_stable_locked(self.content_hash(content))
@@ -373,29 +392,29 @@ class CompressionCache:
with self._lock:
count = 0
for msg in messages:
if _is_tool_result_message(msg):
for _, unit in _tool_result_units(msg):
# A joined-text cache/stable hash cannot prove replay for
# shapes that apply_cached deliberately leaves untouched.
# Anthropic textless results retain their no-rewrite path.
if not _can_swap_tool_result_content(msg):
if not _can_swap_tool_result_content(unit):
break
content = _extract_tool_result_content(msg)
content = _extract_tool_result_content(unit)
if content is not None:
h = self.content_hash(content)
if h not in self._cache and h not in self._stable_hashes:
break
elif _carries_tool_result_text(msg):
# Text after a textless first tool_result: the cache
# keys a message by its first one, so this text was
# never stored and cannot be byte-replayed.
elif _carries_tool_result_text(unit):
break
# A tool_result with no text at all (a ToolSearch
# tool_reference list, an image) gives the cache nothing
# to replay, so it is stable. As a miss it stopped the
# count for the rest of the session.
# Regular user/assistant/system messages and assistant+tool_use
# are always stable — fall through.
count += 1
else:
# A message freezes only when every parallel result can
# be replayed. Textless results need no cached replacement.
count += 1
continue
break
# Reserve the trailing message as the live zone. `max(0, ...)`
# handles the empty-list edge case cleanly.
return min(count, max(0, len(messages) - 1))
@@ -412,25 +431,31 @@ class CompressionCache:
with self._lock:
result: list[dict] = []
for msg in messages:
if not _can_swap_tool_result_content(msg):
result.append(msg)
continue
if _is_tool_result_message(msg):
content = _extract_tool_result_content(msg)
replacement = msg
for index, unit in _tool_result_units(msg):
if not _can_swap_tool_result_content(unit):
continue
content = _extract_tool_result_content(unit)
if content is not None:
h = self.content_hash(content)
compressed = self.get_compressed(h)
if compressed is not None:
result.append(_swap_tool_result_content(msg, compressed))
continue
result.append(msg)
swapped = _swap_tool_result_content(unit, compressed)
if index is None:
replacement = swapped
else:
if replacement is msg:
replacement = copy.deepcopy(msg)
replacement["content"][index] = swapped["content"][0]
result.append(replacement)
return result
def update_from_result(self, originals: list[dict], compressed: list[dict]) -> None:
"""Cache new compressions by comparing original and compressed messages.
Index-aligned: for each position, if both are tool results and the
content differs, store the mapping original_hash -> compressed_content.
Compare messages by position and parallel results by tool-call ID.
Each result gets its own original_hash -> compressed_content mapping;
text in a later result must not disappear behind the first result's hit.
"""
if len(originals) != len(compressed):
logger.warning(
@@ -444,14 +469,28 @@ class CompressionCache:
# (RLock) safely.
with self._lock:
for orig, comp in zip(originals, compressed):
orig_content = _extract_tool_result_content(orig)
comp_content = _extract_tool_result_content(comp)
if orig_content is None or comp_content is None:
orig_units = _tool_result_units(orig)
comp_units = _tool_result_units(comp)
if len(orig_units) != len(comp_units):
continue
if orig_content == comp_content:
# Content unchanged — mark as stable for frozen count walk
self._mark_stable_locked(self.content_hash(orig_content))
continue
h = self.content_hash(orig_content)
tokens_saved = len(orig_content) // 4 - len(comp_content) // 4
self.store_compressed(h, comp_content, tokens_saved=max(tokens_saved, 0))
for (orig_index, orig_unit), (comp_index, comp_unit) in zip(orig_units, comp_units):
if orig_index is None or comp_index is None:
aligned = orig_index == comp_index and orig.get("tool_call_id") == comp.get(
"tool_call_id"
)
else:
aligned = orig_unit["content"][0].get("tool_use_id") == comp_unit[
"content"
][0].get("tool_use_id")
if not aligned:
continue
orig_content = _extract_tool_result_content(orig_unit)
comp_content = _extract_tool_result_content(comp_unit)
if orig_content is None or comp_content is None:
continue
if orig_content == comp_content:
self._mark_stable_locked(self.content_hash(orig_content))
continue
h = self.content_hash(orig_content)
tokens_saved = len(orig_content) // 4 - len(comp_content) // 4
self.store_compressed(h, comp_content, tokens_saved=max(tokens_saved, 0))
+9
View File
@@ -291,6 +291,13 @@ class CompressionStore:
# started: [original tokens stored, compressed tokens stored, retrievals].
self._own_totals = [0, 0, 0]
self._backend_revision = self._read_backend_revision()
self._write_seq: int = 0
@property
def write_seq(self) -> int:
"""Monotonic counter incremented on store/clear mutations."""
with self._lock:
return self._write_seq
@property
def default_ttl_seconds(self) -> int:
@@ -471,6 +478,7 @@ class CompressionStore:
raise StorageError(
f"CCR store did not keep hash={hash_key}; keep the original content"
)
self._write_seq += 1
if self._backend_expires_entries:
if existing is None:
self._own_totals[0] += entry.original_tokens
@@ -848,6 +856,7 @@ class CompressionStore:
self._expiration_heap.clear()
self._stale_heap_entries = 0 # CRITICAL FIX: Reset stale counter
self._stale_expiration_heap_entries = 0
self._write_seq += 1
def close(self) -> None:
"""Close the storage backend and release its resources.
+15 -1
View File
@@ -132,6 +132,7 @@ from headroom.providers.copilot import (
)
from headroom.providers.copilot import (
configure_vscode_proxy_settings,
copilot_harness_settings_enabled,
remove_vscode_proxy_settings,
unrouted_vscode_profiles,
vscode_proxy_url,
@@ -7390,14 +7391,27 @@ def vscode_copilot(
click.echo(
" Keep using Copilot's normal model picker; the selected model is preserved."
)
user_enabled = copilot_harness_settings_enabled(target_settings)
for key in user_enabled:
click.echo(
f' Warning: {target_settings} sets "{key}": true, so chats on the '
"Copilot harness bypass Headroom. Set it to false to route them."
)
if not user_enabled:
click.echo(
" New chats stay on VS Code's Local harness; a chat keeps the engine it "
"started with, so start a new chat."
)
return
click.echo(" Add these user settings to VS Code:")
click.echo(
f' "github.copilot.advanced.debug.overrideProxyUrl": "{vscode_proxy_url(actual_port, _project_name_from_cwd())}",'
)
click.echo(
f' "github.copilot.advanced.debug.overrideCapiUrl": "{vscode_proxy_url(actual_port, _project_name_from_cwd())}"'
f' "github.copilot.advanced.debug.overrideCapiUrl": "{vscode_proxy_url(actual_port, _project_name_from_cwd())}",'
)
click.echo(' "chat.defaultToCopilotHarness": false,')
click.echo(' "chat.editor.preferCopilotHarness": false')
_run_proxy_only_watcher(
agent_label="VS CODE COPILOT",
+4 -2
View File
@@ -624,7 +624,7 @@ def _verify_and_revert(
out: list[dict[str, Any]] = []
reverted = 0
for orig, comp in zip(original, compressed):
if orig == comp or _message_is_lossless(orig, comp):
if _message_is_lossless(orig, comp):
out.append(comp)
else:
out.append(orig)
@@ -654,6 +654,8 @@ def _collect_string_pairs(orig: Any, comp: Any, pairs: list[tuple[str, str]]) ->
Returns False if the structures diverge in shape (different types, lengths,
or dict keys) — a shape we cannot verify and must conservatively revert.
"""
if orig is comp:
return True
if isinstance(orig, str) and isinstance(comp, str):
if orig != comp:
pairs.append((orig, comp))
@@ -668,7 +670,7 @@ def _collect_string_pairs(orig: Any, comp: Any, pairs: list[tuple[str, str]]) ->
return all(_collect_string_pairs(o, c, pairs) for o, c in zip(orig, comp))
# Scalars (int/float/bool/None) must match exactly; transforms only touch
# strings, so a changed non-string is unexpected.
return bool(orig == comp)
return type(orig) is type(comp) and bool(orig == comp)
def _string_pair_is_lossless(original: str, compressed: str) -> bool:
+21 -2
View File
@@ -331,13 +331,28 @@
'text-amber-500': stats.tokens?.output_reduction?.method === 'modelled'
}"
x-text="stats.tokens?.output_reduction?.method || ''"></span>
<!-- A modelled band is the spread between the two benchmarked
models, not a sampling CI. Calling it one would be a lie. -->
<!-- A modelled band is a benchmark's range, not a CI over this
deployment's traffic. Calling it one would be a lie. -->
<span x-text="'· ' + (stats.tokens?.output_reduction?.band_is_ci === false ? 'range ' : '95% CI ') + (stats.tokens?.output_reduction?.ci_low_percent || 0).toFixed(1) + '–' + (stats.tokens?.output_reduction?.ci_high_percent || 0).toFixed(1) + '%'"></span>
</div>
<div class="mt-1 text-xs text-gray-600 leading-relaxed"
x-text="formatNumber(stats.tokens?.output_reduction?.requests || 0) + ' shaped responses · counterfactual'">
</div>
<!-- Lifetime dollars at each request's model output rate. The
high end exists only when savings were modelled from a
benchmark band; a point estimate shows one number. -->
<template x-if="(lifetimeOutputSavings.output_savings_usd || 0) > 0">
<div class="mt-1 text-xs text-gray-400 leading-relaxed"
x-text="'≈ $' + formatCurrency(lifetimeOutputSavings.output_savings_usd || 0)
+ ((lifetimeOutputSavings.output_savings_usd_high || 0) > (lifetimeOutputSavings.output_savings_usd || 0)
? '–$' + formatCurrency(lifetimeOutputSavings.output_savings_usd_high) : '')
+ ' saved on output · '
+ formatNumber(lifetimeOutputSavings.output_tokens_saved || 0)
+ ((lifetimeOutputSavings.output_tokens_saved_high || 0) > (lifetimeOutputSavings.output_tokens_saved || 0)
? '–' + formatNumber(lifetimeOutputSavings.output_tokens_saved_high) : '')
+ ' tokens, all time'">
</div>
</template>
<template x-if="stats.tokens?.output_reduction?.method === 'modelled'">
<div class="mt-1 text-xs text-amber-600/80 leading-relaxed">
Approximate: a benchmark factor, not your traffic. Set
@@ -2800,6 +2815,10 @@
return this.stats.persistent_savings?.lifetime?.cache_savings_usd || 0;
},
get lifetimeOutputSavings() {
return this.stats.persistent_savings?.lifetime || {};
},
get cacheCardAvailable() {
return this.cacheSessionActive || this.lifetimeCacheReadTokens > 0 || this.lifetimeCacheSavingsUsd > 0;
},
+17 -2
View File
@@ -765,13 +765,13 @@ class LocalBackend:
async def get_user_memories(
self,
user_id: str,
limit: int = 100,
limit: int | None = 100,
) -> list[Memory]:
"""Get all memories for a user.
Args:
user_id: User identifier.
limit: Maximum number of memories to return.
limit: Maximum number of memories to return, or None for all memories.
Returns:
List of memories for the user.
@@ -784,6 +784,21 @@ class LocalBackend:
limit=limit,
)
async def get_session_memories(
self,
user_id: str,
session_id: str,
limit: int = 100,
) -> list[Memory]:
"""List recent memories filtered by both user and session before limiting."""
await self._ensure_initialized()
assert self._hierarchical_memory is not None
return await self._hierarchical_memory.get_session_memories(
user_id=user_id,
session_id=session_id,
limit=limit,
)
async def clear_user(self, user_id: str) -> int:
"""Clear all memories and graph data for a user.
+27 -6
View File
@@ -9,6 +9,7 @@ embedding, indexing, caching, and memory bubbling.
from __future__ import annotations
import logging
from dataclasses import replace
from datetime import datetime
from typing import TYPE_CHECKING, Any
@@ -188,6 +189,8 @@ class HierarchicalMemory:
embedding = await self._embedder.embed(content)
memory.embedding = embedding
self._validate_embedding(memory)
# Save to store
await self._store.save(memory)
@@ -256,6 +259,10 @@ class HierarchicalMemory:
for memory, embedding in zip(memories, embeddings):
memory.embedding = embedding
# Validate the whole batch before persisting any of its rows.
for memory in memories:
self._validate_embedding(memory)
# Batch save
await self._store.save_batch(memories)
@@ -476,6 +483,11 @@ class HierarchicalMemory:
content_changed = False
if content is not None and content != memory.content:
# Validate before mutating a possibly shared store/cache object.
if re_embed:
embedding = await self._embedder.embed(content)
self._validate_embedding(replace(memory, embedding=embedding))
memory.embedding = embedding
memory.content = content
content_changed = True
@@ -488,10 +500,6 @@ class HierarchicalMemory:
if metadata is not None:
memory.metadata.update(metadata)
# Re-embed if content changed
if content_changed and re_embed:
memory.embedding = await self._embedder.embed(memory.content)
# Save updates
await self._store.save(memory)
@@ -579,6 +587,8 @@ class HierarchicalMemory:
if auto_embed:
new_memory.embedding = await self._embedder.embed(new_content)
self._validate_embedding(new_memory)
# Perform supersession in store
new_memory = await self._store.supersede(old_memory_id, new_memory, supersede_time)
@@ -791,14 +801,14 @@ class HierarchicalMemory:
async def get_user_memories(
self,
user_id: str,
limit: int = 100,
limit: int | None = 100,
include_sessions: bool = True,
) -> list[Memory]:
"""Get all memories for a user.
Args:
user_id: User identifier.
limit: Maximum memories to return.
limit: Maximum memories to return, or None for all matching memories.
include_sessions: If True, include session-level memories.
If False, only return user-level memories.
@@ -842,6 +852,17 @@ class HierarchicalMemory:
# Internal Methods
# =========================================================================
def _validate_embedding(self, memory: Memory) -> None:
"""Reject incompatible vectors before changing the primary store."""
if memory.embedding is not None and memory.embedding.shape != (
self._vector_index.dimension,
):
raise ValueError(
f"Embedding shape {memory.embedding.shape} does not match "
f"index dimension {self._vector_index.dimension}; configure vector_dimension "
"to match the embedder"
)
async def _index_for_text_search(self, memory: Memory) -> None:
"""Index a memory for full-text search.
+26 -11
View File
@@ -140,14 +140,29 @@ def _save_sync_state(state_path: Path, state: dict[str, Any]) -> None:
def _db_fingerprint(memories: list[Any]) -> str:
"""Compute a fast fingerprint of DB state."""
"""Fingerprint the fields that affect sync for every returned memory."""
if not memories:
return "empty"
# Hash: count + most recent created_at
parts = [str(len(memories))]
for m in memories[:5]: # Sample first 5 for speed
parts.append(getattr(m, "id", "")[:8])
return hashlib.sha256("|".join(parts).encode()).hexdigest()[:16]
# IDs and row count stay unchanged on in-place edits. Sampling also misses
# changes outside the newest rows. Hash the already-fetched snapshot using
# the content and export/lineage fields, without volatile access counters.
rows = []
for memory in memories:
meta = memory.metadata or {}
rows.append(
(
memory.id,
memory.content,
getattr(memory, "category", "") or "",
getattr(memory, "importance", 0.5),
str(memory.created_at),
meta.get("source_agent", "unknown"),
meta.get("sync_direction", ""),
meta.get("content_hash", ""),
)
)
payload = json.dumps(rows, ensure_ascii=False, separators=(",", ":"))
return hashlib.sha256(payload.encode()).hexdigest()
# ---------------------------------------------------------------------------
@@ -188,7 +203,7 @@ async def sync(
prev = state.get(adapter_key, {})
current_agent_fp = adapter.fingerprint()
all_memories = await backend.get_user_memories(user_id, limit=500)
all_memories = await backend.get_user_memories(user_id, limit=None)
current_db_fp = _db_fingerprint(all_memories)
if (
@@ -201,7 +216,7 @@ async def sync(
)
return result
else:
all_memories = await backend.get_user_memories(user_id, limit=500)
all_memories = await backend.get_user_memories(user_id, limit=None)
# --- Phase 1: Import (agent files → DB) ---
result.imported = await sync_import(backend, adapter, user_id, all_memories)
@@ -209,7 +224,7 @@ async def sync(
# --- Phase 2: Export (DB → agent files) ---
# Re-fetch if imports happened (new entries)
if result.imported > 0:
all_memories = await backend.get_user_memories(user_id, limit=500)
all_memories = await backend.get_user_memories(user_id, limit=None)
result.exported = await sync_export(backend, adapter, user_id, all_memories)
# --- Update sync state ---
@@ -245,7 +260,7 @@ async def sync_import(
# Build set of existing content hashes for dedup
if existing_memories is None:
existing_memories = await backend.get_user_memories(user_id, limit=500)
existing_memories = await backend.get_user_memories(user_id, limit=None)
existing_hashes: set[str] = set()
for mem in existing_memories:
@@ -290,7 +305,7 @@ async def sync_export(
) -> int:
"""Export: DB → agent files. Returns count exported."""
if existing_memories is None:
existing_memories = await backend.get_user_memories(user_id, limit=500)
existing_memories = await backend.get_user_memories(user_id, limit=None)
if not existing_memories:
return 0
+9 -7
View File
@@ -55,15 +55,17 @@ def _parse_frontmatter(content: str) -> tuple[dict[str, str], str]:
Returns (frontmatter_dict, body).
"""
if not content.startswith("---"):
# Delimiters occupy their own lines. A name/description can legitimately
# contain "---"; treating that substring as the end corrupts the body and
# its content hash on the next import.
match = re.match(
r"\A---[ \t]*\r?\n(.*?)^---[ \t]*(?:\r?\n|\Z)", content, re.DOTALL | re.MULTILINE
)
if match is None:
return {}, content
end = content.find("---", 3)
if end == -1:
return {}, content
fm_text = content[3:end].strip()
body = content[end + 3 :].strip()
fm_text = match.group(1).strip()
body = content[match.end() :].strip()
fm: dict[str, str] = {}
for line in fm_text.split("\n"):
+35
View File
@@ -296,6 +296,7 @@ class MemorySystem:
handlers = {
"memory_save": self._handle_save,
"memory_search": self._handle_search,
"memory_list": self._handle_list,
"memory_update": self._handle_update,
"memory_delete": self._handle_delete,
}
@@ -494,6 +495,36 @@ class MemorySystem:
"count": len(results),
}
async def handle_memory_list(self, limit: int = 10) -> dict[str, Any]:
"""List recent memories within this user's current scope."""
method = "get_user_memories" if self._session_id is None else "get_session_memories"
list_memories = getattr(self._backend, method, None)
if not callable(list_memories):
return {
"success": False,
"error": "This memory backend does not support listing memories for this scope",
}
limit = max(1, min(limit, 100))
kwargs: dict[str, Any] = {"user_id": self._user_id, "limit": limit}
if self._session_id is not None:
kwargs["session_id"] = self._session_id
memories = await list_memories(**kwargs)
return {
"success": True,
"message": f"Found {len(memories)} memories",
"count": len(memories),
"memories": [
{
"memory_id": memory.id,
"content": memory.content,
"importance": memory.importance,
"entities": memory.entity_refs,
"created_at": memory.created_at.isoformat(),
}
for memory in memories
],
}
async def handle_memory_update(
self,
memory_id: str,
@@ -647,6 +678,10 @@ class MemorySystem:
reason=arguments.get("reason", "Updated by user"),
)
async def _handle_list(self, arguments: dict[str, Any]) -> dict[str, Any]:
"""Internal dispatcher for memory_list."""
return await self.handle_memory_list(limit=arguments.get("limit", 10))
async def _handle_delete(self, arguments: dict[str, Any]) -> dict[str, Any]:
"""Internal dispatcher for memory_delete."""
return await self.handle_memory_delete(
+2
View File
@@ -2,6 +2,7 @@
from .vscode import (
configure_vscode_proxy_settings,
copilot_harness_settings_enabled,
remove_vscode_proxy_settings,
unrouted_vscode_profiles,
vscode_proxy_url,
@@ -37,6 +38,7 @@ __all__ = [
"strip_auto_model_args",
"validate_configuration",
"configure_vscode_proxy_settings",
"copilot_harness_settings_enabled",
"remove_vscode_proxy_settings",
"unrouted_vscode_profiles",
"vscode_proxy_url",
+29 -9
View File
@@ -28,6 +28,11 @@ _CAPI_KEY = "github.copilot.advanced.debug.overrideCapiUrl"
# VS Code flags unknown keys, and shipping one that does nothing invited the
# conclusion that the override mechanism had stopped working.
_AUTH_KEY = "github.copilot.advanced.debug.overrideAuthType"
# A chat on VS Code's "Copilot harness" (Agent Host, the bundled Copilot SDK
# runtime) ignores both endpoint overrides and never reaches the proxy. Both
# settings default to false but are tagged `experiment: startup`, so a rollout
# can flip them per user; only an explicit user value pins the Local harness.
_COPILOT_HARNESS_KEYS = ("chat.defaultToCopilotHarness", "chat.editor.preferCopilotHarness")
def _read_settings(path: Path) -> str:
@@ -115,7 +120,7 @@ def _parse_settings(raw: str) -> object:
return json.loads(re.sub(r",\s*([}\]])", r"\1", candidate))
def _validate_settings(raw: str, path: Path) -> None:
def _validate_settings(raw: str, path: Path) -> dict[str, object]:
try:
parsed = _parse_settings(raw)
except json.JSONDecodeError as exc:
@@ -124,16 +129,17 @@ def _validate_settings(raw: str, path: Path) -> None:
) from exc
if not isinstance(parsed, dict):
raise click.ClickException(f"{path} must contain a JSON object; refusing to overwrite it.")
return parsed
def _managed_block(proxy_url: str, *, owns_preceding_comma: bool, line_sep: str) -> str:
def _managed_block(
settings: Mapping[str, object], *, owns_preceding_comma: bool, line_sep: str
) -> str:
marker = _MARKER_START + (" (comma-added)" if owns_preceding_comma else "")
return (
f"\t{marker}{line_sep}"
f"\t{json.dumps(_PROXY_KEY)}: {json.dumps(proxy_url)},{line_sep}"
f"\t{json.dumps(_CAPI_KEY)}: {json.dumps(proxy_url)}{line_sep}"
f"\t{_MARKER_END}"
entries = f",{line_sep}".join(
f"\t{json.dumps(key)}: {json.dumps(value)}" for key, value in settings.items()
)
return f"\t{marker}{line_sep}{entries}{line_sep}\t{_MARKER_END}"
def remove_vscode_proxy_settings(path: Path) -> bool:
@@ -166,7 +172,12 @@ def remove_vscode_proxy_settings(path: Path) -> bool:
def configure_vscode_proxy_settings(path: Path, proxy_url: str) -> str:
"""Add/update transparent routing while preserving all non-Headroom text."""
"""Add/update transparent routing while preserving all non-Headroom text.
The block also pins new chats to the Local harness, except for a harness
setting the user already set themselves: theirs is left alone, and
``copilot_harness_settings_enabled`` reports it when it bypasses Headroom.
"""
path.parent.mkdir(parents=True, exist_ok=True)
raw = _read_settings(path) if path.exists() else "{}\n"
_validate_settings(raw, path)
@@ -179,6 +190,9 @@ def configure_vscode_proxy_settings(path: Path, proxy_url: str) -> str:
f"{path} already configures a Copilot endpoint override outside Headroom's "
"managed block; refusing to replace it. Remove it or use --no-configure."
)
user_settings = _validate_settings(raw, path)
managed: dict[str, object] = {_PROXY_KEY: proxy_url, _CAPI_KEY: proxy_url}
managed.update({key: False for key in _COPILOT_HARNESS_KEYS if key not in user_settings})
close = raw.rfind("}")
if close < 0:
@@ -194,7 +208,7 @@ def configure_vscode_proxy_settings(path: Path, proxy_url: str) -> str:
before
+ separator
+ newline
+ _managed_block(proxy_url, owns_preceding_comma=needs_comma, line_sep=line_sep)
+ _managed_block(managed, owns_preceding_comma=needs_comma, line_sep=line_sep)
+ line_sep
+ after
)
@@ -203,6 +217,12 @@ def configure_vscode_proxy_settings(path: Path, proxy_url: str) -> str:
return "updated" if had_managed_block else "added"
def copilot_harness_settings_enabled(path: Path) -> list[str]:
"""Return the harness settings in ``path`` that send new chats around Headroom."""
settings = _validate_settings(_read_settings(path), path)
return [key for key in _COPILOT_HARNESS_KEYS if settings.get(key) is True]
def unrouted_vscode_profiles(user_dir: Path) -> list[tuple[str, Path]]:
"""Return ``(name, settings.json)`` for profiles that ignore ``user_dir/settings.json``.
+22
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import enum
import re
from dataclasses import dataclass
@@ -120,6 +121,27 @@ def classify_client_signals(signals: AuthSignals, *, default: str | None = None)
return default
# Up to three numeric parts, and nothing numeric after them: a date stamp or a
# four-part number is not cut down into a release that never existed.
_UA_VERSION_RE = re.compile(r"\d{1,4}(?:\.\d{1,4}){0,2}(?![.\d])")
def client_version_from_user_agent(user_agent: str) -> tuple[str, str] | None:
"""``(harness, version)`` from a User-Agent such as ``claude-cli/2.1.311``.
Only the numeric release that directly follows a known harness prefix in
:data:`CLIENT_UA_MAP` is returned, so nothing else in the header can ride
along. ``None`` when the harness is unknown or carries no numeric version.
"""
ua_lower = user_agent.lower()
for needle, name in CLIENT_UA_MAP:
at = ua_lower.find(needle)
if at >= 0:
match = _UA_VERSION_RE.match(ua_lower, at + len(needle))
return (name, match.group(0)) if match else None
return None
def is_codex_responses_path(path: str) -> bool:
"""Return True for OpenAI Responses endpoints and their subpaths."""
return any(root == path or path.startswith(root + "/") for root in CODEX_RESPONSES_PATHS)
+14 -2
View File
@@ -1646,7 +1646,13 @@ class AnthropicHandlerMixin:
request, headers, routed_to_omlx=routed_to_omlx
)
backend = (
None if routed_to_omlx else resolver_for(self).for_request(request, body=body)
None
if routed_to_omlx
else resolver_for(self).for_request(
request,
body=body,
upstream_url=upstream_base_url or self.ANTHROPIC_API_URL,
)
)
if backend is not None:
if model_override and not body.get("model"):
@@ -4255,7 +4261,13 @@ class AnthropicHandlerMixin:
from headroom.proxy.route_advice import resolver_for
request_backend = (
None if force_direct else resolver_for(self).for_request(request, body=body)
None
if force_direct
else resolver_for(self).for_request(
request,
body=body,
upstream_url=upstream_base_url or self.ANTHROPIC_API_URL,
)
)
if request_backend is not None:
# Route through Bedrock backend
+19 -12
View File
@@ -640,7 +640,11 @@ def _allowed_ws_origins_from_env() -> list[str] | None:
raw = os.environ.get(_CORS_ALLOWED_ORIGINS_ENV)
if raw is None or not raw.strip():
return None
return [origin.strip() for origin in raw.split(",") if origin.strip()]
# "*" is a CORS answer (which pages may read a response). It never waives
# the Origin check, which decides whether the proxy acts on the request at
# all, so it is dropped here; a list left empty means the loopback default.
origins = [origin.strip() for origin in raw.split(",") if origin.strip()]
return [origin for origin in origins if origin != "*"] or None
def _is_loopback_ws_origin(origin: str) -> bool:
@@ -657,7 +661,7 @@ def _is_allowed_websocket_origin(headers: dict[str, str]) -> bool:
Native clients commonly omit Origin, so absence is allowed. When Origin is
present, default to loopback-only and allow explicit configured origins via
HEADROOM_WS_ORIGINS or HEADROOM_CORS_ORIGINS.
HEADROOM_WS_ORIGINS or HEADROOM_CORS_ORIGINS. A ``*`` entry matches nothing.
"""
origin = _header_get(headers, "origin")
if not origin:
@@ -666,8 +670,6 @@ def _is_allowed_websocket_origin(headers: dict[str, str]) -> bool:
allowed_origins = _allowed_ws_origins_from_env()
if allowed_origins is None:
return _is_loopback_ws_origin(origin)
if "*" in allowed_origins:
return True
normalized_origin = _normalize_origin(origin)
if normalized_origin is None:
@@ -3784,7 +3786,10 @@ class OpenAIHandlerMixin:
COMPRESSION_BODY_MAX_BYTES,
)
backend = resolver_for(self).for_request(
request, body=body, native_providers=("openai",)
request,
body=body,
native_providers=("openai",),
upstream_url=upstream_base_url,
)
passthrough_model = body.get("model", "unknown")
if not isinstance(passthrough_model, str):
@@ -4572,7 +4577,7 @@ class OpenAIHandlerMixin:
# Decided before injection: a turn that can buffer can answer the tool,
# so it may carry it even though the client asked for a stream. Whether
# it actually buffers is settled at dispatch, from the final body.
from headroom.proxy.route_advice import advice_from
from headroom.proxy.route_advice import resolver_for
_ccr_handler = getattr(self, "ccr_response_handler", None)
chat_stream_ccr_eligible = _is_openai_chat_stream_ccr_eligible(
@@ -4582,10 +4587,12 @@ class OpenAIHandlerMixin:
_ccr_handler and getattr(_ccr_handler.config, "enabled", True)
),
ccr_inject_tool=self.config.ccr_inject_tool,
routed_to_backend=(
getattr(self, "anthropic_backend", None) is not None
or advice_from(request) is not None
),
# Ask the resolver, not the advice: advice it ignores (a Copilot
# upstream) leaves this request on the direct path.
routed_to_backend=resolver_for(self).for_request(
request, native_providers=("openai",), upstream_url=upstream_base_url
)
is not None,
upstream_base_url=upstream_base_url,
)
can_inject_ccr_tool = _should_inject_openai_chat_ccr_tool(
@@ -5162,7 +5169,7 @@ class OpenAIHandlerMixin:
_normalize_openai_max_tokens(
body,
backend_owns_translation=resolver_for(self).for_request(
request, native_providers=("openai",)
request, native_providers=("openai",), upstream_url=upstream_base_url
)
is not None,
)
@@ -5233,7 +5240,7 @@ class OpenAIHandlerMixin:
# litellm backend; same-family (openai) advice still resolves to
# `self.anthropic_backend`, unchanged.
request_backend = resolver_for(self).for_request(
request, body=body, native_providers=("openai",)
request, body=body, native_providers=("openai",), upstream_url=upstream_base_url
)
if request_backend is not None:
try:
+9 -3
View File
@@ -9,6 +9,7 @@ import asyncio
import contextlib
import json
import logging
import ssl
import time
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING, Any
@@ -18,6 +19,7 @@ from headroom.proxy.auth_mode import classify_client, supports_mid_turn_coalesci
from headroom.proxy.handlers._debug_dump import write_upstream_error_dump
from headroom.proxy.helpers import (
RETRYABLE_OVERLOAD_STATUSES,
RequestWriteTrace,
_path_for_log,
jitter_delay_ms,
overload_retry_is_futile,
@@ -1430,10 +1432,12 @@ class StreamingMixin:
last_connect_error = None
for attempt in range(retry_attempts):
request_trace = RequestWriteTrace()
try:
_upstream_req = streaming_client.build_request(
"POST", url, content=outbound_bytes, headers=outbound_headers
)
_upstream_req.extensions["trace"] = request_trace
upstream_response = await streaming_client.send(_upstream_req, stream=True)
if _codex_wire_debug:
capture_codex_wire_debug(
@@ -1481,9 +1485,11 @@ class StreamingMixin:
# `StreamReset`) from a poisoned shared h2 connection. This runs
# before any body byte is forwarded to the client, so re-sending
# on a fresh connection is safe and avoids a 502. (#1639)
except httpx.TransportError as e:
# A raw ssl.SSLError escapes httpx's TransportError mapping; it is
# retried only if the request write failed (RequestWriteTrace).
except (httpx.TransportError, ssl.SSLError) as e:
last_connect_error = e
if attempt >= retry_attempts - 1:
if attempt >= retry_attempts - 1 or request_trace.forbids_retry(e):
raise
delay_with_jitter = jitter_delay_ms(
@@ -1513,7 +1519,7 @@ class StreamingMixin:
# 502 keeps the structured SSE body for clients that read it while
# letting SDK retry logic treat a transient upstream transport failure
# as what it is.
except httpx.TransportError as e:
except (httpx.TransportError, ssl.SSLError) as e:
error_msg = str(e) or repr(e)
logger.error(f"[{request_id}] Connection error to upstream API: {error_msg}")
self.metrics.record_upstream_connection_error(provider)
+25
View File
@@ -16,6 +16,7 @@ import logging
import os
import random
import re
import ssl
import threading
import time
import warnings
@@ -1767,6 +1768,30 @@ def overload_retry_is_futile(response: httpx.Response, max_ms: int, retries_left
RETRYABLE_OVERLOAD_STATUSES: frozenset[int] = frozenset({429, 529})
class RequestWriteTrace:
"""httpcore ``trace`` extension that records a failed request write.
httpcore maps an ``ssl.SSLError`` to ``ConnectError`` only during the
handshake. Later, a corrupt TLS record surfaces as a raw ``ssl.SSLError``
that says nothing about whether upstream received the request. It is safe
to retry only when it was raised while the request was still being written
(``send_request_headers`` / ``send_request_body`` failed): upstream then
never had a complete request to run. Raised after the write, upstream may
already have accepted, and billed, the POST, so it is not replayed.
"""
def __init__(self) -> None:
self.write_failed = False
async def __call__(self, event: str, info: dict[str, Any]) -> None:
if event.endswith((".send_request_headers.failed", ".send_request_body.failed")):
self.write_failed = True
def forbids_retry(self, exc: BaseException) -> bool:
"""True for a raw TLS error raised after the request was fully written."""
return isinstance(exc, ssl.SSLError) and not self.write_failed
async def request_with_transient_retry(
client: httpx.AsyncClient,
*,
+24 -5
View File
@@ -19,6 +19,7 @@ import shutil
import stat
import subprocess
import tempfile
from collections.abc import Iterator
from enum import Enum
from pathlib import Path
from typing import Any
@@ -98,15 +99,33 @@ OUTLINE_MARKER = " # ... (body elided by Headroom; Read a specific line range
_TRUNCATION_SIGNATURES: tuple[re.Pattern[str], ...] = (
# Claude Code: "[Truncated: PARTIAL view -- <path>: showing lines A-B of
# T total (...). Call Read with offset=N to see more.]"
# Matched in two linear steps (see _iter_banners): this pattern is only the
# body of one bracket-free span, never run against the rest of the output.
re.compile(
r"\[\s*truncated\s*:\s*partial\s+view\b"
r"[^\[\]]*?"
r"showing\s+lines?\s+(?P<start_line>\d+)\s*[-–]\s*(?P<end_line>\d+)"
r"\s+of\s+(?P<total_lines>\d+)\s+total"
r"[^\[\]]*\]",
r"\s+of\s+(?P<total_lines>\d+)\s+total",
re.IGNORECASE,
),
)
_BANNER_OPENER = re.compile(r"\[\s*truncated\s*:\s*partial\s+view\b", re.IGNORECASE)
_BRACKET = re.compile(r"[\[\]]")
def _iter_banners(source: str, body: re.Pattern[str]) -> Iterator[re.Match[str]]:
"""Yield body matches inside each ``[truncated: partial view ... ]`` span.
A span runs from the opener to the next bracket and counts only when that
bracket is ``]``. Spans cannot overlap (the next opener starts with ``[``),
so total work is linear. A single regex with unbounded runs on both sides of
the phrase rescanned the unclosed tail once per phrase: quadratic.
"""
for opener in _BANNER_OPENER.finditer(source):
close = _BRACKET.search(source, opener.end())
if close is None or close.group() != "]":
continue
m = body.search(source, opener.end(), close.start())
if m:
yield m
def _is_plausible_truncation_range(
@@ -123,7 +142,7 @@ def _detect_truncation(source: str) -> tuple[int, int] | None:
internally-consistent upstream truncation banner, else None."""
source_line_count = len(source.splitlines())
for pattern in _TRUNCATION_SIGNATURES:
for m in pattern.finditer(source):
for m in _iter_banners(source, pattern):
start_line = int(m.group("start_line"))
end_line = int(m.group("end_line"))
total_lines = int(m.group("total_lines"))
+9 -5
View File
@@ -588,22 +588,25 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:
# observed output tokens to the recorder so it can produce an honest
# reduction estimate. Best-effort: never let bookkeeping break a response.
output_tokens_saved_est = 0
# High end of the range when the saving is modelled from benchmark factors;
# equal to the point estimate otherwise. Only the lifetime totals carry it.
output_tokens_saved_high_est = 0
if any(str(t).startswith("output_shaper:") for t in outcome.transforms_applied):
try:
from headroom.proxy.output_savings import get_recorder
_rec = get_recorder()
def _record_and_estimate() -> int:
def _record_and_estimate() -> tuple[int, int]:
_rec.record_from_labels(outcome.transforms_applied, outcome.output_tokens)
return _rec.estimate_request_savings(
outcome.transforms_applied, outcome.output_tokens
)
return _rec.request_savings_range(outcome.transforms_applied, outcome.output_tokens)
# Both calls take the recorder lock, and the every-Nth record also
# does a full read-modify-write of the ledger file — run them
# together off the event loop (#18) so a slow flush can't stall it.
output_tokens_saved_est = await asyncio.to_thread(_record_and_estimate)
output_tokens_saved_est, output_tokens_saved_high_est = await asyncio.to_thread(
_record_and_estimate
)
except Exception as exc: # pragma: no cover - defensive
logger.debug(
"Output savings record/estimate failed for request %s; booking 0: %s",
@@ -731,6 +734,7 @@ async def emit_request_outcome(handler: Any, outcome: RequestOutcome) -> None:
uncached_input_tokens=outcome.uncached_input_tokens,
attempted_input_tokens=outcome.attempted_input_tokens,
output_tokens_saved=output_tokens_saved_est,
output_tokens_saved_high=output_tokens_saved_high_est,
project=project,
client=outcome.client,
tool_search_saved=tool_search_saved,
+121 -5
View File
@@ -333,6 +333,37 @@ def register_modelled_factors(level: int, conservative: float, optimistic: float
MODELLED_REDUCTION[level] = (conservative, optimistic)
def _shaped_level(labels: Any) -> int | None:
"""The verbosity level a request was shaped at, or ``None`` if it was not."""
for label in labels or ():
text = str(label)
if not text.startswith(_SHAPED_LABEL_PREFIX + "L"):
continue
try:
return int(text[len(_SHAPED_LABEL_PREFIX) + 1 :])
except ValueError:
continue
return None
def modelled_request_savings(labels: Any, output_tokens: int) -> tuple[int, int]:
"""Output tokens one shaped request saved, from its level's benchmark factors.
``(low, high)`` at the conservative and optimistic factor, using the same
inversion as :meth:`SavingsLedger.estimate_from_model`: observed output is
already shaped, so ``saved = observed * r / (1 - r)``. ``(0, 0)`` when the
request was not shaped or its level has no registered factors.
"""
level = _shaped_level(labels)
if output_tokens <= 0 or level is None:
return 0, 0
factors = MODELLED_REDUCTION.get(level)
if factors is None:
return 0, 0
low, high = (int(round(output_tokens * r / (1.0 - r))) for r in factors)
return low, high
@dataclass
class SavingsEstimate:
"""Result of an estimation pass."""
@@ -637,21 +668,48 @@ class SavingsLedger:
reported, since it displaces nothing, but only while it covers the
traffic: a corner of it is not a headline either way.
"""
return self.select_tier(level)[0]
def select_tier(self, level: int | None = None) -> tuple[SavingsEstimate, int | None]:
""":meth:`best_estimate`, plus the cluster gate the measured tier used.
The second element is the ``min_clusters`` that qualified the measured
estimate, or ``None`` for any other tier. A per-request booking needs
it to tell whether the request's own stratum is part of the
measurement; the headline excludes strata that are not.
"""
measured = self.estimate_from_holdout(min_clusters=MEASURED_SUPERSEDE_MIN_CLUSTERS)
labelled = sum(t.qn for t in self.treatment.values())
if measured is not None and _measured_supersedes(measured, labelled):
return measured
return measured, MEASURED_SUPERSEDE_MIN_CLUSTERS
estimated = self.estimate_from_baseline()
if estimated.n_requests > 0:
return estimated
return estimated, None
measured = self.estimate_from_holdout()
if measured is not None and _measured_covers(measured, labelled):
return measured
return measured, MEASURED_MIN_CLUSTERS
if level is not None:
modelled = self.estimate_from_model(level)
if modelled is not None:
return modelled
return estimated
return modelled, None
return estimated, None
def measured_stratum_saving(
self, key: str, output_tokens: int, min_clusters: int
) -> int | None:
"""Tokens one request in ``key`` saved, from that stratum's own A/B.
``None`` when the stratum is not part of the measurement at
``min_clusters`` -- the same qualification :meth:`estimate_from_holdout`
applies, so a stratum the headline excludes is never credited.
"""
t = self.treatment.get(key)
c = self.control.get(key)
if t is None or c is None or c.qn == 0 or t.qn == 0:
return None
if c.n_clusters < min_clusters or t.n_clusters < min_clusters:
return None
return max(0, int(round(c.qmean - output_tokens)))
# ---- persistence -----------------------------------------------------
@@ -828,6 +886,64 @@ class SavingsRecorder:
return max(0, int(round(mean - output_tokens))) if n > 0 else 0
return 0
def request_savings_range(self, labels: Any, output_tokens: int) -> tuple[int, int]:
"""Per-request output tokens saved as ``(low, high)``, for the rollup.
Only a request that was actually shaped saves anything: the treatment
stratum label is attached before shaping is attempted, so the
``output_shaper:verbosity:L<n>`` label is the proof, as in
:meth:`record_from_labels`. A holdout (control) request saved nothing.
The tier is whatever :meth:`SavingsLedger.best_estimate` picks for the
request's level, so the lifetime dollars always come from the same
tier the dashboard's percentage does:
* measured -> this stratum's own control mean minus the observed
output, low = high, and only if the stratum is part of the
measurement (0 otherwise: the headline excludes it too);
* estimated -> the learned baseline for this request's stratum,
low = high (0 where the stratum has no baseline);
* modelled -> the level's benchmark factors, a low-high band.
With no factors registered (plain OSS) the modelled tier never
appears, so nothing changes there.
"""
# Zero output means the provider reported no usage, not a silent
# reply: every tier would otherwise book the whole baseline as saved.
if output_tokens <= 0:
return 0, 0
label_strings = [str(label) for label in labels or ()]
level = _shaped_level(label_strings)
if level is None:
return 0, 0
key = None
for text in label_strings:
parsed = parse_stratum_label(text)
if parsed is None:
continue
arm, key = parsed
if arm != "treatment":
return 0, 0
break
n = 0
mean = 0.0
measured_point: int | None = None
with self._lock:
tier, min_clusters = self._ledger.select_tier(level)
if tier.kind == "estimated" and key is not None:
mean, _var, n = self._ledger.baseline.lookup(key)
if min_clusters is not None and key is not None:
measured_point = self._ledger.measured_stratum_saving(
key, output_tokens, min_clusters
)
if tier.kind == "modelled":
return modelled_request_savings(label_strings, output_tokens)
if tier.kind == "measured":
point = measured_point or 0
return point, point
point = max(0, int(round(mean - output_tokens))) if n > 0 else 0
return point, point
def _reload_baseline_locked(self) -> None:
"""Adopt the on-disk baseline written by ``learn --verbosity --apply``.
+3
View File
@@ -884,6 +884,8 @@ class PrometheusMetrics:
uncached_input_tokens: int = 0,
attempted_input_tokens: int = 0,
output_tokens_saved: int = 0,
# High end of a modelled output-savings range; None means "same as low".
output_tokens_saved_high: int | None = None,
project: str | None = None,
client: str | None = None,
tool_search_saved: int = 0,
@@ -1143,6 +1145,7 @@ class PrometheusMetrics:
total_input_tokens=total_input_tokens,
total_input_cost_usd=total_input_cost_usd,
output_tokens_saved=output_tokens_saved,
output_tokens_saved_high=output_tokens_saved_high,
output_tokens=output_tokens,
estimated_savings_usd=savings_usd,
)
+16
View File
@@ -34,6 +34,7 @@ import logging
from dataclasses import dataclass
from typing import Any
from headroom.copilot_auth import is_copilot_upstream_url
from headroom.offline import pin_litellm_cost_map_local
log = logging.getLogger(__name__)
@@ -110,6 +111,7 @@ class BackendResolver:
*,
body: dict | None = None,
native_providers: tuple[str, ...] = _NATIVE,
upstream_url: str | None = None,
) -> Any:
"""The backend to serve this request. Falls back to the default.
@@ -122,6 +124,12 @@ class BackendResolver:
short-circuited to the default backend. One proxy instance serves both
wires from a single shared resolver, so native-ness cannot live on the
resolver; it must be supplied per dispatch site.
``upstream_url`` is where the caller sends this request when no backend
is used. When it is GitHub Copilot, cross-provider advice is ignored and
the body is left alone: Copilot serves every model family on the one
upstream, and the proxy holds a Copilot token, not a key for the
provider a translating backend would call.
"""
advice = advice_from(request)
if advice is None:
@@ -133,6 +141,14 @@ class BackendResolver:
# rewrite is enough and the extension has already done it. Nothing
# to switch.
return self._default
if is_copilot_upstream_url(upstream_url):
if body is not None:
log.info(
"route advice ignored: %s via %s; the upstream is GitHub Copilot",
advice.model,
provider,
)
return self._default
if provider in self._failed:
return self._default
+40
View File
@@ -1155,6 +1155,10 @@ class SavingsTracker:
# message-only while per-model dollars did not.
tool_search_saved: int = 0,
output_tokens_saved: int = 0,
# High end of a modelled output-savings range (benchmark factors give a
# band, not a point); ``None`` means the saving is a point estimate and
# the high end equals ``output_tokens_saved``. Lifetime-only.
output_tokens_saved_high: int | None = None,
# Tokens the model actually emitted, DISJOINT from
# ``output_tokens_saved`` (which counts the ones it did not). Priced
# into ``lifetime["total_output_cost_usd"]``; see the delta below.
@@ -1188,6 +1192,11 @@ class SavingsTracker:
delta_tool_tokens_saved = max(_coerce_int(tool_search_saved), 0)
delta_input_tokens = _coerce_int(input_tokens)
delta_output_tokens_saved = max(_coerce_int(output_tokens_saved), 0)
delta_output_tokens_saved_high = (
delta_output_tokens_saved
if output_tokens_saved_high is None
else max(_coerce_int(output_tokens_saved_high), delta_output_tokens_saved)
)
delta_output_tokens = max(_coerce_int(output_tokens), 0)
delta_cache_read_tokens = _coerce_int(cache_read_tokens)
priced = estimated_savings_usd
@@ -1252,6 +1261,10 @@ class SavingsTracker:
if priced is not None
else _estimate_output_savings_usd(model, delta_output_tokens_saved)
)
# Same per-token rate table that priced the low end.
delta_output_savings_usd_high = _estimate_output_savings_usd(
model, delta_output_tokens_saved_high
)
# Completion spend. ``total_input_cost_usd`` has never had an output
# counterpart, so anything answering "what share of my bill did
# Headroom remove" had to divide savings that include output shaping by
@@ -1343,6 +1356,13 @@ class SavingsTracker:
lifetime.get("output_savings_usd", 0.0) + delta_output_savings_usd,
6,
)
# High end of the output-savings range; equals the low end for
# point estimates. Both state builders always write these keys.
lifetime["output_tokens_saved_high"] += delta_output_tokens_saved_high
lifetime["output_savings_usd_high"] = round(
lifetime["output_savings_usd_high"] + delta_output_savings_usd_high,
6,
)
lifetime["tool_tokens_saved"] += delta_tool_tokens_saved
lifetime["tool_schema_savings_usd"] = round(
lifetime["tool_schema_savings_usd"] + delta_tool_savings_usd,
@@ -1851,6 +1871,8 @@ class SavingsTracker:
"total_input_cost_usd": 0.0,
"output_tokens_saved": 0,
"output_savings_usd": 0.0,
"output_tokens_saved_high": 0,
"output_savings_usd_high": 0.0,
"output_tokens": 0,
"total_output_cost_usd": 0.0,
},
@@ -1923,6 +1945,8 @@ class SavingsTracker:
is_v6_lifetime = False
lifetime_output_tokens_saved = 0
lifetime_output_savings_usd = 0.0
lifetime_output_tokens_saved_high: int | None = None
lifetime_output_savings_usd_high: float | None = None
lifetime_output_tokens = 0
lifetime_output_cost_usd = 0.0
if isinstance(lifetime_raw, dict):
@@ -1944,6 +1968,14 @@ class SavingsTracker:
lifetime_basis = str(lifetime_raw.get("savings_basis") or BASIS_UNKNOWN)
lifetime_output_tokens_saved = _coerce_int(lifetime_raw.get("output_tokens_saved"))
lifetime_output_savings_usd = _coerce_float(lifetime_raw.get("output_savings_usd"))
if "output_tokens_saved_high" in lifetime_raw:
lifetime_output_tokens_saved_high = _coerce_int(
lifetime_raw.get("output_tokens_saved_high")
)
if "output_savings_usd_high" in lifetime_raw:
lifetime_output_savings_usd_high = _coerce_float(
lifetime_raw.get("output_savings_usd_high")
)
lifetime_output_tokens = _coerce_int(lifetime_raw.get("output_tokens"))
lifetime_output_cost_usd = _coerce_float(lifetime_raw.get("total_output_cost_usd"))
@@ -2044,6 +2076,14 @@ class SavingsTracker:
"total_input_cost_usd": round(lifetime_input_cost_usd, 6),
"output_tokens_saved": lifetime_output_tokens_saved,
"output_savings_usd": round(lifetime_output_savings_usd, 6),
# A high end below the low end can only come from the history
# repair above raising the low end; never let the band invert.
"output_tokens_saved_high": max(
lifetime_output_tokens_saved_high or 0, lifetime_output_tokens_saved
),
"output_savings_usd_high": round(
max(lifetime_output_savings_usd_high or 0.0, lifetime_output_savings_usd), 6
),
"output_tokens": lifetime_output_tokens,
"total_output_cost_usd": round(lifetime_output_cost_usd, 6),
},
+45 -18
View File
@@ -102,26 +102,48 @@ def compute_request_cache_partition(request: Any) -> str | None:
return compute_cache_partition(headers, principal=principal)
# Fields whose value is opaque, model-visible payload rather than request
# structure: tool call arguments, JSON Schema bodies, and their literal values.
# ``cache_control`` inside them is application data, not a transport directive,
# so it must stay in the key — two requests that differ there can generate
# different completions (see #4272).
_LITERAL_PAYLOAD_FIELDS = frozenset(
{
"arguments", # OpenAI/Anthropic tool call arguments (and its JSON string)
"const",
"default",
"enum",
"example",
"examples",
"input", # Anthropic tool_use input
"input_schema", # Anthropic tool definition
"parameters", # OpenAI tool definition
"properties", # JSON Schema property names and their schemas
"schema", # OpenAI response_format json_schema
"text", # content-block text, when a client sends it as structured data
}
)
def strip_cache_control(obj: Any) -> Any:
"""Recursively drop prompt-cache annotations, preserving schema properties."""
return _strip_cache_control(obj, preserve_key=False)
"""Drop transport prompt-cache annotations, preserving literal payloads.
def _strip_cache_control(obj: Any, *, preserve_key: bool) -> Any:
"""Strip directives while retaining names inside JSON Schema ``properties``.
``cache_control`` is also a valid user-defined JSON Schema property name.
Its value still needs normal recursion because that property's schema may
itself contain prompt-cache annotations.
``cache_control`` is overloaded: on a content block, a ``system`` entry or a
tool definition it is a caching directive the provider never feeds to the
model, so it must not fragment the key; inside tool arguments or a JSON
Schema it is ordinary application data whose value can change the
completion, so stripping it would alias two different requests onto one
cached response (see #4272). Recursion therefore stops at the payload
fields listed in ``_LITERAL_PAYLOAD_FIELDS`` and continues everywhere else.
"""
if isinstance(obj, dict):
return {
k: _strip_cache_control(v, preserve_key=k == "properties")
k: v if k in _LITERAL_PAYLOAD_FIELDS else strip_cache_control(v)
for k, v in obj.items()
if k != "cache_control" or preserve_key
if k != "cache_control"
}
if isinstance(obj, list):
return [_strip_cache_control(item, preserve_key=False) for item in obj]
return [strip_cache_control(item) for item in obj]
return obj
@@ -135,12 +157,17 @@ def compute_semantic_cache_key(
"""Compute a stable cache key from request content and shaping fields.
``cache_control`` is stripped from ``messages`` as well as the shaping
fields: it is a prompt-caching directive for the upstream provider that
never changes the generated completion, so a moved breakpoint must not
fragment the key. Messages are the primary key component and, on the
Anthropic path, the most common place a client (e.g. Claude Code) moves a
breakpoint between turns, so leaving them un-stripped defeated the strip for
the field that matters most.
fields: at request-structure positions it is a prompt-caching directive for
the upstream provider that never changes the generated completion, so a
moved breakpoint must not fragment the key. Messages are the primary key
component and, on the Anthropic path, the most common place a client (e.g.
Claude Code) moves a breakpoint between turns, so leaving them un-stripped
defeated the strip for the field that matters most.
Opaque payload keeps its ``cache_control``-named fields: inside tool inputs,
tool schemas, and ``const``/``default``/``enum`` values that name is
application data the model sees, so requests differing there must not share
a key (see :func:`strip_cache_control`).
``partition`` (see :func:`compute_cache_partition`) is mandatory: a shared
proxy must never answer one caller from another caller's cached response.
+25 -2
View File
@@ -35,6 +35,7 @@ import logging
import math
import os
import signal
import ssl
import sys
import tempfile
import threading
@@ -124,6 +125,7 @@ from headroom.providers.registry import (
from headroom.proxy import runtime_env
from headroom.proxy.audit import is_auditable_path, record_admin_action
from headroom.proxy.auth_mode import CLIENT_UA_MAP, should_stamp_codex_client
from headroom.proxy.auth_policy import client_version_from_user_agent
from headroom.proxy.background_compression import BackgroundCompressor
from headroom.proxy.budget_basis_policy import resolve_estimated_basis_policy
from headroom.proxy.buffered_ccr_response import DEFAULT_BUFFERED_CCR_GRACE_SECONDS
@@ -145,6 +147,7 @@ from headroom.proxy.helpers import (
EAGER_PRELOAD_TIMEOUT_SECONDS,
MAX_COMPRESSION_CACHE_SESSIONS,
RETRYABLE_OVERLOAD_STATUSES,
RequestWriteTrace,
_setup_file_logging,
is_anthropic_auth, # noqa: F401
jitter_delay_ms,
@@ -222,6 +225,7 @@ from headroom.subscription.tracker import (
)
from headroom.telemetry import get_telemetry_collector
from headroom.telemetry.beacon import beacon_off_reason, is_beacon_enabled, is_telemetry_enabled
from headroom.telemetry.session import record_client_version
from headroom.telemetry.toin import get_toin
from headroom.transforms import (
CacheAligner,
@@ -2876,6 +2880,8 @@ class HeadroomProxy(
)
for attempt in range(self.config.retry_max_attempts):
request_trace = RequestWriteTrace()
post_kwargs["extensions"] = {"trace": request_trace}
try:
if stream:
# For streaming, we return early - retry happens at higher level
@@ -2941,10 +2947,16 @@ class HeadroomProxy(
# HTTP/2 `StreamReset`) that a poisoned shared h2 connection raises on
# every in-flight request. Retrying drops the bad connection and
# re-sends on a fresh one instead of collapsing to a 502. (#1639)
except (httpx.TransportError, httpx.HTTPStatusError) as e:
# A raw ssl.SSLError escapes httpx's TransportError mapping; it is
# retried only if the request write failed (RequestWriteTrace).
except (httpx.TransportError, httpx.HTTPStatusError, ssl.SSLError) as e:
last_error = e
if not self.config.retry_enabled or attempt >= self.config.retry_max_attempts - 1:
if (
not self.config.retry_enabled
or attempt >= self.config.retry_max_attempts - 1
or request_trace.forbids_retry(e)
):
# On exhaustion, preserve the upstream 5xx status (e.g. 503
# Service Unavailable, 500, 502, 504) so the client can apply
# its own retry/backoff. Collapsing every exhausted 5xx into a
@@ -4461,6 +4473,17 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
proxy.metrics.record_stack(stack)
except Exception:
logger.debug("record_stack failed", exc_info=True)
if method == "POST":
# The harness's own release, for the anonymous beacon. Every route,
# not only /v1/: Gemini, Bedrock and ChatGPT-auth Codex live
# elsewhere. Only the middleware sees the User-Agent; nothing but a
# known harness name and a numeric version leaves this call.
try:
harness = client_version_from_user_agent(headers.get("user-agent", ""))
if harness:
record_client_version(*harness)
except Exception:
logger.debug("record_client_version failed", exc_info=True)
try:
response = await call_next(request)
except asyncio.CancelledError:
+18 -12
View File
@@ -242,19 +242,23 @@ class BM25Scorer(RelevanceScorer):
# redo identical work per item.
context_freq = Counter(context_tokens)
# Compute average document length for normalization
all_tokens = [self._tokenize(item) for item in items]
avg_len = sum(len(t) for t in all_tokens) / max(len(items), 1)
# Retain corpus statistics, not the tokens for the entire batch.
total_len = 0
n_docs = 0
doc_freq_across: Counter[str] = Counter()
for item in items:
tokens = self._tokenize(item)
total_len += len(tokens)
n_docs += 1
doc_freq_across.update({token for token in tokens if token in context_freq})
del tokens
avg_len = total_len / max(len(items), 1)
# Compute corpus IDF per query term. Unlike single-item scoring,
# a batch is a real corpus, so document frequency is meaningful:
# terms that appear in many items are down-weighted while rare,
# discriminative terms (IDs, UUIDs) are boosted. This is what makes
# the ranking BM25 rather than plain term-frequency weighting.
n_docs = len(all_tokens)
doc_freq_across: Counter[str] = Counter()
for tokens in all_tokens:
doc_freq_across.update(set(tokens))
idf_map = {
term: self._compute_idf(term, n_docs, doc_freq_across[term])
for term in set(context_tokens)
@@ -262,7 +266,9 @@ class BM25Scorer(RelevanceScorer):
}
results = []
for item_tokens in all_tokens:
reasons = {0: "BM25: no matches"}
for item in items:
item_tokens = self._tokenize(item)
raw_score, matched = self._bm25_score(
item_tokens,
context_tokens,
@@ -270,6 +276,7 @@ class BM25Scorer(RelevanceScorer):
idf_map=idf_map,
query_freq=context_freq,
)
del item_tokens
# Normalize
if self.normalize_score:
@@ -283,10 +290,9 @@ class BM25Scorer(RelevanceScorer):
normalized = min(1.0, normalized + 0.3)
match_count = len(matched)
if match_count == 0:
reason = "BM25: no matches"
else:
reason = f"BM25: {match_count} terms"
if match_count not in reasons:
reasons[match_count] = f"BM25: {match_count} terms"
reason = reasons[match_count]
results.append(
RelevanceScore(
+269 -8
View File
@@ -91,6 +91,23 @@ type and its arithmetic, and the folding for the new signals is isolated in
counted in ``errors`` and deliberately NOT folded into ``failures``, which
has been 5xx-only in every row of the corpus and must stay that way.
Later additions, same version (they are additive too, and a reader tells
them apart by presence):
* ``client_usage`` / ``model_usage`` — the session's tokens split by harness
and by model. ``clients`` and ``models`` only say who took part; a session
that mixed two harnesses, or Haiku with Opus, could not be divided or priced.
``client_usage`` covers every turn, so traffic with no identified harness is
a visible row instead of a silent gap.
* ``client_versions`` — the harness's own release (``claude-code 2.1.311``).
Harness releases change request shape far more often than Headroom does.
* ``install`` — how old this install id is, and whether it lives in a
container or CI job. Separates a returning user from an id that is minted
fresh on every run.
* A session that is at least half a day old is closed by the first request on
a later UTC day (``ended: "rollover"``), so an always-on proxy reports about
one row per day instead of a single total that grows for weeks.
Everything added is a counter, a ratio, or a slug from a vocabulary that is
closed in code. Two things are still refused on principle: anything derived
from prompt or file content (which is why ``turn_id`` and TOIN's
@@ -347,6 +364,80 @@ _WASTE_KEYS = (
_STRATUM_TREATMENT = "output_shaper:stratum:"
_STRATUM_CONTROL = "output_shaper:control:"
# Per-turn token columns of `client_usage` and `model_usage`, in order. `n` is
# turns. Every column is the raw per-turn counter, so each sums to its session
# total.
#
# To price a row, do what `CostTracker.record` does: where a provider reports
# no write count, Headroom infers one as input minus cached, and those are the
# same tokens as `uncached`, never billed as a write. `cache_write_inferred`
# is that part, so billed input is
# uncached + cache_read + (cache_write - cache_write_inferred)
# and `cache_write_5m` / `cache_write_1h` split the billed writes by TTL, which
# changes their rate.
_USAGE_FIELDS = (
"n",
"original",
"saved",
"tool_saved",
"output",
"cache_read",
"cache_write",
"cache_write_inferred",
"cache_write_5m",
"cache_write_1h",
"uncached",
)
# Rows per usage table before the rest pool into "other". A session rarely
# sees more than three harnesses or five models; every row is eleven numbers on
# a payload that is re-sent every five minutes, and `_fit_to_wire` cannot shed
# these rows, so the cap is what bounds them.
MAX_USAGE_ROWS = 8
MAX_CLIENT_VERSIONS = 16
# Every harness name `client_usage` and `client_versions` may carry. The value
# comes from `classify_client`, which returns the caller's own `X-Client`
# header when one is sent, so a shape check alone would put whatever a caller
# typed there on the wire with token volumes attached. Names outside this set
# pool into "other". Mirrors `CLIENT_UA_MAP` in headroom/proxy/auth_policy.py
# and `_KNOWN_WRAP_AGENTS` in context.py; duplicated because this package does
# not import `headroom.proxy` (see `record_stack`), and a test holds them equal.
_KNOWN_CLIENTS = frozenset(
{
"aider",
"anthropic_cli",
"antigravity",
"claude",
"claude_code",
"claude_vscode",
"codex",
"copilot",
"cursor",
"droid",
"grok_build",
"omp",
"openclaw",
"opencode",
"strands",
"zed",
}
)
# Labels for turns no harness claimed, so `client_usage` sums to
# `session.turns`. Measured on the corpus: a quarter of sessions carried no
# harness at all, and most of those turns came through /v1/compress.
_CLIENT_VIA_MCP = "via_mcp"
_CLIENT_VIA_COMPRESS = "via_compress_api"
_CLIENT_UNIDENTIFIED = "unidentified"
# A harness release as it appears in a User-Agent: up to three numeric parts.
# Anything else (a build hash, a hostname) is not a version and is not sent.
_VERSION_RE = re.compile(r"^\d{1,4}(?:\.\d{1,4}){0,2}$")
# A session at least this old is closed by the first request on a later UTC
# day. Long enough that an afternoon of work running past midnight UTC stays
# one session; short enough that the pieces of an always-on proxy, which start
# a few seconds after midnight, are old enough to close at the next one. The
# first piece can therefore span two dates; every later one is a single day.
ROLLOVER_MIN_AGE_S = 12 * 3600.0
_INSTALL_AGE_CAP_DAYS = 9999
# Environment variables whose values may be reported, by name. An allowlist,
# never a dump of the environment: a variable absent from this tuple cannot
# reach the wire whatever it holds, and every value that does is put through
@@ -412,6 +503,10 @@ _staged_shapes: dict[tuple[str, str], list[int]] = {}
# tool-output shape slug -> [events, tokens_in, tokens_out]. The structural
# descriptor only — never TOIN's `structure_hash`. See `record_tool_shape`.
_staged_tool_shapes: dict[str, list[int]] = {}
# (harness, version) -> requests. Staged because only the HTTP middleware sees
# the User-Agent, and it runs before any outcome exists. See
# `record_client_version`.
_staged_client_versions: dict[tuple[str, str], int] = {}
def _pct(numerator: float, denominator: float) -> float:
@@ -471,6 +566,76 @@ def _bump(counter: dict[str, int], key: str, *, cap: int = MAX_SHAPES) -> None:
counter[key] = counter.get(key, 0) + 1
def _tool_saved(tags: Any) -> int:
"""Tool-schema tokens saved on one turn. These live only in tags — see the
same arithmetic in emit_request_outcome, which feeds the local dashboard."""
total = 0
if isinstance(tags, dict):
for tag in ("tool_search_deferred_tokens", "turn_hook_tools_saved_tokens"):
try:
total += int(tags.get(tag, 0) or 0)
except (TypeError, ValueError):
pass
return total
def _add_usage(table: dict[str, list[int]], key: str, values: tuple[int, ...]) -> None:
"""Add one turn to a usage table. Past the cap, new keys pool into "other".
Pooled rather than dropped, unlike `_bump`: these tables exist to split the
session's totals, and a split that silently loses turns stops adding up.
"""
if key not in table and len(table) >= MAX_USAGE_ROWS:
key = "other"
row = table.setdefault(key, [0] * len(values))
for index, value in enumerate(values):
row[index] += value
def _known_client(value: Any) -> str:
"""A harness name from `_KNOWN_CLIENTS`, else "other"."""
slug = _client_slug(value)
return slug if slug in _KNOWN_CLIENTS else "other"
def _usage_rows(label: str, table: dict[str, list[int]]) -> list[dict[str, Any]]:
return [
{label: key, **dict(zip(_USAGE_FIELDS, row, strict=True))}
for key, row in sorted(table.items())
]
def _install_facts() -> dict[str, Any]:
"""Age of this install id and where it is running. Three closed values.
The corpus could not tell a user who came back from an id minted fresh on
every container start: Linux proxies showed five times the installs of
macOS for the same traffic. `age_days` is how long ago the id file was
written, so it needs no new state and resets with the id. It is 0 when no
id is kept on disk (stateless mode, or a file that could not be written),
which is what an id minted per run looks like.
"""
from headroom import paths
age_days = 0
if not paths.process_is_stateless():
try:
written = _install_id_path().stat().st_mtime
except OSError:
pass # no id file: age stays 0
else:
age_days = min(max(int((time.time() - written) // 86400), 0), _INSTALL_AGE_CAP_DAYS)
return {
"age_days": age_days,
"container": bool(
os.environ.get("KUBERNETES_SERVICE_HOST")
or os.path.exists("/.dockerenv")
or os.path.exists("/run/.containerenv")
),
"ci": os.environ.get("CI", "").strip().lower() in ("1", "true", "yes"),
}
def _turn_kind(*, cached: bool, status: int, passthrough: bool, attempted: int, saved: int) -> str:
"""Classify one turn into the closed `_TURN_KINDS` alphabet.
@@ -769,6 +934,10 @@ class _Session:
strata_turn_kind: dict[str, int] = field(default_factory=dict)
strata_input_bucket: dict[str, int] = field(default_factory=dict)
strata_tools: dict[str, int] = field(default_factory=dict)
# label -> one count per `_USAGE_FIELDS` column.
client_usage: dict[str, list[int]] = field(default_factory=dict)
model_usage: dict[str, list[int]] = field(default_factory=dict)
client_versions: dict[tuple[str, str], int] = field(default_factory=dict)
def observe(self, name: str, value: float) -> None:
"""Record one sample into a named histogram."""
@@ -1184,6 +1353,23 @@ class _Session:
"config": [
{"key": key, "value": value} for key, value in sorted(_config_snapshot().items())
],
# The session's tokens split by harness and by model. Each table's
# `n` sums to `session.turns` and each token column to its total in
# `tokens`, so either one divides the session without residue.
# `clients` and `models` above are left exactly as they were.
"client_usage": _usage_rows("client", self.client_usage),
"model_usage": _usage_rows("model", self.model_usage),
# Requests by harness release. Counted at the HTTP layer, so `n` is
# requests, not turns: it includes ones that never became a turn,
# and a request that lands just before a session closes is counted
# in whichever session folds next. WebSocket sessions never pass
# that layer and are absent. Read it as "which releases, roughly
# how much", not as a split of the session.
"client_versions": [
{"client": client, "version": version, "n": count}
for (client, version), count in sorted(self.client_versions.items())
],
"install": _install_facts(),
}
@@ -1223,6 +1409,17 @@ class SessionAggregator:
if live is not None and now - live.last_seen >= self._idle_s:
pending.append(live.payload("idle"))
live = None
# An always-on proxy never goes idle, so its one session grew
# for weeks and a day's activity could only be recovered by
# differencing heartbeats. Closing at the day boundary makes
# each row one day's work.
if (
live is not None
and now - live.started >= ROLLOVER_MIN_AGE_S
and now // 86400 != live.started // 86400
):
pending.append(live.payload("rollover"))
live = None
if live is None:
live = _Session(
sid=secrets.token_hex(8),
@@ -1345,14 +1542,9 @@ def _fold(sess: _Session, outcome: Any, now: float, source: str = "proxy") -> No
# problem, not a compression problem, and the two are indistinguishable
# from the token counts alone.
tags = get("tags", None) or {}
tool_saved = _tool_saved(tags)
if isinstance(tags, dict):
# Tool-schema savings live only in tags — see the same arithmetic in
# emit_request_outcome, which feeds the local dashboard.
for tag in ("tool_search_deferred_tokens", "turn_hook_tools_saved_tokens"):
try:
sess.tool_saved_tokens += int(tags.get(tag, 0) or 0)
except (TypeError, ValueError):
pass
sess.tool_saved_tokens += tool_saved
for tag in _REASON_TAGS:
if tag in tags:
key = f"{tag.removesuffix('_reason')}:{_safe_slug(tags[tag])}"
@@ -1377,7 +1569,7 @@ def _fold(sess: _Session, outcome: Any, now: float, source: str = "proxy") -> No
# `_fold` before the caller's heartbeat check and costs a whole emission,
# which is a v1 consequence for a v2 fault.
try:
_fold_extra(sess, get, now, prev_seen, tags, status)
_fold_extra(sess, get, now, prev_seen, tags, status, source, tool_saved)
except Exception:
logger.debug("telemetry: v2 fold failed", exc_info=True)
@@ -1389,6 +1581,8 @@ def _fold_extra(
prev_seen: float | None,
tags: Any,
status: int,
source: str = "proxy",
tool_saved: int = 0,
) -> None:
"""Fold the schema-v2 signals. Additive by construction.
@@ -1409,6 +1603,42 @@ def _fold_extra(
passthrough = is_dict_tags and "passthrough_reason" in tags
cached = bool(get("from_response_cache", False))
# -- usage by harness and by model --------------------------------------
# The same per-turn quantities `_fold` adds to the session totals, so each
# table sums back to them. First in this function for that reason: a fault
# in a section below must not leave a turn counted in `tokens` and missing
# here.
cache_write = int(get("cache_write_tokens") or 0)
turn = (
1,
original,
saved,
tool_saved,
int(get("output_tokens") or 0),
int(get("cache_read_tokens") or 0),
cache_write,
cache_write if get("cache_inferred", False) else 0,
int(get("cache_write_5m_tokens") or 0),
int(get("cache_write_1h_tokens") or 0),
int(get("uncached_input_tokens") or 0),
)
client = get("client", None)
if client:
label = _known_client(client)
elif source == "mcp":
label = _CLIENT_VIA_MCP
elif get("provider", "") == "compress":
label = _CLIENT_VIA_COMPRESS
else:
label = _CLIENT_UNIDENTIFIED
_add_usage(sess.client_usage, label, turn)
# A model id no public registry vouches for can carry an org name (see
# `_public_model`), so it is pooled, never sent.
_add_usage(sess.model_usage, _public_model(str(get("model", "") or "")) or "other", turn)
for version_key, count in _drain_staged_client_versions().items():
if version_key in sess.client_versions or len(sess.client_versions) < MAX_CLIENT_VERSIONS:
sess.client_versions[version_key] = sess.client_versions.get(version_key, 0) + count
# -- distributions ------------------------------------------------------
sess.observe("turn_tokens", original)
sess.observe("overhead_ms", float(get("overhead_ms", 0.0) or 0.0))
@@ -2176,6 +2406,37 @@ class BeaconCompressionObserver:
record_compression(strategy, original_tokens, compressed_tokens)
def record_client_version(client: Any, version: Any) -> None:
"""Beacon entry point for one request's harness release.
Called from the proxy's HTTP middleware, the only place that sees the
User-Agent. Both parts are validated here rather than trusted: the harness
must slug cleanly and the version must be numeric, so a User-Agent that
carries anything else contributes nothing.
"""
from headroom.telemetry.beacon import is_beacon_enabled
if not is_beacon_enabled():
return
slug, text = _known_client(client), str(version or "")
if slug == "other" or not _VERSION_RE.match(text):
return
key = (slug, text)
with _staged_lock:
if key in _staged_client_versions or len(_staged_client_versions) < MAX_CLIENT_VERSIONS:
_staged_client_versions[key] = _staged_client_versions.get(key, 0) + 1
def _drain_staged_client_versions() -> dict[tuple[str, str], int]:
"""Take every staged (harness, version) request count."""
with _staged_lock:
if not _staged_client_versions:
return {}
drained = dict(_staged_client_versions)
_staged_client_versions.clear()
return drained
def _drain_staged_strategies() -> dict[str, list[int]]:
"""Take everything staged since the last drain. Caller merges it."""
with _staged_lock:
+260 -77
View File
@@ -143,6 +143,10 @@ _ALREADY_COMPRESSED_MARKERS = (
"<<ccr:",
)
_CCR_MARKER_HASH_RE = re.compile(
r"(?:Retrieve (?:more|original): hash=|<<ccr:)([0-9a-fA-F]{12,64})(?=[^0-9a-fA-F]|$)"
)
def _is_already_compressed(text: str) -> bool:
"""True if ``text`` still carries a CCR retrieval marker.
@@ -607,6 +611,24 @@ def _external_compressor_matches(descriptor: CompressorDescriptor, content_mime:
return any(d in ("*", "*/*") or d == type_wildcard for d in declared)
def _carries_cache_control(block: dict[str, Any]) -> bool:
"""True when ``block`` holds a client ``cache_control`` breakpoint.
The Messages API also accepts the marker on a sub-block of a
``tool_result``'s list content. Rewriting that tool_result drops the
marker exactly like one on the block itself, so both count (the same
shapes ``count_cache_breakpoints`` counts).
"""
if "cache_control" in block:
return True
if block.get("type") != "tool_result":
return False
inner = block.get("content")
return isinstance(inner, list) and any(
isinstance(sub, dict) and "cache_control" in sub for sub in inner
)
def _malformed_tool_call_ids(messages: list[dict[str, Any]]) -> set[str]:
"""Ids of OpenAI tool calls whose ``function`` is not an object.
@@ -1797,6 +1819,13 @@ def content_cache_key(
return h.hexdigest()
# Bump when a routing change makes earlier cached output wrong for the same
# version and config, so the disk tier starts a fresh namespace instead of
# replaying it. "code-never-kompress": before #4214, code could reach Kompress
# and lose keywords; a cache made then must not be served after the fix.
_ROUTING_POLICY_REVISION = "code-never-kompress"
def _config_namespace(config: Any) -> str:
"""A prefix for this router's keys in the shared disk tier: a digest of its
config and the headroom version. The proxy may run routers configured
@@ -1822,7 +1851,9 @@ def _config_namespace(config: Any) -> str:
# starts a fresh namespace rather than serving output made under another.
settings = sorted((k, v) for k, v in os.environ.items() if k.startswith("HEADROOM_"))
h = hashlib.blake2b(digest_size=8)
h.update(f"{__version__}|{stable(asdict(config))!r}|{settings!r}".encode())
h.update(
f"{__version__}|{_ROUTING_POLICY_REVISION}|{stable(asdict(config))!r}|{settings!r}".encode()
)
return h.hexdigest() + ":"
@@ -1868,6 +1899,7 @@ class CompressionCache:
# least recently used first. ``stamp`` is the last use, or the creation
# time for a result with a CCR marker.
self._results: OrderedDict[str, tuple[str, float, str, float, float, bool]] = OrderedDict()
self._marker_hashes: dict[str, tuple[str, ...]] = {}
self._bytes = 0
# Tier 1: {key: marked_at}, oldest first.
self._skip: OrderedDict[str, float] = OrderedDict()
@@ -2007,11 +2039,35 @@ class CompressionCache:
self._evictions += 1
return False
def put(self, key: str, compressed: str, ratio: float, strategy: str) -> None:
def get_marker_hashes(self, key: str) -> tuple[str, ...]:
"""Return CCR marker hashes tracked for a cached entry."""
with self._lock:
return self._marker_hashes.get(key, ())
def invalidate(self, key: str) -> bool:
"""Drop a stale cached result without marking it skipped. Thread-safe."""
with self._lock:
existed = key in self._results
self._drop_locked(key)
if existed:
self._evictions += 1
return existed
def put(
self,
key: str,
compressed: str,
ratio: float,
strategy: str,
marker_hashes: tuple[str, ...] = (),
) -> None:
"""Store a compressed result (Tier 2). Thread-safe."""
with self._lock:
self._disk_reads.pop(key, None)
self._skip.pop(key, None)
has_marker = self._admit_locked(key, compressed, ratio, strategy)
if marker_hashes:
self._marker_hashes[key] = marker_hashes
token = object()
if self._store is not None:
self._disk_writes[key] = token
@@ -2070,6 +2126,7 @@ class CompressionCache:
entry = self._results.pop(key, None)
if entry is not None:
self._bytes -= sys.getsizeof(entry[0]) + _CACHE_ENTRY_OVERHEAD
self._marker_hashes.pop(key, None)
def _skip_locked(self, key: str) -> None:
self._skip.pop(key, None)
@@ -2124,6 +2181,7 @@ class CompressionCache:
with self._disk_lock:
with self._lock:
self._results.clear()
self._marker_hashes.clear()
self._bytes = 0
self._skip.clear()
self._disk_reads.clear()
@@ -2309,6 +2367,24 @@ def _mcp_result_min_chars() -> int:
_MCP_NAME_PREFIXES = ("mcp_", "mcp--")
def _join_tool_result_text_blocks(blocks: list[Any]) -> str:
"""Flatten list-form ``tool_result`` text blocks into one string.
Each block is a separate piece of tool output (an MCP server returning
several ``TextContent`` items, for example), so a newline goes between
blocks unless the block already ends with one. A bare ``"".join`` fuses
the last line of one block with the first line of the next, and the
line-oriented compressors then emit a line the tool never produced.
"""
parts: list[str] = []
for i, b in enumerate(blocks):
text = b.get("text", "")
parts.append(text)
if i < len(blocks) - 1 and text and not text.endswith("\n"):
parts.append("\n")
return "".join(parts)
def _is_small_mcp_result(tool_name: Any, text: Any) -> bool:
"""True when ``text`` is an MCP tool's output short enough to keep verbatim.
@@ -4169,6 +4245,12 @@ class ContentRouter(Transform):
active = self._active_external_compressors
if not active:
return None
# PASSTHROUGH is the router's explicit "leave this block unmangled"
# decision (source code with prefer_code_aware_for_code=False, whole or
# as a mixed-content section). Its strategy maps to text/plain below, so
# a prose-only external compressor would otherwise rewrite the code.
if strategy == CompressionStrategy.PASSTHROUGH:
return None
content_mime = _CONTENT_TYPE_TO_MIME.get(self._content_type_from_strategy(strategy))
if content_mime is None:
return None
@@ -4538,12 +4620,17 @@ class ContentRouter(Transform):
# compressor on the byte-folded remainder and keep it IFF it removes a
# further meaningful chunk (Kompress must save >= _lossy_min_extra_savings
# beyond the fold). Keeps the fold AND reclaims the semantic word-drop
# tail, never doing worse than the fold. DIFF folds are returned verbatim
# — Kompressing hunks corrupts `git apply`.
# tail, never doing worse than the fold. Code and explicit passthrough
# remain lossless; Kompress would also corrupt diff hunks.
if _ll_label is not None:
_lossy_after_fold = (
self._lossless_then_lossy
and strategy != CompressionStrategy.DIFF
and strategy
not in {
CompressionStrategy.DIFF,
CompressionStrategy.CODE_AWARE,
CompressionStrategy.PASSTHROUGH,
}
and _ll_label != "lossless_diff"
and not self._looks_like_diff(content)
)
@@ -4591,14 +4678,9 @@ class ContentRouter(Transform):
compressor = self._get_code_compressor()
if compressor:
compressor_name = type(compressor).__name__
# Registry-resolved dispatch: the built-in "code_aware"
# adapter delegates to this same getter+method with the
# language passed through ``config``, so on a real
# compression the content is byte-identical to the
# historical direct call. If the adapter did NOT compress
# (``compressed=False``), leave the local ``compressed``
# None so the EXISTING Kompress fallback below runs
# exactly as today.
# The registry adapter passes the language through to
# the code-aware compressor. If it declines the block,
# preserve the original code rather than trying ML.
output = self._registry_compress(
"code_aware",
strategy,
@@ -4615,39 +4697,6 @@ class ContentRouter(Transform):
# 55% compression and no fallback could beat it.
compressed_tokens = _estimate_tokens(output.content)
decision_reason = "code_aware"
if compressed is None:
# Fallback to Kompress
compressed, compressed_tokens = self._try_ml_compressor(
content, context, question
)
strategy = CompressionStrategy.KOMPRESS # Update for TOIN
actual_strategy = strategy
compressor_name = "KompressCompressor"
decision_reason = "code_aware_unavailable_fallback_kompress"
strategy_chain.append(CompressionStrategy.KOMPRESS.value)
elif (
self._lossless_then_lossy
and compressed_tokens is not None
and compressed_tokens >= original_tokens
):
# #3 — lossless-then-lossy: code-aware produced NO net shrink
# and the lossless fold found nothing either, so this code
# block would otherwise pass through uncompressed. Give the
# lossy ML compressor (Kompress) a shot so lossy runs even when
# lossless has no savings. Reads are protected upstream, so
# only NON-read code reaches here. Keep Kompress ONLY if it
# actually shrinks (never inflate).
# Recorded as tried even if it loses, so the no-savings
# fallback below does not run the same inference again.
strategy_chain.append(CompressionStrategy.KOMPRESS.value)
_k, _ = self._try_ml_compressor(content, context, question)
_kt = _estimate_tokens(_k)
if _kt < original_tokens and len(_k) < len(content):
compressed, compressed_tokens = _k, _kt
strategy = CompressionStrategy.KOMPRESS
actual_strategy = strategy
compressor_name = "KompressCompressor"
decision_reason = "code_aware_no_shrink_fallback_kompress"
elif strategy == CompressionStrategy.SMART_CRUSHER:
# SmartCrusher handles its own TOIN recording
@@ -4872,15 +4921,11 @@ class ContentRouter(Transform):
# some rows and not others with nothing marking which (#3652).
fallback_eligible_strategy = strategy in {
CompressionStrategy.SMART_CRUSHER,
CompressionStrategy.CODE_AWARE,
CompressionStrategy.CONFIG,
}
fallback_no_savings = compressed == content or compressed_tokens >= original_tokens
if fallback_eligible_strategy and fallback_no_savings:
# Skip if Kompress was already tried by an inline fallback
# (e.g. CODE_AWARE's code-compressor-unavailable path at
# line 1249). Prevents a duplicate strategy_chain entry
# and a wasted second _try_ml_compressor call.
# Do not run Kompress twice if an inline fallback already tried it.
already_tried_kompress = CompressionStrategy.KOMPRESS.value in strategy_chain
if not already_tried_kompress:
strategy_chain.append(CompressionStrategy.KOMPRESS.value)
@@ -4952,10 +4997,9 @@ class ContentRouter(Transform):
# produced and KEEP it only if it removes a further meaningful chunk
# (>= _lossy_min_extra_savings beyond the strategy result) and is
# actually shorter — never inflating, never doing worse than the
# strategy output. DIFF is excluded (Kompress corrupts ``git
# apply``); TEXT/KOMPRESS already ran Kompress; CODE_AWARE has its
# own inline no-shrink fallback; SMART_CRUSHER uses the
# zero-savings fallback above; TABULAR never goes to Kompress.
# strategy output. Code, diffs, and tables stay out of lossy ML;
# TEXT/KOMPRESS already ran it, and SMART_CRUSHER uses the
# zero-savings fallback above.
if (
self._lossless_then_lossy
and compressed is not None
@@ -5397,6 +5441,14 @@ class ContentRouter(Transform):
# don't accept the kwarg are unaffected on the common path.
if protected:
compress_kwargs["ccr_original"] = content
# F2.2: forward the request's TOIN read-only gate per
# call, as _invoke_smart_crusher does for crush() —
# the compressor is shared across concurrent requests,
# and the kwarg is only sent when gating so
# compressors without it keep working.
_policy = self._runtime_compression_policy
if _policy is not None and _policy.toin_read_only:
compress_kwargs["record_toin"] = False
# One deadline for the whole request, not one per
# block. Without this a request with N compressible
# blocks gets N full deadlines and can run far past
@@ -5468,6 +5520,8 @@ class ContentRouter(Transform):
def _strategy_from_detection_type(self, content_type: ContentType) -> CompressionStrategy:
"""Get strategy from ContentType enum."""
if content_type == ContentType.SOURCE_CODE and not self.config.prefer_code_aware_for_code:
return CompressionStrategy.PASSTHROUGH
mapping = {
ContentType.SOURCE_CODE: CompressionStrategy.CODE_AWARE,
ContentType.JSON_ARRAY: CompressionStrategy.SMART_CRUSHER,
@@ -5515,10 +5569,13 @@ class ContentRouter(Transform):
self._code_compressor = CodeAwareCompressor(
CodeCompressorConfig(
enable_ccr=self.config.ccr_inject_marker,
# The code compressor's Kompress fallback builds its
# own KompressCompressor, so it must honour the same
# switch as _get_kompress() (#4719).
fallback_to_kompress=self.config.enable_kompress,
# Never let the code compressor fall back to Kompress
# internally (unknown language, Perl, no tree-sitter,
# AST failure). Kompress is a prose model and drops
# keywords from code (#4214). A block the code
# compressor cannot handle stays unchanged, whether or
# not Kompress is enabled for prose (#4719).
fallback_to_kompress=False,
)
)
else:
@@ -6856,6 +6913,7 @@ class ContentRouter(Transform):
prefix_replay_guaranteed=prefix_replay_guaranteed,
protect_prompt_text=prompt_turn,
in_mutable_window=(i >= mutable_turn_start),
compression_store=kwargs.get("compression_store"),
)
result_slots[i] = transformed_message
route_counts["content_blocks"] += 1
@@ -7159,6 +7217,12 @@ class ContentRouter(Transform):
# Tier 2: result cache — reuse compressed output
cached = self._cache.get(content_key)
if cached is not None and not self._cached_markers_retrievable(
content_key,
compression_store=kwargs.get("compression_store"),
):
self._cache.invalidate(content_key)
cached = None
if cached is not None:
cached_compressed, cached_ratio, cached_strategy = cached
# Cache-churn fix: if a verdict was frozen for this block on a
@@ -7250,6 +7314,10 @@ class ContentRouter(Transform):
# --- Pass 2: Parallel compression of all cache-miss messages ---
if pending_tasks:
_ccr_store = self._resolve_ccr_store(kwargs.get("compression_store"))
_ccr_write_seq_before = (
getattr(_ccr_store, "write_seq", None) if _ccr_store is not None else None
)
max_workers = min(len(pending_tasks), _compress_workers())
t_parallel_start = time.perf_counter()
@@ -7411,12 +7479,27 @@ class ContentRouter(Transform):
# warmed when the net-cost gate blocks the slot: the
# gate's verdict is contextual (suffix size), the
# compression result is not.
self._cache.put(
content_key,
result.compressed,
accept_ratio,
result.strategy_used.value,
_ccr_store_wrote = (
_ccr_write_seq_before is not None
and _ccr_store is not None
and getattr(_ccr_store, "write_seq", None) != _ccr_write_seq_before
)
_marker_hashes = self._collect_verified_marker_hashes(
result.compressed,
compression_store=kwargs.get("compression_store"),
store_wrote=_ccr_store_wrote,
)
if self._markers_currently_retrievable(
_marker_hashes,
compression_store=kwargs.get("compression_store"),
):
self._cache.put(
content_key,
result.compressed,
accept_ratio,
result.strategy_used.value,
marker_hashes=_marker_hashes,
)
# Freeze "compress" so the cache-hit path above never
# re-applies a tighter min_ratio to this block.
if freeze_decision:
@@ -7807,7 +7890,7 @@ class ContentRouter(Transform):
tc = block.get("content")
protected = (
frozen
or ("cache_control" in block)
or _carries_cache_control(block)
or block.get("tool_use_id") in verbatim_tool_ids
)
if isinstance(tc, str) and tc:
@@ -7897,6 +7980,61 @@ class ContentRouter(Transform):
except Exception: # never break the proxy
return messages
@staticmethod
def _resolve_ccr_store(compression_store: Any = None) -> Any:
if compression_store is not None:
return compression_store
try:
from ..cache.compression_store import get_compression_store
return get_compression_store()
except ImportError:
return None
@classmethod
def _collect_verified_marker_hashes(
cls,
compressed_text: str,
compression_store: Any = None,
store_wrote: bool = False,
) -> tuple[str, ...]:
if not _is_already_compressed(compressed_text):
return ()
hashes = tuple(dict.fromkeys(_CCR_MARKER_HASH_RE.findall(compressed_text)))
if not hashes:
return ()
if store_wrote:
return hashes
store = cls._resolve_ccr_store(compression_store)
exists_fn = getattr(store, "exists", None) if store is not None else None
if exists_fn is None:
return ()
return tuple(h for h in hashes if exists_fn(h))
@classmethod
def _markers_currently_retrievable(
cls,
marker_hashes: tuple[str, ...],
compression_store: Any = None,
) -> bool:
if not marker_hashes:
return True
store = cls._resolve_ccr_store(compression_store)
exists_fn = getattr(store, "exists", None) if store is not None else None
if exists_fn is None:
return True
return all(bool(exists_fn(hash_key)) for hash_key in marker_hashes)
def _cached_markers_retrievable(
self,
content_key: str,
compression_store: Any = None,
) -> bool:
return self._markers_currently_retrievable(
self._cache.get_marker_hashes(content_key),
compression_store=compression_store,
)
def _process_content_blocks(
self,
message: dict[str, Any],
@@ -7919,12 +8057,14 @@ class ContentRouter(Transform):
prefix_replay_guaranteed: bool = False,
protect_prompt_text: bool = False,
in_mutable_window: bool | None = None,
compression_store: Any = None,
) -> dict[str, Any]:
"""Process content blocks (Anthropic format) for compression.
Cache-safety contract:
1. Any block carrying `cache_control` is the client's explicit
cache breakpoint. Modifying any byte of such a block changes
1. Any block carrying `cache_control` (on the block itself or on
a sub-block of a tool_result's list content) is the client's
explicit cache breakpoint. Modifying any byte of such a block changes
the cache key the upstream provider matches against, turning
a 90% read discount into a 25% write penalty (Anthropic).
We never modify cache_control'd blocks, regardless of role
@@ -8038,7 +8178,9 @@ class ContentRouter(Transform):
# cache breakpoint. Frozen-message-count is a coarse
# message-level approximation; this is the per-block
# guarantee that we never bust an explicit cache key.
if "cache_control" in block and not (fresh_turn and block.get("type") == "tool_result"):
if _carries_cache_control(block) and not (
fresh_turn and block.get("type") == "tool_result"
):
new_blocks.append(block)
if route_counts is not None:
route_counts.setdefault("cache_control_protected", 0)
@@ -8061,7 +8203,7 @@ class ContentRouter(Transform):
and all(isinstance(b, dict) and b.get("type") == "text" for b in _tr_content)
)
_tr_text = (
"".join(b.get("text", "") for b in _tr_content)
_join_tool_result_text_blocks(_tr_content)
if _tr_list_form_early
else _tr_content
)
@@ -8166,9 +8308,7 @@ class ContentRouter(Transform):
and all(isinstance(b, dict) and b.get("type") == "text" for b in tool_content)
)
tool_text = (
"".join(b.get("text", "") for b in tool_content)
if _tr_list_form
else tool_content
_join_tool_result_text_blocks(tool_content) if _tr_list_form else tool_content
)
# Small MCP results stay verbatim (see _is_small_mcp_result).
@@ -8272,6 +8412,7 @@ class ContentRouter(Transform):
strategy_label="tool_result",
details_prefix="tool",
enforce_reversibility=True,
compression_store=compression_store,
)
if compressed_content is not None:
new_blocks.append(
@@ -8371,6 +8512,7 @@ class ContentRouter(Transform):
strategy_label="text_block",
details_prefix="text",
enforce_reversibility=enforce_reversibility,
compression_store=compression_store,
)
if compressed_content is not None:
new_blocks.append({**block, "text": compressed_content})
@@ -8403,6 +8545,7 @@ class ContentRouter(Transform):
strategy_label: str,
details_prefix: str,
enforce_reversibility: bool = False,
compression_store: Any = None,
) -> tuple[str | None, bool]:
"""Apply two-tier cache lookup + compression to a single content string.
@@ -8461,6 +8604,12 @@ class ContentRouter(Transform):
# Tier 2: result cache — reuse compressed output
cached = self._cache.get(content_key)
if cached is not None and not self._cached_markers_retrievable(
content_key,
compression_store=compression_store,
):
self._cache.invalidate(content_key)
cached = None
if cached is not None:
cached_compressed, cached_ratio, cached_strategy = cached
if route_counts is not None:
@@ -8505,8 +8654,17 @@ class ContentRouter(Transform):
# Cache miss — run full compression
if route_counts is not None:
route_counts["cache_miss"] = route_counts.get("cache_miss", 0) + 1
_blk_ccr_store = self._resolve_ccr_store(compression_store)
_blk_write_seq_before = (
getattr(_blk_ccr_store, "write_seq", None) if _blk_ccr_store is not None else None
)
t0 = time.perf_counter()
result = self.compress(content, context=context, bias=bias)
_blk_store_wrote = (
_blk_write_seq_before is not None
and _blk_ccr_store is not None
and getattr(_blk_ccr_store, "write_seq", None) != _blk_write_seq_before
)
compress_ms = (time.perf_counter() - t0) * 1000
if compressor_timing is not None:
key = f"compressor:{result.strategy_used.value}"
@@ -8535,7 +8693,22 @@ class ContentRouter(Transform):
if _byte_accept and len(result.compressed) < len(content):
_ll_ratio = len(result.compressed) / max(1, len(content))
_ll_label = _chain[0] if _is_pure_lossless else "+".join(_chain)
self._cache.put(content_key, result.compressed, _ll_ratio, _ll_label)
_blk_markers = self._collect_verified_marker_hashes(
result.compressed,
compression_store=compression_store,
store_wrote=_blk_store_wrote,
)
if self._markers_currently_retrievable(
_blk_markers,
compression_store=compression_store,
):
self._cache.put(
content_key,
result.compressed,
_ll_ratio,
_ll_label,
marker_hashes=_blk_markers,
)
transforms_applied.append(f"router:{strategy_label}:{_ll_label}")
if compressed_details is not None:
compressed_details.append(f"{details_prefix}:{_ll_label}:{_ll_ratio:.2f}")
@@ -8578,12 +8751,22 @@ class ContentRouter(Transform):
)
return None, False
# Compressed — store in result cache
self._cache.put(
content_key,
_blk_markers = self._collect_verified_marker_hashes(
result.compressed,
result.compression_ratio,
result.strategy_used.value,
compression_store=compression_store,
store_wrote=_blk_store_wrote,
)
if self._markers_currently_retrievable(
_blk_markers,
compression_store=compression_store,
):
self._cache.put(
content_key,
result.compressed,
result.compression_ratio,
result.strategy_used.value,
marker_hashes=_blk_markers,
)
# Freeze "compress" so the cache-hit path above never re-applies a
# tighter min_ratio to this block.
if freeze_decision and self._frozen_verdict_recoverable(
+38 -16
View File
@@ -1715,7 +1715,9 @@ def ccr_retrieval_marker(
)
def store_kompress_in_ccr(original: str, compressed: str, original_tokens: int) -> str | None:
def store_kompress_in_ccr(
original: str, compressed: str, original_tokens: int, *, record_toin: bool = True
) -> str | None:
"""Store an original->compressed mapping in the proxy-local CCR store and
return its retrieval hash (or None on any failure).
@@ -1723,6 +1725,11 @@ def store_kompress_in_ccr(original: str, compressed: str, original_tokens: int)
(:mod:`headroom.transforms.kompress_remote`) share one CCR policy. Model-free
— touches only the compression store + telemetry, never the ONNX model — so
it works in a sandboxed proxy installed without the ``[ml]`` extra.
``record_toin=False`` still stores in CCR (the compressed output stays
retrievable) but skips the TOIN observation for this call. Callers pass
it when the request's ``CompressionPolicy`` has ``toin_read_only=True``
(Subscription, F2.2), mirroring ``SmartCrusher.crush(record_toin=...)``.
"""
try:
from ..cache.compression_store import get_compression_store
@@ -1744,17 +1751,18 @@ def store_kompress_in_ccr(original: str, compressed: str, original_tokens: int)
tool_signature_hash=signature.structure_hash,
compression_strategy="kompress",
)
with contextlib.suppress(Exception):
from ..telemetry import get_toin
if record_toin:
with contextlib.suppress(Exception):
from ..telemetry import get_toin
get_toin().record_compression(
tool_signature=signature,
original_count=original_tokens,
compressed_count=compressed_tokens,
original_tokens=original_tokens,
compressed_tokens=compressed_tokens,
strategy="kompress",
)
get_toin().record_compression(
tool_signature=signature,
original_count=original_tokens,
compressed_count=compressed_tokens,
original_tokens=original_tokens,
compressed_tokens=compressed_tokens,
strategy="kompress",
)
return cache_key
except Exception as e:
# Store backends can echo the payload in errors, so no level logs it;
@@ -1931,6 +1939,7 @@ class KompressCompressor(Transform):
*,
allow_download: bool = True,
ccr_original: str | None = None,
record_toin: bool = True,
_deadline_started_at: float | None = None,
_time_budget_cap_seconds: float | None = None,
) -> KompressResult:
@@ -1953,6 +1962,10 @@ class KompressCompressor(Transform):
``content`` is a tag-protected placeholder intermediate
({{HEADROOM_TAG_N}}); passing the pre-protection original keeps a
later full retrieval lossless. Defaults to ``content``.
record_toin: When False, the CCR store still records the mapping
but no TOIN observation is written for this call. The router
passes it when the request policy is ``toin_read_only``
(Subscription, F2.2).
Returns:
KompressResult with compressed text.
@@ -1994,6 +2007,7 @@ class KompressCompressor(Transform):
target_ratio=[target_ratio],
batch_size=_batch_size(),
ccr_originals=[ccr_original],
record_toin=record_toin,
_deadline_started_at=t_deadline,
_time_budget_cap_seconds=_time_budget_cap_seconds,
)
@@ -2197,7 +2211,8 @@ class KompressCompressor(Transform):
if self.config.enable_ccr:
ccr_source = ccr_original if ccr_original is not None else content
ccr_source_tokens = len(ccr_source.split())
cache_key = self._store_in_ccr(ccr_source, compressed, ccr_source_tokens)
gate: dict[str, bool] = {} if record_toin else {"record_toin": False}
cache_key = self._store_in_ccr(ccr_source, compressed, ccr_source_tokens, **gate)
if cache_key:
# Report the source line span so a reader can tell content was
# compressed away rather than absent — "items" counts words, which
@@ -2292,6 +2307,7 @@ class KompressCompressor(Transform):
batch_size: int = 32,
*,
ccr_originals: list[str | None] | None = None,
record_toin: bool = True,
_deadline_started_at: float | None = None,
_time_budget_cap_seconds: float | None = None,
) -> list[KompressResult]:
@@ -2402,6 +2418,7 @@ class KompressCompressor(Transform):
question=question,
target_ratio=r,
ccr_original=ccr_source,
record_toin=record_toin,
_deadline_started_at=t_deadline,
_time_budget_cap_seconds=(
None if cap_ends_at is None else cap_ends_at - time.monotonic()
@@ -2637,7 +2654,8 @@ class KompressCompressor(Transform):
if ccr_source is None:
ccr_source = content
ccr_source_tokens = len(ccr_source.split())
cache_key = self._store_in_ccr(ccr_source, compressed, ccr_source_tokens)
gate: dict[str, bool] = {} if record_toin else {"record_toin": False}
cache_key = self._store_in_ccr(ccr_source, compressed, ccr_source_tokens, **gate)
if cache_key:
# Report the source line span so a reader can tell content was
# compressed away rather than absent — "items" counts words, which
@@ -2746,6 +2764,8 @@ class KompressCompressor(Transform):
**kwargs: Any,
) -> TransformResult:
"""Apply Kompress compression to messages (Transform interface)."""
policy = kwargs.get("compression_policy")
record_toin = not (policy is not None and policy.toin_read_only)
tokens_before = sum(tokenizer.count_text(str(m.get("content", ""))) for m in messages)
transformed = []
transforms_applied = []
@@ -2763,7 +2783,7 @@ class KompressCompressor(Transform):
# Compress tool outputs and long assistant messages
# Model decides how much — no hardcoded ratios
if role in ("tool", "assistant"):
result = self.compress(content)
result = self.compress(content, record_toin=record_toin)
if result.compression_ratio < 0.9:
transformed.append({**message, "content": result.compressed})
transforms_applied.append(f"kompress:{role}:{result.compression_ratio:.2f}")
@@ -2781,5 +2801,7 @@ class KompressCompressor(Transform):
transforms_applied=transforms_applied or ["kompress:noop"],
)
def _store_in_ccr(self, original: str, compressed: str, original_tokens: int) -> str | None:
return store_kompress_in_ccr(original, compressed, original_tokens)
def _store_in_ccr(
self, original: str, compressed: str, original_tokens: int, *, record_toin: bool = True
) -> str | None:
return store_kompress_in_ccr(original, compressed, original_tokens, record_toin=record_toin)
+6 -1
View File
@@ -226,6 +226,7 @@ class RemoteKompressCompressor:
*,
allow_download: bool = True,
ccr_original: str | None = None,
record_toin: bool = True,
_time_budget_cap_seconds: float | None = None,
) -> KompressResult:
"""Compress via the remote endpoint.
@@ -253,6 +254,9 @@ class RemoteKompressCompressor:
which ContentRouter caught with a broad ``except Exception`` and logged
as ``Kompress failed: ...``. Compression silently degraded to zero on the
whole deployment while the proxy kept reporting success.
``record_toin`` mirrors the local compressor: False keeps the CCR
store write but skips the TOIN observation for this call.
"""
n_words = len(content.split())
# Same floor contract as the in-process compressor: lossy
@@ -327,7 +331,8 @@ class RemoteKompressCompressor:
ccr_source_tokens = (
len(ccr_source.split()) if ccr_original is not None else result.original_tokens
)
cache_key = store_kompress_in_ccr(ccr_source, compressed, ccr_source_tokens)
gate: dict[str, bool] = {} if record_toin else {"record_toin": False}
cache_key = store_kompress_in_ccr(ccr_source, compressed, ccr_source_tokens, **gate)
if cache_key:
# Report the source line span so a reader can tell content was
# compressed away rather than absent (#2586).
@@ -75,8 +75,16 @@ _HEADING_ROW_RE = re.compile(r"^(?P<line>\d+):(?P<content>.*)$")
_TIMESTAMP_ROW_RE = re.compile(
r"^\s*\[?(?:"
r"\d{4}-\d{2}-\d{2}[ T]\d{1,2}:\d{2}" # 2026-09-02 14:30 / ISO 8601 'T'
r"|\d{4}/\d{2}/\d{2}[ T]\d{1,2}:\d{2}" # Go log, nginx error log: 2026/09/02 14:30
r"|\d{2}/\d{2}/\d{2,4}[ T]\d{1,2}:\d{2}" # 09/02/2026 14:30
r"|[A-Z][a-z]{2}\s+\d{1,2}\s+\d{1,2}:\d{2}" # syslog: Aug 16 11:02
r"|[IWEF]\d{4}\s+\d{1,2}:\d{2}" # klog/glog: E0902 14:30
# Common/combined access log: 10.0.0.7 - - [02/Sep/2026:14:30:00. The
# fields hold no ':', so a `grep -n` row (`path:12:10.0.0.7 - - [...`) is
# not claimed. The host takes name/IPv4 characters only, capped at 255
# (DNS names are at most 253), so a grep row's path or a long unbroken
# line is not scanned to its end.
r"|[\w.-]{1,255} [^\s:]+ [^\s:]+ \[\d{2}/[A-Z][a-z]{2}/\d{4}:\d{2}:\d{2}"
r"|\d{1,2}:\d{2}:\d{2}(?:[.,]\d+)?(?:\s|\]|$)" # bare 15:03:53 / [15:03:53]
r")"
)
+182 -15
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import re
from bisect import bisect_left, bisect_right
from dataclasses import dataclass
from .content_detector import ContentType, _is_search_result_line
@@ -97,19 +98,14 @@ def _any_nonblank(lines: list[str], start: int, stop: int) -> bool:
def _has_valid_json_block_with_text(content: str) -> bool:
"""Return true when prose or log text wraps a valid JSON block."""
lines = content.split("\n")
# Built only after a scan has run to the end without balancing — see
# _extract_json_block. Content that balances promptly never allocates it and
# so pays nothing for it.
scan_cache: dict[tuple[int, bool, bool], tuple[int, int, bool, bool]] | None = None
blocks = _JsonBlockScanner(lines)
for index, line in enumerate(lines):
if not line.strip().startswith(("[", "{")):
if not _is_json_candidate(line):
continue
json_content, end_index = _extract_json_block(lines, index, cache=scan_cache)
json_content, end_index = blocks.extract(index)
if json_content is None:
if scan_cache is None:
scan_cache = {}
continue
try:
@@ -141,7 +137,7 @@ def split_into_sections(content: str, *, isolate: tuple[str, ...] = ()) -> list[
def _carries_isolate(text: str) -> bool:
return any(marker in text for marker in isolate)
scan_cache: dict[tuple[int, bool, bool], tuple[int, int, bool, bool]] | None = None
blocks = _JsonBlockScanner(lines)
i = 0
while i < len(lines):
@@ -183,12 +179,8 @@ def split_into_sections(content: str, *, isolate: tuple[str, ...] = ()) -> list[
i += 1
continue
if line.strip().startswith(("[", "{")):
json_content, end_i = _extract_json_block(lines, i, cache=scan_cache)
if json_content is None and scan_cache is None:
# First scan that ran to the end without balancing: from here on
# every later candidate would re-walk the same tail.
scan_cache = {}
if _is_json_candidate(line):
json_content, end_i = blocks.extract(i)
if json_content is not None:
# Bracket balance alone is not JSON: prose like a harness
# sanitizer banner ("[harness: ... you.]") balances on one
@@ -336,6 +328,181 @@ def _scan_line(line: str, in_string: bool, escaped: bool) -> tuple[int, int, boo
return bracket, brace, in_string, escaped
def _is_json_candidate(line: str) -> bool:
return line.strip().startswith(("[", "{"))
class _JsonBlockScanner:
"""Answers :func:`_extract_json_block` for every candidate of one pass.
Each candidate walks forward until its running bracket and brace counts
are both <= 0. Walked one by one, N candidates that balance late or never
cost N^2/2 line steps. The scanner walks them directly until they have
walked as many lines as the content has, then answers all the rest at
once, with exactly the same results:
* A walk is a chain of (line, string state) nodes, and each node has one
successor, so the walks of all candidates form a forest whose roots are
past the last line. Every node is scanned once, however many walks
share it (walks that start in different string states and later fall
into the same state merge).
* With ``D(v)`` the counts summed from node ``v`` to the end of its
chain, a walk from ``u`` balances at ``w`` exactly when
``D(next(w)) >= D(u)`` in both counts. So a candidate ends just before
its nearest ancestor ``z`` with ``D(z) >= D(u)``.
* One depth-first pass from the root keeps, over the ancestors of the
current node, a tree keyed by bracket sum whose nodes hold stacks of
(brace sum, depth); stacks are updated by overwrite-and-undo so leaving
a node restores them. Each query and each push costs O(log^2 n).
"""
def __init__(self, lines: list[str]) -> None:
self._lines = lines
self._direct_steps_left = len(lines)
# Candidate line -> last line of its block (None: never balances).
self._ends: dict[int, int | None] | None = None
def extract(self, start: int) -> tuple[str | None, int]:
if self._direct_steps_left > 0:
json_content, end = _extract_json_block(self._lines, start)
walked = (end if json_content is not None else len(self._lines) - 1) - start + 1
self._direct_steps_left -= walked
return json_content, end
if self._ends is None:
self._ends = self._solve()
end_line = self._ends.get(start)
if end_line is None:
return None, start
return "\n".join(self._lines[start : end_line + 1]), end_line
def _solve(self) -> dict[int, int | None]:
lines = self._lines
n = len(lines)
candidates = [i for i, line in enumerate(lines) if _is_json_candidate(line)]
# Build the forest: node ids in creation order, one per (line, state).
node_of: dict[tuple[int, bool, bool], int] = {}
node_line: list[int] = []
d_bracket: list[int] = []
d_brace: list[int] = []
succ: list[int] = [] # -1: past the last line (the root)
start_node: dict[int, int] = {}
for s in candidates:
key = (s, False, False)
prev = -1
while key[0] < n:
found = node_of.get(key)
if found is not None:
if prev >= 0:
succ[prev] = found
break
b, c, in_string, escaped = _scan_line(lines[key[0]], key[1], key[2])
v = len(node_line)
node_of[key] = v
node_line.append(key[0])
d_bracket.append(b)
d_brace.append(c)
succ.append(-1)
if prev >= 0:
succ[prev] = v
prev = v
key = (key[0] + 1, in_string, escaped)
start_node[s] = node_of[(s, False, False)]
# Suffix sums D, children lists (successors have larger lines).
count = len(node_line)
sum_b = [0] * count
sum_c = [0] * count
children: list[list[int]] = [[] for _ in range(count)]
roots: list[int] = []
for v in sorted(range(count), key=node_line.__getitem__, reverse=True):
nxt = succ[v]
if nxt < 0:
sum_b[v], sum_c[v] = d_bracket[v], d_brace[v]
roots.append(v)
else:
sum_b[v], sum_c[v] = d_bracket[v] + sum_b[nxt], d_brace[v] + sum_c[nxt]
children[nxt].append(v)
is_query = {start_node[s] for s in candidates}
# Tree over bracket sums; each tree node stacks ancestors as
# (-brace sum, depth) with -brace increasing toward the top.
coords = sorted({0, *sum_b})
size = 1
while size < len(coords):
size *= 2
neg_c: list[list[int]] = [[] for _ in range(2 * size)]
depth_of: list[list[int]] = [[] for _ in range(2 * size)]
used = [0] * (2 * size)
def push(bracket: int, brace: int, depth: int) -> list[tuple[int, int, int, int, int]]:
undo = []
node = bisect_left(coords, bracket) + size
while node:
stack_c, stack_d, top = neg_c[node], depth_of[node], used[node]
# Entries with brace <= this one are shallower: drop them.
pos = bisect_left(stack_c, -brace, 0, top)
if pos < len(stack_c):
undo.append((node, top, pos, stack_c[pos], stack_d[pos]))
stack_c[pos], stack_d[pos] = -brace, depth
else:
undo.append((node, top, pos, 0, -1))
stack_c.append(-brace)
stack_d.append(depth)
used[node] = pos + 1
node //= 2
return undo
def pop(undo: list[tuple[int, int, int, int, int]]) -> None:
for node, top, pos, old_c, old_d in reversed(undo):
if old_d < 0:
neg_c[node].pop()
depth_of[node].pop()
else:
neg_c[node][pos], depth_of[node][pos] = old_c, old_d
used[node] = top
def deepest(bracket: int, brace: int) -> int:
# Deepest ancestor with bracket sum >= bracket and brace sum >= brace.
best = -1
lo, hi = bisect_left(coords, bracket) + size, 2 * size
while lo < hi:
for node in ((lo,) if lo & 1 else ()) + ((hi - 1,) if hi & 1 else ()):
idx = bisect_right(neg_c[node], -brace, 0, used[node]) - 1
if idx >= 0 and depth_of[node][idx] > best:
best = depth_of[node][idx]
lo = (lo + 1) // 2
hi //= 2
return best
ends: dict[int, int | None] = {}
path: list[int] = [-1] # path[d]: ancestor at depth d; depth 0 is the root
root_undo = push(0, 0, 0)
# Iterative DFS: (node, undo record or None when entering).
work: list[tuple[int, list[tuple[int, int, int, int, int]] | None]] = [
(v, None) for v in roots
]
while work:
v, undo = work.pop()
if undo is not None:
pop(undo)
path.pop()
continue
depth = len(path)
if v in is_query:
z = deepest(sum_b[v], sum_c[v])
if z < 0:
ends[node_line[v]] = None
else:
w = path[z + 1] if z + 1 < depth else v
ends[node_line[v]] = node_line[w]
path.append(v)
work.append((v, push(sum_b[v], sum_c[v], depth)))
work.extend((child, None) for child in children[v])
pop(root_undo)
return ends
def _extract_json_block(
lines: list[str],
start: int,
+4 -3
View File
@@ -314,7 +314,7 @@ export function restoreAgentMessages(
} else if (sameWireMessage(before, message)) {
result.push(normalizeAgentMessage(original));
} else {
result.push(applyCompressedMessage(original, message));
result.push(applyCompressedMessage(original, before, message));
}
}
return result;
@@ -341,12 +341,13 @@ function sameWireMessage(a: OpenAIMessage, b: OpenAIMessage): boolean {
);
}
function applyCompressedMessage(original: any, compressed: OpenAIMessage): any {
function applyCompressedMessage(original: any, sent: OpenAIMessage, compressed: OpenAIMessage): any {
const base = normalizeAgentMessage(original);
const text = typeof compressed.content === "string" ? compressed.content : "";
if (base.role === "assistant") {
let content = replaceTextBlocks(base.content, text);
let content =
sent.content === compressed.content ? base.content : replaceTextBlocks(base.content, text);
if (Array.isArray(compressed.tool_calls)) {
content = content.map((block: any) => withCompressedArguments(block, compressed.tool_calls!));
}
@@ -162,7 +162,7 @@ describe("assemble() keeps the provider prompt cache", () => {
expect(messages[0]).toMatchObject({ role: "user", content: "[3 earlier messages omitted]" });
});
it("applies compressed tool-call arguments without dropping the assistant's thinking", async () => {
it("applies compressed tool-call arguments without moving unchanged text blocks", async () => {
mocked.compress.mockImplementation(async (messages: any[]) => ({
...compressToolResults(messages),
messages: messages.map((m) =>
@@ -172,10 +172,16 @@ describe("assemble() keeps the provider prompt cache", () => {
),
}));
const { messages } = await engine().assemble({ sessionId: "s", messages: history() });
const input = history();
input[1].content.push({ type: "text", text: "Waiting for the result." });
const { messages } = await engine().assemble({ sessionId: "s", messages: input });
expect(messages[1].content.map((b: any) => b.type)).toEqual(["thinking", "text", "toolCall"]);
expect(messages[1].content[2].arguments).toEqual({ command: "kubectl get pods" });
expect(messages[1].content).toEqual([
{ type: "thinking", thinking: "run kubectl", thinkingSignature: "sig-1" },
{ type: "text", text: "Running it." },
{ type: "toolCall", id: "t1", name: "exec", arguments: { command: "kubectl get pods" } },
{ type: "text", text: "Waiting for the result." },
]);
});
it("never leaks its bookkeeping into the messages it returns", async () => {
+24
View File
@@ -110,6 +110,30 @@ def _skip_proxy_port_preflight_unless_exercised(
monkeypatch.setattr(proxy, "_refuse_busy_port", lambda *args, **kwargs: None)
# Credentials the Copilot code reads from the environment (copilot_quota.py,
# copilot_auth.py). Any test that enters the proxy lifespan starts the Copilot
# quota poller, which sends such a token to api.github.com; a developer's real
# GITHUB_TOKEN must never be used by a test. A test that needs one sets it with
# monkeypatch.setenv, which runs after this fixture.
_COPILOT_TOKEN_ENV_VARS = (
"GITHUB_COPILOT_GITHUB_TOKEN",
"GITHUB_COPILOT_TOKEN",
"COPILOT_GITHUB_TOKEN",
"GITHUB_COPILOT_API_TOKEN",
"GITHUB_COPILOT_API_TOKEN_EXPIRES_AT",
"GITHUB_COPILOT_REFRESH_OAUTH_TOKEN",
"COPILOT_PROVIDER_BEARER_TOKEN",
"GH_TOKEN",
"GITHUB_TOKEN",
)
@pytest.fixture(autouse=True)
def _scrub_developer_copilot_tokens(monkeypatch):
for key in _COPILOT_TOKEN_ENV_VARS:
monkeypatch.delenv(key, raising=False)
@pytest.fixture(autouse=True)
def _scrub_developer_headroom_env(monkeypatch, tmp_path, tmp_path_factory):
for key in list(os.environ):
+18
View File
@@ -151,6 +151,24 @@ def test_source_output_from_search_command_untouched(tokenizer):
assert out == CODE
GO_LOG = "".join(
f"2026/09/02 14:{30 + i // 60:02d}:{i % 60:02d} ERROR handler: upstream timeout req={i}\n"
for i in range(40)
)
@pytest.mark.parametrize("command", ["grep ERROR /var/log/api.log", "cat /var/log/api.log"])
def test_go_log_keeps_its_timestamps(command, tokenizer):
# Split as path:line:content, `2026/09/02 14:30:00 ...` would fold into a
# `2026/09/02 14` header over `30:00 ...` rows. `cat` reaches the search
# fold through the router's lossless-first stage, `grep` through the
# bash-search fold.
out, transforms = _anthropic(command, GO_LOG, tokenizer)
assert "router:bash:lossless_search" not in transforms
assert "router:tool_result:lossless_search" not in transforms
assert "2026/09/02 14" not in out.split("\n")
# ---- path-listing fold (find/ls -1/rg -l): fold repeated parent dirs ----
from headroom.transforms.lossless_compaction import (
compact_lossless as _cl,
+253
View File
@@ -12,7 +12,9 @@ from __future__ import annotations
import gzip
import json
import os
import re
import time
from pathlib import Path
from typing import Any
@@ -84,6 +86,10 @@ V2_TOP = {
"errors",
"strata",
"config",
"client_usage",
"model_usage",
"client_versions",
"install",
}
@@ -135,11 +141,13 @@ def _clean_staging():
S._staged_stacks.clear()
S._staged_shapes.clear()
S._staged_tool_shapes.clear()
S._staged_client_versions.clear()
yield
S._staged_strategies.clear()
S._staged_stacks.clear()
S._staged_shapes.clear()
S._staged_tool_shapes.clear()
S._staged_client_versions.clear()
@pytest.fixture
@@ -900,7 +908,252 @@ def test_the_worst_case_body_actually_sent_fits_the_oldest_receiver():
for index in range(600)
]
payload = emit(*outcomes)
# The usage tables and versions cannot be shed, so fill them to their caps
# with nine-digit counters: the body must still fit.
big = dict.fromkeys(S._USAGE_FIELDS, 987_654_321)
names = sorted(S._KNOWN_CLIENTS)
payload["client_usage"] = [{"client": names[i], **big} for i in range(S.MAX_USAGE_ROWS + 1)]
payload["model_usage"] = [
{"model": f"claude-opus-4-8-2026010{i}", **big} for i in range(S.MAX_USAGE_ROWS + 1)
]
payload["client_versions"] = [
{"client": names[i % len(names)], "version": f"1234.1234.{1000 + i}", "n": 987_654_321}
for i in range(S.MAX_CLIENT_VERSIONS)
]
saved = payload["tokens"]["saved"]
sent = S._fit_to_wire(payload, S.resource_attributes(), compress=False)
assert len(sent) <= 64 * 1024, f"sent {len(sent):,} B, over the 64KB receiver cap"
assert payload["tokens"]["saved"] == saved, "trimming cost a v1 counter"
# ---------------------------------------------------------------------------
# usage by harness and model, harness versions, install facts, daily rollover
# ---------------------------------------------------------------------------
def test_usage_tables_split_the_session_totals_without_residue():
"""`client_usage` and `model_usage` exist to divide a mixed session, so each
must add back up to the session: every turn lands in exactly one row,
including the turns no harness claimed."""
class Codex(Outcome):
client = "codex"
model = "gpt-4o-mini"
tags = {"tool_search_deferred_tokens": 70}
class Gateway(Outcome):
client = None
provider = "compress"
model = "ft:gpt-4o:acme-corp:internal-bot:abc123"
class Anonymous(Outcome):
client = None
payload = emit(Outcome(), Outcome(), Codex(), Gateway(), Anonymous())
by_client = {r["client"]: r for r in payload["client_usage"]}
assert {name: r["n"] for name, r in by_client.items()} == {
"claude_code": 2,
"codex": 1,
"via_compress_api": 1,
"unidentified": 1,
}
assert by_client["codex"]["tool_saved"] == 70
for table in ("client_usage", "model_usage"):
rows = payload[table]
assert sum(r["n"] for r in rows) == payload["session"]["turns"], table
for column, total in (
("original", "original"),
("saved", "saved"),
("tool_saved", "tool_saved"),
("output", "output"),
("cache_read", "cache_read"),
("cache_write", "cache_write"),
("uncached", "uncached"),
):
assert sum(r[column] for r in rows) == payload["tokens"][total], (table, column)
assert sum(r["cache_write_5m"] for r in rows) == payload["cache"]["write_5m"], table
assert sum(r["cache_write_1h"] for r in rows) == payload["cache"]["write_1h"], table
# A fine-tune id carries an org name: pooled, never sent.
assert "acme" not in json.dumps(payload)
assert {r["model"] for r in payload["model_usage"]} == {"gpt-4o", "gpt-4o-mini", "other"}
def test_a_usage_row_prices_inferred_cache_writes_the_way_the_cost_tracker_does():
"""Where a provider reports no write count, Headroom infers one as input
minus cached. Those are the same tokens as `uncached` and are never billed
as a write, so a row has to say how much of its `cache_write` is inferred
or a reader double-counts them: 1000 billed tokens would price as 2000."""
class InferredWrite(Outcome):
provider = "openai"
model = "gpt-4o"
provider_input_tokens = 1000
cache_read_tokens = 0
cache_write_tokens = 1000
cache_write_5m_tokens = 0
cache_write_1h_tokens = 0
uncached_input_tokens = 1000
cache_inferred = True
class ReportedWrite(Outcome):
model = "gpt-4o-mini" # cache_write 100 = 80 at 5m + 20 at 1h, all billed
def billed_input(row: dict[str, Any]) -> int:
return (
row["uncached"] + row["cache_read"] + row["cache_write"] - row["cache_write_inferred"]
)
rows = {r["model"]: r for r in emit(InferredWrite(), ReportedWrite())["model_usage"]}
assert billed_input(rows["gpt-4o"]) == 1000
assert rows["gpt-4o"]["cache_write_inferred"] == 1000
assert billed_input(rows["gpt-4o-mini"]) == 400 + 500 + 100
assert (rows["gpt-4o-mini"]["cache_write_5m"], rows["gpt-4o-mini"]["cache_write_1h"]) == (
80,
20,
)
def test_an_mcp_turn_is_labelled_not_dropped():
payload = emit(
S._McpCompression(
original_tokens=800, attempted_input_tokens=800, optimized_tokens=200, tokens_saved=600
),
source="mcp",
)
assert [(r["client"], r["n"], r["saved"]) for r in payload["client_usage"]] == [
("via_mcp", 1, 600)
]
def test_usage_tables_pool_overflow_instead_of_losing_turns():
table: dict[str, list[int]] = {}
for index in range(S.MAX_USAGE_ROWS + 9):
S._add_usage(table, f"model{index}", (1, 10))
assert len(table) == S.MAX_USAGE_ROWS + 1
assert table["other"] == [9, 90]
assert sum(row[0] for row in table.values()) == S.MAX_USAGE_ROWS + 9
def test_a_caller_supplied_client_name_never_reaches_the_usage_tables(beacon_on):
"""`classify_client` returns the caller's `X-Client` header as typed, so the
name is checked against a closed list, not just for shape."""
class Named(Outcome):
client = "acme-corp-billing"
S.record_client_version("acme-corp-billing", "1.2.3")
payload = emit(Named(), Outcome())
assert [(r["client"], r["n"]) for r in payload["client_usage"]] == [
("claude_code", 1),
("other", 1),
]
assert payload["client_versions"] == []
def test_the_known_client_list_covers_every_harness_the_proxy_can_name():
from headroom.proxy.auth_policy import CLIENT_UA_MAP
from headroom.telemetry.context import _KNOWN_WRAP_AGENTS
named = {S._client_slug(name) for _, name in CLIENT_UA_MAP} | set(_KNOWN_WRAP_AGENTS)
assert named <= S._KNOWN_CLIENTS, sorted(named - S._KNOWN_CLIENTS)
@pytest.mark.parametrize(
("user_agent", "expected"),
[
("claude-cli/2.1.311 (external, cli)", ("claude-code", "2.1.311")),
("Corp-Wrapper/9 codex-cli/0.45.0-alpha.3", ("codex", "0.45.0")),
("claude-cli/dev-build", None),
("curl/8.4.0", None),
# Over-long or four-part numbers are not releases; never cut one down.
("claude-cli/20261115", None),
("claude-cli/1.2.3456789", None),
("claude-cli/10.0.3.7", None),
],
)
def test_user_agent_version_parser(user_agent, expected):
from headroom.proxy.auth_policy import client_version_from_user_agent
assert client_version_from_user_agent(user_agent) == expected
def test_only_a_numeric_release_of_a_known_harness_is_staged(beacon_on):
S.record_client_version("claude-code", "2.1.311")
S.record_client_version("claude-code", "2.1.311")
S.record_client_version("claude-code", "2.1.311-internal.example.com")
payload = emit(Outcome())
assert payload["client_versions"] == [{"client": "claude_code", "version": "2.1.311", "n": 2}]
def test_install_facts_report_age_and_ephemerality(tmp_path, monkeypatch):
id_file = tmp_path / "install_id"
id_file.write_text("a" * 32)
ten_days_ago = time.time() - 10 * 86400 - 60
os.utime(id_file, (ten_days_ago, ten_days_ago))
monkeypatch.setattr(S, "_install_id_path", lambda: id_file)
monkeypatch.delenv("HEADROOM_STATELESS", raising=False)
monkeypatch.setenv("CI", "true")
facts = emit(Outcome())["install"]
assert facts["age_days"] == 10 and facts["ci"] is True
assert set(facts) == {"age_days", "container", "ci"}
# Stateless: the id is random per process, so there is no age to report.
monkeypatch.setenv("HEADROOM_STATELESS", "1")
facts = emit(Outcome())["install"]
assert facts["age_days"] == 0
def test_a_long_running_session_is_closed_at_the_utc_day_boundary():
"""An always-on proxy never idles, so its session used to grow for weeks.
It now ends at the day boundary; a session that merely runs past midnight
is left whole."""
day = 86400.0
rows: list[dict[str, Any]] = []
agg = S.SessionAggregator(rows.append, idle_s=10 * day, flush_s=100 * day)
start = 20 * day + 3600.0 # 01:00 UTC
agg.record(Outcome(), now=start)
agg.record(Outcome(), now=start + 22 * 3600.0) # 23:00, same day
assert rows == []
agg.record(Outcome(), now=21 * day + 5.0) # just past midnight, 23h old
assert [(r["session"]["ended"], r["session"]["turns"]) for r in rows] == [("rollover", 2)]
agg.record(Outcome(), now=22 * day + 5.0) # the next piece closes a day later
assert [r["session"]["ended"] for r in rows] == ["rollover", "rollover"]
assert rows[0]["session"]["id"] != rows[1]["session"]["id"]
# A clock that steps backwards must not close anything.
agg.record(Outcome(), now=21 * day + 5.0)
assert len(rows) == 2
# Started at 20:00 UTC and still going at 01:00: five hours old, untouched.
rows.clear()
evening = S.SessionAggregator(rows.append, idle_s=10 * day, flush_s=100 * day)
evening.record(Outcome(), now=30 * day + 20 * 3600.0)
evening.record(Outcome(), now=31 * day + 3600.0)
assert rows == []
def test_the_proxy_reports_the_harness_release_it_was_called_by(beacon_on):
"""The wiring, end to end: a real request's User-Agent reaches the payload
as a harness and a release, and nothing else from the header does."""
from tests.test_header_isolation import _make_anthropic_app
client, _ = _make_anthropic_app()
response = client.post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"user-agent": "claude-cli/2.1.311 (external, cli) host-a.internal",
},
json={
"model": "claude-sonnet-4-6",
"max_tokens": 16,
"messages": [{"role": "user", "content": "hi"}],
},
)
assert response.status_code == 200, response.text
rows: list[dict[str, Any]] = []
S.get_session_aggregator().flush_all(emit=rows.append)
assert rows[-1]["client_versions"] == [{"client": "claude_code", "version": "2.1.311", "n": 1}]
assert rows[-1]["client_usage"][0]["client"] == "claude_code"
assert "host-a" not in json.dumps(rows[-1])
+6 -4
View File
@@ -135,7 +135,7 @@ class TestCacheReplayShapes(unittest.TestCase):
)
self.assertEqual(prep.frozen_message_count, min(confirmed, 1))
def test_cached_text_after_textless_anthropic_result_remains_mutable(self) -> None:
def test_cached_text_after_textless_anthropic_result_is_replayed(self) -> None:
messages = [
{
"role": "user",
@@ -148,10 +148,12 @@ class TestCacheReplayShapes(unittest.TestCase):
]
before = copy.deepcopy(messages)
prep = prepare_turn(self.cache, messages, policy=FREEZE_POLICY_REPLAYABLE)
self.assertEqual(prep.frozen_message_count, 0)
self.assertEqual(prep.pipeline_input, before)
self.assertEqual(prep.frozen_message_count, 1)
expected = copy.deepcopy(before)
expected[0]["content"][1]["content"] = "short"
self.assertEqual(prep.pipeline_input, expected)
self.assertEqual(messages, before)
self.assertEqual(self.cache.get_stats()["hits"], 0)
self.assertEqual(self.cache.get_stats()["hits"], 1)
def test_supported_stable_hash_and_trailing_live_zone_are_unchanged(self) -> None:
cache = CompressionCache()
+21
View File
@@ -44,6 +44,11 @@ def test_wrap_vscode_configures_actual_port_and_seeds_subscription(tmp_path: Pat
assert "http://127.0.0.1:9999/" in settings
assert "model" not in settings.lower()
assert "normal model picker" in result.output
# Chats on the Copilot harness never reach the proxy, and a chat keeps the
# engine it started with, so the user has to be told to start a new one.
assert "Local harness" in result.output
assert "start a new chat" in result.output
assert "Warning" not in result.output
assert captured["openai_api_url"] == "https://api.githubcopilot.com"
assert captured["copilot_api_token"] == "copilot-token"
@@ -120,6 +125,20 @@ def test_wrap_vscode_checks_the_profiles_of_the_user_dir_it_configures(
assert "Work" not in output
def test_wrap_vscode_warns_when_the_user_opted_into_the_copilot_harness(tmp_path: Path) -> None:
path = tmp_path / "settings.json"
path.write_text('{\n "chat.editor.preferCopilotHarness": true\n}\n', encoding="utf-8")
output = _run_wrap_vscode("--settings-file", str(path))
# The wrap still succeeds and keeps the user's choice, but says what it costs.
assert '"chat.editor.preferCopilotHarness": true' in output
assert "bypass Headroom" in output
assert "chat.defaultToCopilotHarness" not in output
assert "stay on VS Code's Local harness" not in output
assert path.read_text(encoding="utf-8").count("preferCopilotHarness") == 1
def test_wrap_vscode_no_configure_prints_transparent_settings(tmp_path: Path) -> None:
path = tmp_path / "settings.json"
@@ -141,6 +160,8 @@ def test_wrap_vscode_no_configure_prints_transparent_settings(tmp_path: Path) ->
assert not path.exists()
assert "overrideProxyUrl" in result.output
assert "overrideCapiUrl" in result.output
assert '"chat.defaultToCopilotHarness": false' in result.output
assert '"chat.editor.preferCopilotHarness": false' in result.output
# No `overrideAuthType`: the setting does not exist in the modern Copilot
# Chat extension, so printing it told users to add a key VS Code flags as
# unknown and which does nothing (#3076).
+89 -7
View File
@@ -58,22 +58,49 @@ def test_disabled_kompress_turns_off_code_aware_fallback() -> None:
assert compressor.config.fallback_to_kompress is False
def test_enabled_kompress_keeps_code_aware_fallback() -> None:
def test_enabled_kompress_still_turns_off_code_aware_fallback() -> None:
# Kompress may be on for prose, but it must never compress code (#4214):
# the router's code compressor leaves blocks it cannot handle unchanged.
router = ContentRouter(ContentRouterConfig(enable_code_aware=True))
compressor = router._get_code_compressor()
assert compressor is not None
assert compressor.config.fallback_to_kompress is True
assert compressor.config.fallback_to_kompress is False
def test_unknown_language_code_passes_through_without_kompress(
kompress_spies: tuple[MagicMock, MagicMock],
) -> None:
assert detect_language(UNKNOWN_CODE)[0] == CodeLanguage.UNKNOWN
router = ContentRouter(ContentRouterConfig(enable_code_aware=True, enable_kompress=False))
PERL_CODE = "\n".join(
["#!/usr/bin/perl", "use strict;", "use warnings;"]
+ [
f'my $v{i} = $ARGV[{i % 3}] // {i}; print "$v{i}\\n" if $v{i} =~ /^\\d+$/;'
for i in range(60)
]
)
PYTHON_CODE = "\n".join(
["import json", ""]
+ [
f"def handler_{i}(event):\n if event.get('k{i}'):\n return json.dumps(event)\n return None\n"
for i in range(40)
]
)
def _code_aware_entry(enable_kompress: bool):
router = ContentRouter(
ContentRouterConfig(enable_code_aware=True, enable_kompress=enable_kompress)
)
entry = router.compressor_registry.get("code_aware")
assert entry is not None
return router, entry
@pytest.mark.parametrize("enable_kompress", [False, True])
def test_unknown_language_code_passes_through_without_kompress(
kompress_spies: tuple[MagicMock, MagicMock], enable_kompress: bool
) -> None:
assert detect_language(UNKNOWN_CODE)[0] == CodeLanguage.UNKNOWN
_, entry = _code_aware_entry(enable_kompress)
out = entry.compress(CompressInput(content=UNKNOWN_CODE, content_type="text/x-code"))
@@ -81,3 +108,58 @@ def test_unknown_language_code_passes_through_without_kompress(
available.assert_not_called()
compressor.assert_not_called()
assert out.content == UNKNOWN_CODE
@pytest.mark.parametrize("enable_kompress", [False, True])
def test_perl_code_passes_through_without_kompress(
kompress_spies: tuple[MagicMock, MagicMock], enable_kompress: bool
) -> None:
# detect_language() reports Perl-dominant code as UNKNOWN on purpose, so the
# Perl branch is reached through an explicit language hint.
_, entry = _code_aware_entry(enable_kompress)
out = entry.compress(
CompressInput(content=PERL_CODE, content_type="text/x-code", config={"language": "perl"})
)
available, compressor = kompress_spies
available.assert_not_called()
compressor.assert_not_called()
assert out.content == PERL_CODE
@pytest.mark.parametrize("enable_kompress", [False, True])
def test_ast_failure_passes_through_without_kompress(
kompress_spies: tuple[MagicMock, MagicMock],
monkeypatch: pytest.MonkeyPatch,
enable_kompress: bool,
) -> None:
router, entry = _code_aware_entry(enable_kompress)
code_compressor = router._get_code_compressor()
assert code_compressor is not None
def _boom(*_args, **_kwargs):
raise RuntimeError("simulated AST failure")
monkeypatch.setattr(code_compressor, "_compress_with_ast", _boom)
out = entry.compress(CompressInput(content=PYTHON_CODE, content_type="text/x-code"))
available, compressor = kompress_spies
available.assert_not_called()
compressor.assert_not_called()
assert out.content == PYTHON_CODE
def test_disk_cache_namespace_includes_the_routing_policy_revision(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# Output cached before #4214 (code sent to Kompress) must not be replayed
# after the fix by a restart with the same version and config.
import headroom.transforms.content_router as cr
config = ContentRouterConfig()
current = cr._config_namespace(config)
monkeypatch.setattr(cr, "_ROUTING_POLICY_REVISION", "earlier-policy")
assert cr._config_namespace(config) != current
+71
View File
@@ -7,6 +7,77 @@ import pytest
from headroom.cache.compression_cache import CompressionCache
def _parallel_results(*contents):
return {
"role": "user",
"content": [
{"type": "tool_result", "tool_use_id": f"tool-{i}", "content": content}
for i, content in enumerate(contents)
],
}
def test_parallel_results_are_all_cached_and_replayed():
import copy
cache = CompressionCache()
original = _parallel_results(
"first original " * 20,
[{"type": "text", "text": "second original " * 20, "cache_control": {"type": "ephemeral"}}],
)
compressed = _parallel_results(
"first compressed",
[{"type": "text", "text": "second compressed", "cache_control": {"type": "ephemeral"}}],
)
untouched = copy.deepcopy(original)
cache.update_from_result([original], [compressed])
assert cache.apply_cached([original]) == [compressed]
assert original == untouched
assert cache.compute_frozen_count([original, {"role": "user", "content": "next"}]) == 1
@pytest.mark.parametrize("first", ["cached", [{"type": "tool_reference", "tool_name": "Read"}]])
def test_a_later_parallel_cache_miss_stops_freezing(first):
cache = CompressionCache()
cache.mark_stable(cache.content_hash("cached"))
original = _parallel_results(first, "not cached")
assert cache.compute_frozen_count([original, {"role": "user", "content": "next"}]) == 0
def test_parallel_results_preserve_textless_blocks_and_cache_later_text():
cache = CompressionCache()
references = [{"type": "tool_reference", "tool_name": "Read"}]
original = _parallel_results(references, "original " * 20)
compressed = _parallel_results(references, "compressed")
cache.update_from_result([original], [compressed])
assert cache.apply_cached([original]) == [compressed]
assert cache.compute_frozen_count([original, {"role": "user", "content": "next"}]) == 1
def test_parallel_replay_does_not_flatten_an_unsupported_later_result():
cache = CompressionCache()
blocks = [{"type": "text", "text": "part one"}, {"type": "text", "text": "part two"}]
original = _parallel_results("original " * 20, blocks)
compressed = _parallel_results("compressed", "part one\npart two")
cache.update_from_result([original], [compressed])
replay = cache.apply_cached([original])[0]
assert replay["content"][0]["content"] == "compressed"
assert replay["content"][1]["content"] == blocks
assert cache.compute_frozen_count([original, {"role": "user", "content": "next"}]) == 0
def test_changed_parallel_result_ids_do_not_seed_the_wrong_result():
cache = CompressionCache()
original = _parallel_results("alpha original", "beta original")
compressed = _parallel_results("alpha compressed", "beta compressed")
compressed["content"].reverse()
cache.update_from_result([original], [compressed])
assert cache.apply_cached([original]) == [original]
@pytest.fixture
def cache() -> CompressionCache:
return CompressionCache()
+201 -1
View File
@@ -5,7 +5,8 @@ auth mode), TOIN must serve cached recommendations but NEVER write new
pattern observations from this request. PAYG / OAuth keep writing so
the network effect keeps growing. The gate is read at the
``record_compression`` call site in ``smart_crusher.py`` and
``content_router.py``.
``content_router.py``, and — since #4801 — at the Kompress CCR store
(``store_kompress_in_ccr``), the second write path of #4474.
These tests mirror the structure of
``tests/test_smart_crusher_toin_attachment.py`` (the F2.1-era TOIN
@@ -339,3 +340,202 @@ def test_smart_crusher_crush_record_toin_false_skips_write(fresh_toin):
crusher.crush(payload)
assert sum(p.total_compressions for p in fresh_toin._patterns.values()) > 0
# ─── Kompress CCR store: record_toin gate (#4801) ────────────────────────
def _toin_total(toin) -> int:
return sum(p.total_compressions for p in toin._patterns.values())
def test_kompress_store_record_toin_false_skips_write(fresh_toin):
"""``store_kompress_in_ccr(record_toin=False)`` keeps the CCR mapping
(the compressed output stays retrievable) but writes no TOIN
observation; the default call writes one."""
from headroom.cache.compression_store import get_compression_store
from headroom.transforms.kompress_compressor import store_kompress_in_ccr
cache_key = store_kompress_in_ccr("word " * 400, "word " * 100, 400, record_toin=False)
assert cache_key is not None
assert get_compression_store().retrieve(cache_key) is not None
assert _toin_total(fresh_toin) == 0
cache_key = store_kompress_in_ccr("other " * 400, "other " * 100, 400)
assert cache_key is not None
assert _toin_total(fresh_toin) == 1
class _FakeEncoding:
def __init__(self, word_lists: list[list[str]]):
self._word_lists = word_lists
self._ids = [[0] * len(w) for w in word_lists]
def __getitem__(self, key: str):
return {"input_ids": self._ids, "attention_mask": self._ids}[key]
def word_ids(self, batch_index: int = 0) -> list[int]:
return list(range(len(self._word_lists[batch_index])))
class _FakeTokenizer:
def __call__(self, words, **_kwargs):
batch = words if (words and isinstance(words[0], list)) else [words]
return _FakeEncoding(batch)
class _FakeModel:
def get_keep_mask(self, input_ids, _attention_mask):
return [[i < 2 for i in range(len(input_ids[0]))]]
def get_scores(self, input_ids, _attention_mask):
return [[1.0 if i < 2 else 0.0 for i in range(len(row))] for row in input_ids]
def _local_compressor(monkeypatch):
from headroom.transforms.kompress_compressor import KompressCompressor
monkeypatch.setattr(
"headroom.transforms.kompress_compressor._load_kompress",
lambda *a, **k: (_FakeModel(), _FakeTokenizer(), "onnx"),
)
return KompressCompressor()
def test_kompress_compressor_record_toin_false_skips_write(fresh_toin, monkeypatch):
"""The local compressor forwards the gate to the CCR store: gated
compression still returns a retrieval key but records nothing."""
compressor = _local_compressor(monkeypatch)
content = "line one\nline two\nline three " * 20
gated = compressor.compress(content, record_toin=False)
assert gated.cache_key is not None
assert _toin_total(fresh_toin) == 0
compressor.compress(content)
assert _toin_total(fresh_toin) == 1
def test_kompress_compress_batch_record_toin_false_skips_write(fresh_toin, monkeypatch):
"""The batch path (which reconstructs and stores separately) honours
the gate the same way."""
compressor = _local_compressor(monkeypatch)
content = "line one\nline two\nline three " * 20
results = compressor.compress_batch([content], record_toin=False)
assert results[0].cache_key is not None
assert _toin_total(fresh_toin) == 0
def test_kompress_compress_batch_forced_batched_record_toin_false_skips_write(
fresh_toin, monkeypatch
):
"""Forcing the batched path (no sequential fallback) still honours the
gate: its separate CCR store write records nothing when gated."""
compressor = _local_compressor(monkeypatch)
monkeypatch.setattr(compressor, "_should_use_sequential_fallback", lambda: False)
content = "line one\nline two\nline three " * 20
results = compressor.compress_batch([content], record_toin=False)
assert results[0].cache_key is not None
assert _toin_total(fresh_toin) == 0
results = compressor.compress_batch([content])
assert results[0].cache_key is not None
assert _toin_total(fresh_toin) == 1
class _FakeResponse:
def __init__(self, payload: dict) -> None:
self._payload = payload
def raise_for_status(self) -> None:
return None
def json(self) -> dict:
return self._payload
class _FakeClient:
def __init__(self, payload: dict) -> None:
self._payload = payload
def post(self, url, headers=None, json=None): # noqa: A002, ANN001
return _FakeResponse(self._payload)
def close(self) -> None:
return None
def test_remote_kompress_record_toin_false_skips_write(fresh_toin, monkeypatch):
"""The remote client shares the store function, so the same gate
applies on the hosted-endpoint path."""
from headroom.transforms.kompress_remote import RemoteKompressCompressor
compressor = RemoteKompressCompressor("https://ml.example.invalid")
compressor._client = _FakeClient({"compressed": "short", "compression_ratio": 0.2}) # type: ignore[assignment]
compressor.config.enable_ccr = True
compressor.config.min_input_words = 10
content = "real secret block " * 60
gated = compressor.compress(content, record_toin=False)
assert gated.cache_key is not None
assert _toin_total(fresh_toin) == 0
compressor.compress(content)
assert _toin_total(fresh_toin) == 1
@_skip_no_core
def test_content_router_kompress_path_forwards_toin_gate(monkeypatch):
"""The router never calls ``KompressCompressor.apply()``, so it must
forward the request's gate per call, as it does for ``crush()``: the
kwarg is sent only when the policy is read-only."""
from headroom.transforms.content_router import ContentRouter
from headroom.transforms.kompress_compressor import KompressResult
calls: list[dict] = []
class _Stub:
def is_ready(self) -> bool:
return True
def ensure_background_load(self) -> None:
return None
def compress(self, content: str, **kwargs) -> KompressResult:
calls.append(kwargs)
return KompressResult(
compressed="short",
original=content,
original_tokens=100,
compressed_tokens=1,
compression_ratio=0.01,
)
router = ContentRouter()
monkeypatch.setattr(router, "_get_kompress", lambda: _Stub())
content = "plain prose about workers processing batches steadily " * 20
router._runtime_compression_policy = policy_for_mode(AuthMode.SUBSCRIPTION)
router._try_ml_compressor(content, "")
assert calls[-1].get("record_toin") is False
router._runtime_compression_policy = policy_for_mode(AuthMode.PAYG)
router._try_ml_compressor(content, "")
assert "record_toin" not in calls[-1]
def test_kompress_apply_subscription_policy_skips_write(fresh_toin, monkeypatch):
"""Through the Transform interface, a Subscription policy reaches
``compress()`` as the gate; no policy keeps the legacy write."""
compressor = _local_compressor(monkeypatch)
content = "line one\nline two\nline three " * 20
messages = [{"role": "tool", "content": content, "tool_call_id": "t1"}]
policy = policy_for_mode(AuthMode.SUBSCRIPTION)
compressor.apply(messages, _tokenizer(), compression_policy=policy)
assert _toin_total(fresh_toin) == 0
compressor.apply(messages, _tokenizer())
assert _toin_total(fresh_toin) == 1
@@ -0,0 +1,35 @@
"""A developer's GitHub/Copilot token in the shell must not reach any test.
The Copilot quota poller reads these variables and sends the token to
api.github.com, so ``tests/conftest.py`` removes them for every test.
"""
from __future__ import annotations
import os
import pytest
from headroom.subscription.copilot_quota import discover_github_token
TOKEN_VARS = (
"GITHUB_COPILOT_GITHUB_TOKEN",
"GITHUB_TOKEN",
"COPILOT_GITHUB_TOKEN",
"GITHUB_COPILOT_API_TOKEN",
"GH_TOKEN",
)
@pytest.mark.parametrize("name", TOKEN_VARS)
def test_developer_token_is_not_visible_to_tests(name: str) -> None:
assert name not in os.environ
def test_the_quota_poller_finds_no_token() -> None:
assert discover_github_token() is None
def test_a_test_can_still_set_its_own_token(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("GITHUB_TOKEN", "test-token")
assert discover_github_token() == "test-token"
+21
View File
@@ -376,6 +376,27 @@ def test_dedup_folds_user_string_read_observation():
assert out[1]["content"] == span
def test_dedup_never_rewrites_nested_cache_control_tool_result():
# Anthropic list-form tool_result whose text sub-block carries the client's
# cache_control marker: the block may already be cached under that key, so
# it is a reference target only. Control: the same block unmarked folds.
span = _readspan()
def tr(tid, text, marked):
sub = {"type": "text", "text": text}
if marked:
sub["cache_control"] = {"type": "ephemeral"}
block = {"type": "tool_result", "tool_use_id": tid, "content": [sub]}
return {"role": "user", "content": [block]}
for marked in (False, True):
msgs = [tr("t1", f"a\n{span}", False), tr("t2", f"b\n{span}", marked)]
later = _dedup_only(msgs)[1]["content"][0]["content"][0]
assert ("[↑" in later["text"]) is not marked
if marked:
assert later == msgs[1]["content"][0]["content"][0]
def test_dedup_does_not_fold_plain_user_prose():
# A duplicated ORDINARY user message (no preceding read command) must stay
# verbatim — user intent is never folded.
+14 -1
View File
@@ -196,7 +196,7 @@ def test_tokens_after_counts_reverted_messages(monkeypatch) -> None:
# `headroom.compress` the attribute is the function; fetch the module.
compress_module = importlib.import_module("headroom.compress")
monkeypatch.setattr(compress_module, "_message_is_lossless", lambda orig, comp: False)
monkeypatch.setattr(compress_module, "_string_pair_is_lossless", lambda orig, comp: False)
msgs = _tool_result_messages(_repeated_path_records())
res = headroom.densify(msgs)
assert res.reverted_messages == 1
@@ -216,3 +216,16 @@ def test_new_fields_do_not_shift_positional_arguments() -> None:
assert config_names[-3:] == ["diagnostics", "mode", "verify_lossless"]
result_names = [f.name for f in fields(CompressResult)]
assert result_names[-3:] == ["diagnostics", "lossless", "reverted_messages"]
def test_lossless_verifier_reverts_equal_valued_scalar_type_changes() -> None:
from headroom.compress import _verify_and_revert
original = {"input": {"enabled": True, "count": 1}, "content": '[{"id":1}]'}
for changed_input in ({"enabled": 1, "count": 1}, {"enabled": True, "count": 1.0}):
for content in (original["content"], "[1]{id:int}\n1\n"):
changed = dict(original, input=changed_input, content=content)
messages, reverted, lossless = _verify_and_revert([original], [changed])
assert reverted == 1
assert messages[0] is original
assert lossless
+138
View File
@@ -6,12 +6,19 @@ every in-flight request. Those are transport errors, so the proxy must retry
them (dropping the bad connection and re-sending on a fresh one) instead of
collapsing to a 502. These tests drive the real `_retry_request` and
`_stream_response` paths.
A corrupt TLS record surfaces as a raw `ssl.SSLError`, not an
`httpx.TransportError`. It is retried only when it hit while the request was
still being written. After the write, upstream may already have accepted and
billed the POST, so the error propagates and the POST is sent once.
"""
from __future__ import annotations
import ssl
from unittest.mock import AsyncMock, MagicMock
import httpcore
import httpx
import pytest
@@ -177,3 +184,134 @@ async def test_successful_stream_still_returns_200():
assert result.status_code == 200
proxy.metrics.record_upstream_connection_error.assert_not_called()
def _bad_record() -> ssl.SSLError:
# What httpx raises on a connection whose next TLS record is corrupt.
return ssl.SSLError(1, "[SSL] record layer failure (_ssl.c:2580)")
_SSE_STOP = b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
_SSE_OK = b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: %d\r\n\r\n%s" % (
len(_SSE_STOP),
_SSE_STOP,
)
class _Upstream(httpcore.AsyncNetworkBackend):
"""Real httpcore over fake sockets: one failure mode per connection.
``"write"``: the TLS error hits while the request is written (never sent).
``"read"``: upstream receives the whole POST, then the TLS error hits.
``None``: a healthy connection that answers with an SSE stream.
"""
def __init__(self, *modes: str | None) -> None:
self.modes = list(modes)
self.received = b""
@property
def posts(self) -> int:
return self.received.count(b"POST /v1/messages")
async def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
return _UpstreamStream(self, self.modes.pop(0))
class _UpstreamStream(httpcore.AsyncNetworkStream):
def __init__(self, upstream: _Upstream, mode: str | None) -> None:
self.upstream, self.mode, self.replied = upstream, mode, False
async def write(self, buffer, timeout=None):
if self.mode == "write":
raise _bad_record()
self.upstream.received += buffer
async def read(self, max_bytes, timeout=None):
if self.mode == "read":
raise _bad_record()
reply, self.replied = (b"" if self.replied else _SSE_OK), True
return reply
async def aclose(self):
pass
async def start_tls(self, ssl_context, server_hostname=None, timeout=None):
return self
def _proxy_over(upstream: _Upstream):
proxy = _mock_proxy()
transport = httpx.AsyncHTTPTransport()
# Same hook upstream_pinning uses: swap the pool's network backend.
transport._pool._network_backend = upstream
proxy.http_client = httpx.AsyncClient(transport=transport)
return proxy
async def _retry_post(proxy):
return await proxy._retry_request(
"POST",
"https://api.anthropic.com/v1/messages",
{"x-api-key": "sk-test"},
{"model": "claude-sonnet-4-20250514", "messages": []},
)
async def test_retry_request_does_not_replay_a_post_upstream_received():
upstream = _Upstream("read", None)
with pytest.raises(ssl.SSLError):
await _retry_post(_proxy_over(upstream))
assert upstream.posts == 1
async def test_retry_request_retries_ssl_error_while_writing_the_request():
upstream = _Upstream("write", None)
result = await _retry_post(_proxy_over(upstream))
assert result.status_code == 200
assert upstream.posts == 1
assert upstream.modes == []
async def test_stream_does_not_replay_a_post_upstream_received():
upstream = _Upstream("read", None)
result = await _run_stream(_proxy_over(upstream))
body = b"".join([chunk async for chunk in result.body_iterator])
assert upstream.posts == 1
assert result.status_code == 502
assert b"upstream_tls_error" in body
async def test_stream_retries_ssl_error_while_writing_the_request():
upstream = _Upstream("write", None)
result = await _run_stream(_proxy_over(upstream))
body = b"".join([chunk async for chunk in result.body_iterator])
assert result.status_code == 200
assert _SSE_STOP in body
assert upstream.posts == 1
assert upstream.modes == []
async def test_ssl_error_without_write_evidence_is_not_retried():
# The review's harness: the transport accepts the POST, then raises. It
# emits no httpcore trace events, so nothing shows the POST went unsent.
seen: list[httpx.Request] = []
def accept_then_fail(request: httpx.Request) -> httpx.Response:
seen.append(request)
raise _bad_record()
proxy = _mock_proxy()
proxy.http_client = httpx.AsyncClient(transport=httpx.MockTransport(accept_then_fail))
with pytest.raises(ssl.SSLError):
await _retry_post(proxy)
assert len(seen) == 1
+49 -1
View File
@@ -24,6 +24,9 @@ def _multi_hour_log() -> str:
return "\n".join(lines)
_LONGEST_HOST = ".".join(["h" * 63] * 3 + ["h" * 61]) # 253 chars, the DNS maximum
@pytest.mark.parametrize(
"sample",
[
@@ -34,13 +37,58 @@ def _multi_hour_log() -> str:
),
"\n".join(f"[15:{m:02d}:53] tool: Bash(cmd {m})" for m in range(60)),
"\n".join(f"2026-09-02T14:{m:02d}:10 [WARN] latency high {m}" for m in range(60)),
"\n".join(f"2026/09/02 14:{m:02d}:10 ERROR upstream timeout req={m}" for m in range(60)),
"\n".join(
f"2026/09/02 14:{m:02d}:10 [error] 31#31: *{m} connect() failed (111: refused)"
for m in range(60)
),
"\n".join(
f"E0902 14:{m:02d}:10.000000 1 reflector.go:{m}] failed to list *v1.Pod"
for m in range(60)
),
"\n".join(
f'10.0.0.7 - - [02/Sep/2026:14:{m:02d}:10 +0000] "GET /items/{m} HTTP/1.1" 500 512'
for m in range(60)
),
"\n".join(
f'{_LONGEST_HOST} - - [02/Sep/2026:14:{m:02d}:10 +0000] "GET /" 200 5'
for m in range(60)
),
],
ids=[
"iso-datetime",
"syslog",
"bracketed-time",
"iso-T",
"go-log",
"nginx-error",
"klog",
"access-log",
"access-log-longest-host",
],
ids=["iso-datetime", "syslog", "bracketed-time", "iso-T"],
)
def test_timestamped_logs_are_never_folded(sample: str) -> None:
assert compact_lossless(sample, "search") == sample
@pytest.mark.parametrize(
("path", "row"),
[
("2026/09/02/api.log", "2026/09/02 14:30:{s:02d} ERROR upstream timeout"),
("logs/nginx/error.log", "2026/09/02 14:30:{s:02d} [error] 31#31: connect() failed"),
("logs/controller.log", "E0902 14:30:{s:02d}.000000 1 reflector.go:100] list failed"),
("/var/log/nginx/access.log", '10.0.0.7 - - [02/Sep/2026:14:30:{s:02d} +0000] "GET /" 500'),
],
ids=["go-log", "nginx-error", "klog", "access-log"],
)
def test_grep_rows_over_those_logs_still_fold(path: str, row: str) -> None:
"""``grep -n`` output starts with the file path, so it is not a log row."""
grep = "\n".join(f"{path}:{i}:{row.format(s=i % 60)}" for i in range(1, 41))
out = compact_lossless(grep, "search")
assert len(out) < len(grep)
assert out.split("\n")[0] == path
def test_fatal_line_keeps_its_full_timestamp() -> None:
out = compact_lossless(_multi_hour_log(), "search")
fatal = [line for line in out.split("\n") if "FATAL" in line]
+104
View File
@@ -0,0 +1,104 @@
"""Reject incompatible embeddings before changing primary or cached memories."""
from unittest.mock import AsyncMock
import numpy as np
import pytest
from headroom.memory.adapters.cache import LRUMemoryCache
from headroom.memory.adapters.hnsw import HNSWVectorIndex
from headroom.memory.adapters.sqlite import SQLiteMemoryStore
from headroom.memory.config import MemoryConfig
from headroom.memory.core import HierarchicalMemory
from headroom.memory.models import Memory
from headroom.memory.ports import MemoryFilter
@pytest.fixture
def components(tmp_path):
store = SQLiteMemoryStore(tmp_path / "memories.db")
vector = HNSWVectorIndex(dimension=4)
text = AsyncMock()
embedder = AsyncMock()
cache = LRUMemoryCache()
memory = HierarchicalMemory(
store, vector, text, embedder, cache, MemoryConfig(auto_bubble=False)
)
return memory, store, vector, text, embedder, cache
@pytest.mark.asyncio
@pytest.mark.parametrize("shape", [(8,), (2, 2), ()])
async def test_add_rejects_incompatible_shape_without_persisting(components, shape):
memory, store, vector, text, embedder, cache = components
embedder.embed.return_value = np.zeros(shape, dtype=np.float32)
with pytest.raises(ValueError):
await memory.add("Must not be half-written", user_id="alice")
assert await store.query(MemoryFilter(user_id="alice")) == []
assert vector.size == 0
text.index_memory.assert_not_called()
assert cache.size == 0
@pytest.mark.asyncio
async def test_batch_validates_every_embedding_before_saving_any_row(components):
memory, store, vector, _, embedder, _ = components
embedder.embed_batch.return_value = [np.ones(4), np.ones(8)]
with pytest.raises(ValueError):
await memory.add_batch(
[
{"content": "Valid first vector", "user_id": "alice"},
{"content": "Invalid second vector", "user_id": "alice"},
]
)
assert await store.query(MemoryFilter(user_id="alice")) == []
assert vector.size == 0
@pytest.mark.asyncio
@pytest.mark.parametrize("operation", ["update", "supersede"])
async def test_rejected_replacement_keeps_the_existing_memory_and_lineage(components, operation):
memory, store, vector, _, embedder, cache = components
embedder.embed.return_value = np.ones(4)
original = await memory.add("Original fact", user_id="alice")
embedder.embed.return_value = np.ones(8)
with pytest.raises(ValueError):
if operation == "update":
await memory.update(
original.id, content="Invalid replacement", metadata={"changed": True}
)
else:
await memory.supersede(original.id, "Invalid replacement")
stored = await store.get(original.id)
assert stored.content == "Original fact"
assert stored.metadata == {}
assert stored.valid_until is None
assert stored.superseded_by is None
assert len(await store.query(MemoryFilter(user_id="alice", include_superseded=True))) == 1
assert (await cache.get(original.id)).content == "Original fact"
assert vector.size == 1
@pytest.mark.asyncio
async def test_failed_update_does_not_mutate_a_reference_returning_store(components):
memory, _, _, _, embedder, _ = components
original = Memory(content="Original", user_id="alice", embedding=np.ones(4))
memory._store = AsyncMock()
memory._store.get.return_value = original
embedder.embed.return_value = np.ones(8)
with pytest.raises(ValueError):
await memory.update(original.id, content="Replacement", metadata={"changed": True})
assert original.content == "Original"
assert original.metadata == {}
memory._store.save.assert_not_awaited()
@pytest.mark.asyncio
async def test_matching_embeddings_and_explicit_no_embedding_still_work(components):
memory, store, vector, _, embedder, _ = components
embedder.embed.return_value = np.ones(4)
with_vector = await memory.add("Indexed fact", user_id="alice")
without_vector = await memory.add("Text-only fact", user_id="alice", auto_embed=False)
assert (await store.get(with_vector.id)).embedding.shape == (4,)
assert (await store.get(without_vector.id)).embedding is None
assert vector.size == 1
+46
View File
@@ -0,0 +1,46 @@
"""A horizontal separator in metadata must not end YAML frontmatter."""
import hashlib
import pytest
from headroom.memory.sync_adapters.claude_code import ClaudeCodeAdapter, _parse_frontmatter
@pytest.mark.parametrize("newline", ["\n", "\r\n"])
def test_embedded_dashes_are_not_a_closing_delimiter(newline):
text = newline.join(["---", "name: foo---bar", "type: project", "---", "", "Original body"])
metadata, body = _parse_frontmatter(text)
assert metadata == {"name": "foo---bar", "type": "project"}
assert body == "Original body"
@pytest.mark.parametrize("opening", ["---not-a-header", "----"])
def test_non_delimiter_opening_preserves_the_original_body(opening):
text = f"{opening}\nname: text\n---\nbody"
assert _parse_frontmatter(text) == ({}, text)
def test_closing_delimiter_must_occupy_the_line():
text = "---\nname: value\n---suffix\ntype: project\n---\nBody\n---\nTail"
metadata, body = _parse_frontmatter(text)
assert metadata == {"name": "value", "type": "project"}
assert body == "Body\n---\nTail"
def test_missing_delimiter_preserves_input():
text = "---\nname: foo---bar\nbody without closing delimiter"
assert _parse_frontmatter(text) == ({}, text)
@pytest.mark.asyncio
async def test_real_adapter_round_trips_dashes_in_generated_metadata(tmp_path):
adapter = ClaudeCodeAdapter(tmp_path / "memory")
content = "Use foo---bar as the separator\nKeep the second line intact."
original_hash = hashlib.sha256(content.encode()).hexdigest()[:16]
assert await adapter.write_memories([{"content": content, "content_hash": original_hash}]) == 1
reread = await adapter.read_memories()
assert len(reread) == 1
assert reread[0].content == content
assert reread[0].content_hash == original_hash
assert await adapter.write_memories([{"content": content, "content_hash": original_hash}]) == 0
+133
View File
@@ -0,0 +1,133 @@
"""The advertised listing tool must reach the scoped backend without a query."""
from datetime import datetime, timedelta
from unittest.mock import AsyncMock
import pytest
from headroom.memory.adapters.sqlite import SQLiteMemoryStore
from headroom.memory.backends.local import LocalBackend, LocalBackendConfig
from headroom.memory.core import HierarchicalMemory
from headroom.memory.models import Memory
from headroom.memory.system import MemorySystem
@pytest.mark.asyncio
@pytest.mark.parametrize("optimized", [False, True])
async def test_advertised_list_tool_dispatches_without_semantic_search(optimized):
backend = AsyncMock()
newest = Memory(id="new", content="Newest fact", user_id="alice")
older = Memory(
id="old",
content="Older fact",
user_id="alice",
created_at=datetime.now() - timedelta(days=1),
)
backend.get_user_memories.return_value = [newest, older]
system = MemorySystem(backend, user_id="alice")
assert "memory_list" in [t["function"]["name"] for t in system.get_tools(optimized)]
result = await system.process_tool_call("memory_list", {})
assert result["success"] is True
assert result["count"] == 2
assert [m["memory_id"] for m in result["memories"]] == ["new", "old"]
assert result["memories"][0]["content"] == "Newest fact"
assert "embedding" not in result["memories"][0]
backend.get_user_memories.assert_awaited_once_with(user_id="alice", limit=10)
backend.search_memories.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.parametrize(("requested", "effective"), [(1, 1), (100, 100), (0, 1), (200, 100)])
async def test_list_limit_matches_the_advertised_bounds(requested, effective):
backend = AsyncMock()
backend.get_user_memories.return_value = []
result = await MemorySystem(backend, "alice").process_tool_call(
"memory_list", {"limit": requested}
)
assert result["success"] is True
assert result["count"] == 0
assert result["memories"] == []
backend.get_user_memories.assert_awaited_once_with(user_id="alice", limit=effective)
@pytest.mark.asyncio
async def test_backend_without_listing_reports_an_unsupported_operation():
result = await MemorySystem(object(), "alice").process_tool_call("memory_list", {})
assert result["success"] is False
assert "does not support listing" in result["error"]
@pytest.mark.asyncio
async def test_list_backend_error_uses_the_tool_error_response():
backend = AsyncMock()
backend.get_user_memories.side_effect = RuntimeError("listing unavailable")
result = await MemorySystem(backend, "alice").process_tool_call("memory_list", {})
assert result["success"] is False
assert result["error"] == "listing unavailable"
@pytest.mark.asyncio
@pytest.mark.parametrize(
("session_id", "expected"),
[("session-a", ["alice-a"]), ("missing", []), ("", []), (None, ["alice-b"])],
)
async def test_listing_applies_user_and_session_scope_before_the_limit(
tmp_path, session_id, expected
):
store = SQLiteMemoryStore(tmp_path / "memories.db")
now = datetime.now()
await store.save_batch(
[
Memory(
id="alice-a",
content="Current session",
user_id="alice",
session_id="session-a",
created_at=now - timedelta(days=3),
),
Memory(
id="alice-global",
content="Unscoped fact",
user_id="alice",
created_at=now - timedelta(days=2),
),
Memory(
id="alice-b",
content="Other session",
user_id="alice",
session_id="session-b",
created_at=now - timedelta(days=1),
),
Memory(
id="bob-a",
content="Other user",
user_id="bob",
session_id="session-a",
created_at=now,
),
]
)
backend = LocalBackend(LocalBackendConfig(db_path=str(tmp_path / "memories.db")))
backend._hierarchical_memory = HierarchicalMemory(store, AsyncMock(), AsyncMock(), AsyncMock())
backend._initialized = True
result = await MemorySystem(backend, "alice", session_id=session_id).process_tool_call(
"memory_list", {"limit": 1}
)
assert result["success"] is True
assert [m["memory_id"] for m in result["memories"]] == expected
@pytest.mark.asyncio
async def test_session_listing_does_not_fall_back_to_a_user_only_backend():
class UserOnlyBackend:
get_user_memories = AsyncMock(return_value=[])
backend = UserOnlyBackend()
result = await MemorySystem(backend, "alice", session_id="session-a").process_tool_call(
"memory_list", {}
)
assert result["success"] is False
assert "does not support listing" in result["error"]
backend.get_user_memories.assert_not_awaited()
+80
View File
@@ -0,0 +1,80 @@
"""Incremental sync must observe edits without new rows or IDs."""
from dataclasses import replace
import numpy as np
import pytest
from headroom.memory.adapters.fts5 import FTS5TextIndex
from headroom.memory.adapters.graph import InMemoryGraphStore
from headroom.memory.adapters.sqlite import SQLiteMemoryStore
from headroom.memory.adapters.sqlite_vector import SQLiteVectorIndex, is_sqlite_vec_available
from headroom.memory.backends.local import LocalBackend
from headroom.memory.config import MemoryConfig
from headroom.memory.core import HierarchicalMemory
from headroom.memory.models import Memory
from headroom.memory.sync import _db_fingerprint, sync
from headroom.memory.sync_adapters.codex_agent import CodexAdapter
class FixedEmbedder:
async def embed(self, text):
return np.array([1.0, 0.0, 0.0], dtype=np.float32)
@pytest.mark.parametrize("position", [0, 6])
def test_fingerprint_observes_content_edits_at_every_position(position):
rows = [Memory(id=f"memory-{i}", content=f"fact {i}", user_id="alice") for i in range(7)]
changed = rows.copy()
changed[position] = replace(rows[position], content="corrected fact")
assert _db_fingerprint(rows) != _db_fingerprint(changed)
def test_fingerprint_uses_complete_ids():
original = Memory(id="12345678-old", content="fact", user_id="alice")
assert _db_fingerprint([original]) != _db_fingerprint([replace(original, id="12345678-new")])
def test_fingerprint_observes_export_eligibility():
original = Memory(content="fact", user_id="alice")
changed = replace(original, metadata={"source_agent": "codex", "sync_direction": "import"})
assert _db_fingerprint([original]) != _db_fingerprint([changed])
def test_fingerprint_stable_for_equivalent_rows():
rows = [Memory(content="fact", user_id="alice")]
assert _db_fingerprint(rows) == _db_fingerprint([replace(rows[0])])
assert _db_fingerprint([]) == _db_fingerprint([])
@pytest.mark.asyncio
@pytest.mark.skipif(not is_sqlite_vec_available(), reason="sqlite-vec unavailable")
async def test_incremental_sync_exports_in_place_sqlite_edit(tmp_path, monkeypatch):
monkeypatch.setenv("HEADROOM_STATELESS", "0")
memory = HierarchicalMemory(
SQLiteMemoryStore(tmp_path / "memory.db"),
SQLiteVectorIndex(dimension=3, db_path=tmp_path / "vectors.db"),
FTS5TextIndex(tmp_path / "fts.db"),
FixedEmbedder(),
config=MemoryConfig(auto_bubble=False, vector_dimension=3),
)
backend = LocalBackend()
backend._hierarchical_memory = memory
backend._graph = InMemoryGraphStore()
backend._initialized = True
adapter = CodexAdapter(tmp_path / "AGENTS.md")
state_path = tmp_path / "state.json"
try:
saved = await memory.add("Original fact", user_id="alice")
first = await sync(backend, adapter, "alice", state_path)
assert first.exported == 1
unchanged = await sync(backend, adapter, "alice", state_path)
assert unchanged.imported == unchanged.exported == 0
await memory.update(saved.id, content="Corrected fact")
updated = await sync(backend, adapter, "alice", state_path)
assert updated.exported == 1
assert "Corrected fact" in adapter._path.read_text(encoding="utf-8")
repeated = await sync(backend, adapter, "alice", state_path)
assert repeated.imported == repeated.exported == 0
finally:
await memory.close()
+107
View File
@@ -0,0 +1,107 @@
"""Agent synchronization must include memories older than the newest 500."""
from datetime import datetime, timedelta
from unittest.mock import AsyncMock
import numpy as np
import pytest
from headroom.memory.adapters.graph import InMemoryGraphStore
from headroom.memory.adapters.hnsw import HNSWVectorIndex
from headroom.memory.adapters.sqlite import SQLiteMemoryStore
from headroom.memory.backends.local import LocalBackend, LocalBackendConfig
from headroom.memory.config import MemoryConfig
from headroom.memory.core import HierarchicalMemory
from headroom.memory.models import Memory
from headroom.memory.ports import MemoryFilter
from headroom.memory.sync import sync, sync_export, sync_import
from headroom.memory.sync_adapters.codex_agent import CodexAdapter
@pytest.fixture
async def backend(tmp_path):
store = SQLiteMemoryStore(tmp_path / "memories.db")
embedder = AsyncMock()
embedder.embed.return_value = np.ones(4)
memory = HierarchicalMemory(
store,
HNSWVectorIndex(dimension=4),
AsyncMock(),
embedder,
config=MemoryConfig(auto_bubble=False),
)
backend = LocalBackend(LocalBackendConfig(db_path=str(tmp_path / "memories.db")))
backend._hierarchical_memory = memory
backend._graph = InMemoryGraphStore()
backend._initialized = True
now = datetime.now()
memories = [
Memory(
id=f"alice-{i:04}",
content=f"Distinct memory {i}",
user_id="alice",
created_at=now - timedelta(seconds=i),
)
for i in range(501)
]
memories.append(Memory(content="Other user's private fact", user_id="bob"))
await store.save_batch(memories)
return backend
@pytest.fixture
def adapter(tmp_path):
return CodexAdapter(tmp_path / "AGENTS.md")
@pytest.mark.asyncio
async def test_import_deduplicates_a_memory_older_than_the_latest_500(backend, adapter):
await adapter.write_memories([{"content": "Distinct memory 500", "headroom_id": "alice-0500"}])
assert await sync_import(backend, adapter, "alice") == 0
rows = await backend._hierarchical_memory._store.query(MemoryFilter(user_id="alice"))
assert len(rows) == 501
@pytest.mark.asyncio
async def test_export_includes_the_oldest_memory_and_keeps_user_scope(backend, adapter):
assert await sync_export(backend, adapter, "alice") == 501
exported = await adapter.read_memories()
assert "Distinct memory 500" in {m.content for m in exported}
assert "Other user's private fact" not in {m.content for m in exported}
@pytest.mark.asyncio
@pytest.mark.parametrize("force", [False, True])
async def test_full_sync_exports_every_memory_and_is_idempotent(backend, adapter, tmp_path, force):
state = tmp_path / "state.json"
first = await sync(backend, adapter, "alice", state_path=state, force=force)
assert first.imported == 0
assert first.exported == 501
second = await sync(backend, adapter, "alice", state_path=state, force=True)
assert second.imported == 0
assert second.exported == 0
@pytest.mark.asyncio
async def test_sync_refetch_after_import_does_not_truncate_exports(backend, adapter, tmp_path):
await adapter.write_memories([{"content": "New agent fact", "headroom_id": "new-agent-fact"}])
result = await sync(backend, adapter, "alice", state_path=tmp_path / "state.json", force=True)
assert result.imported == 1
assert result.exported == 501
assert len(await adapter.read_memories()) == 502
@pytest.mark.asyncio
async def test_explicit_existing_snapshot_is_not_requeried(backend, adapter):
snapshot = [Memory(content="Explicit snapshot", user_id="alice")]
backend.get_user_memories = AsyncMock(side_effect=AssertionError("snapshot already provided"))
assert await sync_export(backend, adapter, "alice", existing_memories=snapshot) == 1
assert await sync_import(backend, adapter, "alice", existing_memories=snapshot) == 0
backend.get_user_memories.assert_not_awaited()
@pytest.mark.asyncio
async def test_optional_unbounded_query_preserves_the_default_limit(backend):
assert len(await backend.get_user_memories("alice")) == 100
assert len(await backend.get_user_memories("alice", limit=3)) == 3
assert len(await backend.get_user_memories("alice", limit=None)) == 501
+90 -11
View File
@@ -22,12 +22,40 @@ ROOT = Path(__file__).resolve().parents[1]
# token to its own scan.
FLAG = "trust_remote" + "_code"
# The value: a quoted string, or a name / number (``True``, ``1``, ``-1``, ``cfg.x``).
# Anything but the exact name ``False`` is treated as enabling the flag.
_VALUE = r"\"[^\"]*\"|'[^']*'|[-+]?[\w.]+"
# Matches the kwarg form (``flag=True``), the mapping form (``"flag": True``)
# and the subscript form (``kwargs["flag"] = True``), capturing whatever it is
# set to. The optional quote and bracket matter: without them the mapping form
# slips through, and ``from_pretrained(**{"flag": True})`` is exactly how this
# would come back.
ASSIGNMENT = re.compile(re.escape(FLAG) + r"[\"']?\s*\]?\s*[=:]\s*([A-Za-z_][\w.]*)")
# set to up to the next delimiter. The optional quote and bracket matter:
# without them the mapping form slips through, and
# ``from_pretrained(**{"flag": True})`` is exactly how this would come back.
# The value is NOT required to start with a letter: the library tests the flag
# for truthiness, so ``=1``, ``=(True)`` and ``="yes"`` enable it just as
# ``=True`` does. A value on the next line is still a value, because ``\s*``
# spans the newline.
ASSIGNMENT = re.compile(re.escape(FLAG) + r"[\"']?\s*\]?\s*[=:]\s*\(*\s*(" + _VALUE + ")")
# ``setattr(cfg, "flag", True)`` and ``kwargs.setdefault("flag", True)``: the
# name is a string literal followed by a comma, not by ``=`` or ``:``.
# Only calls that set or default the flag count: ``log.info("flag", True)`` does not.
NAMED_ARGUMENT = re.compile(
r"(?:\b(?:setattr|getattr)\s*\([^,()]*,|\b(?:setdefault|get|pop)\s*\()\s*[\"']"
+ re.escape(FLAG)
+ r"[\"']\s*,\s*\(*\s*("
+ _VALUE
+ ")"
)
def _values(text: str) -> list[tuple[int, str]]:
"""Every ``(line number, value)`` the flag is set to in ``text``."""
found: list[tuple[int, str]] = []
for pattern in (ASSIGNMENT, NAMED_ARGUMENT):
for match in pattern.finditer(text):
found.append((text.count("\n", 0, match.start()) + 1, match.group(1)))
return found
def _tracked_files() -> list[Path]:
@@ -35,6 +63,8 @@ def _tracked_files() -> list[Path]:
git-tracked rather than a filesystem walk: the repository is commonly checked
out alongside worktrees and virtualenvs that a naive rglob would sweep in.
Without git (an exported tarball) the package itself is still scanned, so the
guard does not silently stop running.
"""
try:
out = subprocess.run(
@@ -43,8 +73,8 @@ def _tracked_files() -> list[Path]:
capture_output=True,
check=True,
).stdout
except (OSError, subprocess.CalledProcessError) as exc: # pragma: no cover
pytest.skip(f"git ls-files unavailable: {exc}")
except (OSError, subprocess.CalledProcessError):
return sorted((ROOT / "headroom").rglob("*.py"))
return [ROOT / name for name in out.decode().split("\0") if name]
@@ -58,10 +88,10 @@ def test_remote_code_is_never_enabled_anywhere_in_the_tree() -> None:
continue # binary or vanished (submodule, symlink) — nothing to read
if FLAG not in text:
continue
for lineno, line in enumerate(text.splitlines(), start=1):
for value in ASSIGNMENT.findall(line):
if value != "False":
offenders.append(f"{path.relative_to(ROOT)}:{lineno}: {line.strip()}")
lines = text.splitlines()
for lineno, value in _values(text):
if value != "False":
offenders.append(f"{path.relative_to(ROOT)}:{lineno}: {lines[lineno - 1].strip()}")
assert not offenders, (
f"{FLAG} must be False everywhere — it executes repository-supplied "
@@ -69,9 +99,58 @@ def test_remote_code_is_never_enabled_anywhere_in_the_tree() -> None:
)
@pytest.mark.parametrize(
"line",
[
f"model = load(x, {FLAG}=True)",
f"model = load(x, {FLAG}=1)",
f"model = load(x, {FLAG}=(True))",
f'model = load(x, {FLAG}="yes")',
f"model = load(x, {FLAG}=enabled)",
f'kwargs["{FLAG}"] = True',
f'load(**{{"{FLAG}": 1}})',
f'setattr(cfg, "{FLAG}", True)',
f'kwargs.setdefault("{FLAG}", True)',
],
)
def test_the_scan_flags_every_truthy_way_to_enable_the_flag(line: str) -> None:
values = [value for _, value in _values(line)]
assert values and all(value != "False" for value in values), line
@pytest.mark.parametrize(
"line",
[
f'log.info("{FLAG}", True)',
f'print("{FLAG}", 1)',
f'logger.debug("{FLAG}", enabled)',
],
)
def test_the_scan_ignores_calls_that_do_not_set_the_flag(line: str) -> None:
assert _values(line) == []
def test_the_scan_flags_a_value_on_the_next_line() -> None:
text = f"load(\n x,\n {FLAG}=\n True,\n)\n"
assert [value for _, value in _values(text)] == ["True"]
@pytest.mark.parametrize(
"line",
[
f"model = load(x, {FLAG}=False)",
f"model = load(x, {FLAG}=(False))",
f'kwargs["{FLAG}"] = False',
f'setattr(cfg, "{FLAG}", False)',
],
)
def test_the_scan_accepts_an_explicit_false(line: str) -> None:
assert [value for _, value in _values(line)] == ["False"]
def test_the_tokenizer_loader_sets_the_flag_explicitly() -> None:
"""Explicit beats relying on the library default, which upstream can change."""
source = (ROOT / "headroom" / "tokenizers" / "huggingface.py").read_text(encoding="utf-8")
values = ASSIGNMENT.findall(source)
values = [value for _, value in _values(source)]
assert values, f"tokenizer loader no longer passes {FLAG} explicitly"
assert set(values) == {"False"}
+40
View File
@@ -953,6 +953,46 @@ def test_websocket_origin_policy_can_be_pinned_with_env(monkeypatch):
assert _is_allowed_websocket_origin({"origin": "http://localhost:3000"}) is False
@pytest.mark.parametrize(
("ws_origins", "cors_origins"),
[(None, "*"), ("*", None), (None, "*, https://dash.example.com")],
)
def test_websocket_origin_policy_ignores_wildcard(monkeypatch, ws_origins, cors_origins):
for name, value in (
("HEADROOM_WS_ORIGINS", ws_origins),
("HEADROOM_CORS_ORIGINS", cors_origins),
):
if value is None:
monkeypatch.delenv(name, raising=False)
else:
monkeypatch.setenv(name, value)
assert _is_allowed_websocket_origin({"origin": "https://remote.example"}) is False
# A bare "*" leaves the loopback default in place.
if "dash.example.com" not in (cors_origins or ""):
assert _is_allowed_websocket_origin({"origin": "http://127.0.0.1:8787"}) is True
else:
assert _is_allowed_websocket_origin({"origin": "https://dash.example.com"}) is True
def test_handle_openai_responses_ws_closes_foreign_origin_under_wildcard_cors(monkeypatch):
monkeypatch.delenv("HEADROOM_WS_ORIGINS", raising=False)
monkeypatch.setenv("HEADROOM_CORS_ORIGINS", "*")
handler = _DummyOpenAIHandler()
websocket = _DummyWebSocket({"origin": "https://remote.example"})
with patch.dict(sys.modules, {"websockets": MagicMock()}):
with patch(
"headroom.proxy.handlers.openai._resolve_codex_routing_headers",
side_effect=AssertionError("routing should not run"),
):
anyio.run(handler.handle_openai_responses_ws, websocket)
assert websocket.closed is True
assert websocket.close_code == 1008
assert websocket.close_reason == "origin not allowed"
def test_handle_openai_responses_ws_resolves_codex_routing_headers():
class SentinelError(RuntimeError):
pass
+140
View File
@@ -9,6 +9,9 @@ SavingsRecorder.estimate_request_savings supplies that per-request number.
from __future__ import annotations
import pytest
from headroom.proxy import output_savings
from headroom.proxy.output_savings import (
SavingsRecorder,
stratum_key,
@@ -86,3 +89,140 @@ def test_estimate_request_savings_zero_for_control_and_unknown(tmp_path):
assert rec.estimate_request_savings(["something-else"], 600) == 0
# Treatment but output exceeded the baseline -> clamped to 0, never negative.
assert rec.estimate_request_savings([stratum_label("treatment", key)], 5000) == 0
@pytest.fixture
def l4_factors(monkeypatch):
"""Benchmark factors as an enterprise extension would register them."""
monkeypatch.setattr(output_savings, "MODELLED_REDUCTION", {4: (0.2, 0.5)})
def test_shaped_request_without_a_baseline_is_priced_from_its_level_factors(tmp_path, l4_factors):
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
labels = [stratum_label("treatment", _key()), "output_shaper:verbosity:L4"]
rec.record_from_labels(labels, 800) # the funnel records before it estimates
# Observed output is already shaped: saved = 800 * r / (1 - r).
assert rec.request_savings_range(labels, 800) == (200, 800)
def test_a_holdout_too_small_to_report_keeps_the_factor_tier(tmp_path, l4_factors):
"""Same tier as the dashboard: one control observation does not make the
holdout the headline, so the request stays on the modelled band."""
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
key = _key()
shaped = [stratum_label("treatment", key), "output_shaper:verbosity:L4"]
rec.record_from_labels(shaped, 800)
rec.record_from_labels([stratum_label("control", key)], 1000)
assert rec._ledger.best_estimate(4).kind == "modelled"
assert rec.request_savings_range(shaped, 800) == (200, 800)
def test_measured_tier_credits_only_strata_inside_the_measurement(tmp_path, l4_factors):
"""Devin's case: stratum A carries the holdout, stratum B has no control.
A request in A books A's own control mean minus its output; a request in
B books nothing, exactly as the measured headline leaves B out."""
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
a, b = "opus|a|s|tools", "opus|b|s|tools"
for i in range(5):
rec._ledger.record("control", a, 1000, f"c{i}")
rec._ledger.record("treatment", a, 800, f"t{i}")
rec._ledger.record("treatment", b, 1000, "tb")
assert rec._ledger.best_estimate(4).kind == "measured"
shaped = "output_shaper:verbosity:L4"
assert rec.request_savings_range([stratum_label("treatment", a), shaped], 800) == (200, 200)
assert rec.request_savings_range([stratum_label("treatment", b), shaped], 1000) == (0, 0)
def test_baseline_and_holdout_outrank_the_factors(tmp_path, l4_factors):
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
key = _key()
for _ in range(5):
rec._ledger.baseline.observe(key, 1000)
shaped = "output_shaper:verbosity:L4"
assert rec.request_savings_range([stratum_label("treatment", key), shaped], 600) == (400, 400)
assert rec.request_savings_range([stratum_label("control", key)], 600) == (0, 0)
def test_no_registered_factors_means_no_modelled_saving(tmp_path):
"""Plain OSS ships an empty factor table: nothing is booked."""
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
labels = [stratum_label("treatment", _key()), "output_shaper:verbosity:L4"]
assert rec.request_savings_range(labels, 800) == (0, 0)
def test_lifetime_carries_the_output_savings_range_across_a_restart(tmp_path):
path = str(tmp_path / "s.json")
tracker = SavingsTracker(path=path)
tracker.record_request(
model="claude-opus-4-8",
input_tokens=1000,
tokens_saved=0,
output_tokens_saved=200,
output_tokens_saved_high=800,
timestamp="2026-03-27T09:00:00Z",
)
tracker.record_request( # a point estimate: high end equals low end
model="claude-opus-4-8",
input_tokens=1000,
tokens_saved=0,
output_tokens_saved=100,
timestamp="2026-03-27T09:30:00Z",
)
lifetime = SavingsTracker(path=path).snapshot()["lifetime"]
assert lifetime["output_tokens_saved"] == 300
assert lifetime["output_tokens_saved_high"] == 900
low_usd, high_usd = lifetime["output_savings_usd"], lifetime["output_savings_usd_high"]
assert low_usd > 0
assert high_usd == pytest.approx(low_usd * 3, rel=1e-3)
def test_treatment_request_that_was_not_shaped_saves_nothing(tmp_path, l4_factors):
"""The stratum label is attached before shaping is attempted; only the
verbosity label proves the request was shaped."""
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
key = _key()
for _ in range(5):
rec._ledger.baseline.observe(key, 1000)
assert rec.request_savings_range([stratum_label("treatment", key)], 600) == (0, 0)
def test_factors_are_not_booked_once_the_deployment_has_a_baseline(tmp_path, l4_factors):
"""A baseline learned for other traffic must not leave this request on
benchmark factors while /stats reports the estimated tier."""
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
other = stratum_key(
turn_kind="chat", input_tokens=500, model="claude-opus-4-8", has_tools=False
)
for _ in range(5):
rec._ledger.baseline.observe(other, 1000)
labels = [stratum_label("treatment", _key()), "output_shaper:verbosity:L4"]
rec.record_from_labels(labels, 800)
low, high = rec.request_savings_range(labels, 800)
assert low == high # a baseline point estimate, never the factor band
def test_fresh_tracker_lifetime_carries_the_range_keys(tmp_path):
lifetime = SavingsTracker(path=str(tmp_path / "s.json")).snapshot()["lifetime"]
assert lifetime["output_tokens_saved_high"] == 0
assert lifetime["output_savings_usd_high"] == 0.0
def test_a_response_without_output_usage_books_nothing(tmp_path, l4_factors):
"""A missing completion count arrives as 0; no tier may read that as
the whole baseline saved."""
rec = SavingsRecorder(str(tmp_path / "o.json"), flush_every=1)
a = "opus|a|s|tools"
for i in range(5):
rec._ledger.record("control", a, 1000, f"c{i}")
rec._ledger.record("treatment", a, 800, f"t{i}")
rec._ledger.baseline.observe(a, 1000)
shaped = [stratum_label("treatment", a), "output_shaper:verbosity:L4"]
assert rec.request_savings_range(shaped, 0) == (0, 0)
+1 -1
View File
@@ -33,7 +33,7 @@ class _FakeClient:
self._response = response
self.calls = 0
async def post(self, url, content=None, headers=None):
async def post(self, url, content=None, headers=None, extensions=None):
self.calls += 1
if self._responses is not None:
return self._responses[self.calls - 1]
@@ -8,6 +8,7 @@ import pytest
from headroom.providers.copilot.vscode import (
configure_vscode_proxy_settings,
copilot_harness_settings_enabled,
remove_vscode_proxy_settings,
unrouted_vscode_profiles,
vscode_proxy_url,
@@ -67,6 +68,77 @@ def test_configure_update_and_remove_preserve_jsonc_verbatim(tmp_path: Path) ->
assert remove_vscode_proxy_settings(path) is False
def _live_settings(path: Path) -> dict[str, object]:
"""Parse the written JSONC the way VS Code does: comments and trailing commas ignored."""
lines = path.read_text(encoding="utf-8").splitlines()
body = "\n".join(line for line in lines if not line.strip().startswith("//"))
return json.loads(body.replace(",\n}", "\n}"))
def test_configure_keeps_new_chats_on_the_local_harness(tmp_path: Path) -> None:
path = tmp_path / "settings.json"
original = '{\n\t"editor.fontSize": 15\n}\n'
path.write_text(original, encoding="utf-8")
configure_vscode_proxy_settings(path, "http://127.0.0.1:8787")
# A chat on the Copilot harness ignores the endpoint overrides, and VS Code
# can flip either default by rollout, so both are pinned explicitly.
settings = _live_settings(path)
assert settings["chat.defaultToCopilotHarness"] is False
assert settings["chat.editor.preferCopilotHarness"] is False
assert copilot_harness_settings_enabled(path) == []
assert remove_vscode_proxy_settings(path) is True
assert path.read_text(encoding="utf-8") == original
def test_configure_upgrades_a_block_written_before_the_harness_settings(tmp_path: Path) -> None:
path = tmp_path / "settings.json"
original = '{\n\t"editor.fontSize": 15\n}\n'
path.write_text(
'{\n\t"editor.fontSize": 15,\n'
"\t// --- Headroom Copilot proxy --- (comma-added)\n"
'\t"github.copilot.advanced.debug.overrideProxyUrl": "http://127.0.0.1:8787",\n'
'\t"github.copilot.advanced.debug.overrideAuthType": "token",\n'
'\t"github.copilot.advanced.debug.overrideCapiUrl": "http://127.0.0.1:8787"\n'
"\t// --- end Headroom Copilot proxy ---\n}\n",
encoding="utf-8",
)
assert configure_vscode_proxy_settings(path, "http://127.0.0.1:8787") == "updated"
settings = _live_settings(path)
assert settings["chat.defaultToCopilotHarness"] is False
assert settings["chat.editor.preferCopilotHarness"] is False
assert "github.copilot.advanced.debug.overrideAuthType" not in settings
assert remove_vscode_proxy_settings(path) is True
assert path.read_text(encoding="utf-8") == original
@pytest.mark.parametrize("user_value", [True, False])
def test_configure_leaves_a_harness_setting_the_user_already_chose(
tmp_path: Path, user_value: bool
) -> None:
path = tmp_path / "settings.json"
original = f'{{\n\t"chat.defaultToCopilotHarness": {json.dumps(user_value)},\n}}\n'
path.write_text(original, encoding="utf-8")
for _ in range(2): # a re-run must not start writing the key either
configure_vscode_proxy_settings(path, "http://127.0.0.1:8787")
configured = path.read_text(encoding="utf-8")
# A second copy inside the block would win silently: JSONC keeps the last one.
assert configured.count('"chat.defaultToCopilotHarness"') == 1
settings = _live_settings(path)
assert settings["chat.defaultToCopilotHarness"] is user_value
assert settings["chat.editor.preferCopilotHarness"] is False
assert copilot_harness_settings_enabled(path) == (
["chat.defaultToCopilotHarness"] if user_value else []
)
assert remove_vscode_proxy_settings(path) is True
assert path.read_text(encoding="utf-8") == original
def test_configure_refuses_malformed_and_unmanaged_override(tmp_path: Path) -> None:
path = tmp_path / "settings.json"
for original in (
+16 -4
View File
@@ -94,8 +94,20 @@ def test_explicit_allowlist_override(monkeypatch: pytest.MonkeyPatch) -> None:
def test_wildcard_optback(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HEADROOM_CORS_ORIGINS", "*")
resp = _preflight(_make_client(), "http://evil.com")
assert resp.status_code == 200
assert resp.headers.get("access-control-allow-origin") == "*"
monkeypatch.delenv("HEADROOM_WS_ORIGINS", raising=False)
client = _make_client()
# "*" widens which pages may read a response; it does not let a foreign
# page drive the proxy, so the security gate refuses it before CORS runs.
foreign = _preflight(client, "http://evil.com")
assert foreign.status_code == 403
assert foreign.headers.get("access-control-allow-origin") is None
refused_post = client.post("/v1/messages", content="{}", headers={"Origin": "http://evil.com"})
assert refused_post.status_code == 403
# A page the proxy trusts still gets the wildcard answer.
local = _preflight(client, "http://127.0.0.1:8787")
assert local.status_code == 200
assert local.headers.get("access-control-allow-origin") == "*"
# Wildcard opt-back must not silently re-enable credentialed reads.
assert resp.headers.get("access-control-allow-credentials") != "true"
assert local.headers.get("access-control-allow-credentials") != "true"
+1 -1
View File
@@ -223,7 +223,7 @@ class _RetryThenSuccessClient:
def __init__(self) -> None:
self.attempts = 0
async def post(self, url, content, headers, timeout=None): # noqa: ANN001, ANN201
async def post(self, url, content, headers, timeout=None, extensions=None): # noqa: ANN001, ANN201
self.attempts += 1
if self.attempts == 1:
raise httpx.ConnectTimeout("connect timed out")
+30 -5
View File
@@ -93,22 +93,33 @@ def _seed_ccr_entry() -> str:
)
# What the guard answers: the body FastAPI gives an unknown path, so the route is
# invisible rather than forbidden. A detail route answers 404 with its OWN message
# ("No telemetry found for signature: ...") when its key is absent, so a bare 404
# status cannot tell the guard from a missing key.
GUARD_DENIAL = {"detail": "Not Found"}
@pytest.mark.parametrize("method,path", GATED)
def test_non_loopback_caller_gets_404(method: str, path: str) -> None:
# A vanilla TestClient presents client.host="testclient", which is not a
# loopback IP, so the guard returns 404 (invisible, not 403).
client = TestClient(_make_app())
# A routable, non-loopback peer (TEST-NET-3), with a loopback Host header so the
# client-IP check is the only thing that can refuse it. A vanilla TestClient
# presents client.host="testclient", which is not an IP at all, so it would
# not tell "denies non-loopback IPs" from "denies a peer it cannot parse".
client = TestClient(_make_app(), base_url="http://127.0.0.1", client=("203.0.113.9", 4242))
resp = client.request(method, path)
assert resp.status_code == 404, resp.text
assert resp.json() == GUARD_DENIAL, resp.text
@pytest.mark.parametrize("method,path", GATED)
def test_loopback_caller_allowed(method: str, path: str) -> None:
client = _loopback_client()
resp = client.request(method, path, json={} if method == "post" else None)
# Detail routes legitimately return 404 when their test key is absent;
# the companion non-loopback test proves the guard itself.
# Detail routes legitimately return 404 when their test key is absent, but with
# their own message; the guard's denial body would mean it refused loopback.
assert resp.status_code in {200, 404, 422}, resp.text
assert resp.json() != GUARD_DENIAL, resp.text
def test_toin_pattern_detail_whitelists_learned_payload(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -1175,3 +1186,17 @@ def test_settings_write_refused_for_trusted_gateway_peer(
def test_settings_write_allowed_for_real_loopback() -> None:
resp = _loopback_client().post("/settings", json={"values": {}})
assert resp.status_code == 200, resp.text
@pytest.mark.parametrize("host", ["headroom-remote.invalid", "evil.example:8787"])
def test_local_only_routes_refuse_the_hosts_the_rust_front_relays_for_remote_callers(
host: str,
) -> None:
# The Rust front reaches this proxy from 127.0.0.1. For a caller that is
# not local on its side it sends a non-loopback Host (the reserved
# headroom-remote.invalid when the Host would otherwise name loopback),
# so these routes must refuse a loopback peer carrying such a Host.
client = TestClient(_make_app(), base_url=f"http://{host}", client=("127.0.0.1", 12345))
assert client.get("/admin/upstream").status_code == 404
assert client.get("/debug/tasks").status_code == 404
assert client.get("/transformations/feed").status_code == 404
+4
View File
@@ -151,6 +151,8 @@ def test_savings_tracker_sanitizes_legacy_state_and_applies_retention(tmp_path):
"total_input_cost_usd": 0.0,
"output_tokens_saved": 0,
"output_savings_usd": 0.0,
"output_tokens_saved_high": 0,
"output_savings_usd_high": 0.0,
"output_tokens": 0,
"total_output_cost_usd": 0.0,
}
@@ -205,6 +207,8 @@ def test_non_dict_savings_state_resets_to_default(tmp_path):
"total_input_cost_usd": 0.0,
"output_tokens_saved": 0,
"output_savings_usd": 0.0,
"output_tokens_saved_high": 0,
"output_savings_usd_high": 0.0,
"output_tokens": 0,
"total_output_cost_usd": 0.0,
}
@@ -2,6 +2,8 @@
from __future__ import annotations
import pytest
from headroom.proxy.semantic_cache_key_policy import (
compute_semantic_cache_key,
strip_cache_control,
@@ -73,3 +75,10 @@ def test_strip_cache_control_preserves_user_defined_schema_property() -> None:
}
assert strip_cache_control(schema) == schema
def test_semantic_cache_key_requires_a_partition() -> None:
"""The partition is mandatory, not defaulted: a shared proxy must never
answer one caller from another caller's cached response."""
with pytest.raises(ValueError, match="requires a caller partition"):
compute_semantic_cache_key(MESSAGES, MODEL, partition="")
+37
View File
@@ -723,3 +723,40 @@ def test_tokens_inflated_does_not_disturb_derived_sizes() -> None:
assert o.attempted_input_tokens == 57845
assert o.savings_pct == 0.0
assert o.tokens_inflated == 2684
@pytest.mark.asyncio
async def test_funnel_books_the_modelled_output_range_on_the_lifetime(
tmp_path, monkeypatch
) -> None:
"""Registered factors reach the tracker's lifetime totals end to end:
outcome -> PrometheusMetrics.record_request -> SavingsTracker."""
from headroom.proxy import output_savings
from headroom.proxy.prometheus_metrics import PrometheusMetrics
from headroom.proxy.savings_tracker import SavingsTracker
monkeypatch.setattr(output_savings, "MODELLED_REDUCTION", {4: (0.2, 0.5)})
monkeypatch.setattr(
output_savings, "_RECORDER", output_savings.SavingsRecorder(str(tmp_path / "o.json"))
)
tracker = SavingsTracker(path=str(tmp_path / "s.json"))
h = _FunnelHarness()
h.metrics = PrometheusMetrics(savings_tracker=tracker)
key = output_savings.stratum_key(
turn_kind="code", input_tokens=8000, model="claude-sonnet-4", has_tools=True
)
await h._record_request_outcome(
_outcome(
output_tokens=800,
transforms_applied=[
output_savings.stratum_label("treatment", key),
"output_shaper:verbosity:L4",
],
)
)
lifetime = tracker.snapshot()["lifetime"]
assert lifetime["output_tokens_saved"] == 200
assert lifetime["output_tokens_saved_high"] == 800
assert lifetime["output_savings_usd_high"] > lifetime["output_savings_usd"] > 0
+1 -1
View File
@@ -37,7 +37,7 @@ class _FakeClient:
self._exc = exc
self.calls = 0
async def post(self, url, content=None, headers=None):
async def post(self, url, content=None, headers=None, extensions=None):
self.calls += 1
if self._exc is not None:
raise self._exc
@@ -12,7 +12,13 @@ from __future__ import annotations
from types import SimpleNamespace
import httpx
import pytest
from fastapi.testclient import TestClient
from headroom import copilot_auth
from headroom.proxy.route_advice import BackendResolver, RouteAdvice
from headroom.proxy.server import ProxyConfig, create_app
class _Sentinel:
@@ -79,3 +85,66 @@ def test_failed_provider_falls_back_to_default() -> None:
assert r1 == "DEFAULT_BACKEND"
r2 = resolver.for_request(_request("claude-opus-5", "anthropic"), native_providers=("openai",))
assert r2 == "DEFAULT_BACKEND"
def test_copilot_upstream_ignores_cross_provider_advice() -> None:
# A Copilot proxy holds only a Copilot token, so advice naming another
# provider must not move the request or rewrite its model. A GHE host
# counts as Copilot too.
resolver = _resolver()
body: dict = {"model": "gpt-5-mini"}
result = resolver.for_request(
_request("claude-opus-5", "anthropic"),
body=body,
native_providers=("openai",),
upstream_url="https://copilot-api.acme.ghe.com",
)
assert result == "DEFAULT_BACKEND"
assert body["model"] == "gpt-5-mini"
def test_copilot_chat_stays_on_copilot_despite_cross_provider_advice(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# A proxy in front of GitHub Copilot holds a Copilot token only, and Copilot
# serves every model family on its own /chat/completions. Advice naming
# another provider used to send the request to Anthropic through a
# translating backend, where it failed for want of a key.
class _Provider:
async def get_api_token(self, *, integration_id=None): # noqa: ANN001, ANN202
return SimpleNamespace(token="test-copilot-token")
monkeypatch.setattr(copilot_auth, "get_copilot_token_provider", lambda: _Provider())
built: list[str] = []
monkeypatch.setattr(BackendResolver, "_build", lambda self, provider: built.append(provider))
sent: list[tuple[str, str]] = []
async def fake_retry(method, url, headers, body, *args, **kwargs): # noqa: ANN001, ANN002, ANN003, ANN202
sent.append((url, body["model"]))
return httpx.Response(200, json={"choices": [], "usage": {}})
app = create_app(
ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
openai_api_url="https://api.business.githubcopilot.com",
)
)
@app.middleware("http")
async def publish_advice(request, call_next): # noqa: ANN001, ANN202
request.state.headroom_route = RouteAdvice(model="claude-sonnet-5-5", provider="anthropic")
return await call_next(request)
with TestClient(app) as client:
client.app.state.proxy._retry_request = fake_retry
response = client.post(
"/v1/chat/completions",
json={"model": "gpt-5-mini", "messages": [{"role": "user", "content": "hi"}]},
headers={"Authorization": "Bearer test-key"},
)
assert response.status_code == 200, response.text
assert built == [], "no translating backend may be built for a Copilot upstream"
assert sent == [("https://api.business.githubcopilot.com/chat/completions", "gpt-5-mini")]
+46
View File
@@ -394,3 +394,49 @@ def test_wildcard_selection_activates_registered_external(_memory_ccr):
assert comp.calls
assert "external:ext_json" in result.strategy_chain
# ───────────── explicit passthrough code never reaches an external ─────────────
_PY_FENCE = "\n".join(
["import json", ""]
+ [
f"def handler_{i}(event):\n if event.get('k{i}'):\n return json.dumps(event)\n return None\n"
for i in range(30)
]
)
_PROSE = " ".join(
["The nightly job failed after the deploy and the operator wants a short summary."] * 40
)
def test_passthrough_code_section_is_not_offered_to_a_text_external(_memory_ccr):
# With prefer_code_aware_for_code=False the router keeps source code
# unmangled (PASSTHROUGH). A selected prose-only external compressor must
# not receive that code: mixed content splits the fence into its own section.
comp = _RecordingExternal(name="ext_text", content_types=("text/plain",))
router = ContentRouter(
_cfg(active_external_compressors=["ext_text"], prefer_code_aware_for_code=False)
)
router.compressor_registry.register(comp, replace=True)
router._active_external_compressors = router._resolve_active_external_compressors()
content = f"{_PROSE}\n\n```python\n{_PY_FENCE}\n```\n\n{_PROSE}"
result = router.compress(content)
assert all("def handler_0" not in call.content for call in comp.calls)
assert f"```python\n{_PY_FENCE}\n```" in result.compressed
def test_passthrough_whole_code_block_is_not_offered_to_a_text_external(_memory_ccr):
comp = _RecordingExternal(name="ext_text", content_types=("text/plain",))
router = ContentRouter(
_cfg(active_external_compressors=["ext_text"], prefer_code_aware_for_code=False)
)
router.compressor_registry.register(comp, replace=True)
router._active_external_compressors = router._resolve_active_external_compressors()
result = router.compress(_PY_FENCE)
assert not comp.calls
assert result.compressed == _PY_FENCE
+201
View File
@@ -17,6 +17,30 @@ from headroom.transforms.content_router import (
)
@pytest.mark.parametrize("disk", [False, True])
@pytest.mark.parametrize("skip_method", ["mark_skip", "move_to_skip"])
def test_a_new_result_supersedes_an_older_skip(tmp_path, disk, skip_method):
store = ResultStore(tmp_path / "cache.db", 1800) if disk else None
cache = CompressionCache(store=store)
getattr(cache, skip_method)("same")
cache.put("same", "compressed", 0.4, "kompress")
assert not cache.is_skipped("same")
assert cache.get("same") == ("compressed", 0.4, "kompress")
assert cache.skip_size == 0
def test_first_sight_skips_do_not_issue_sqlite_writes(tmp_path):
store = ResultStore(tmp_path / "cache.db", 1800)
cache = CompressionCache(store=store)
statements = []
store._db.set_trace_callback(statements.append)
for i in range(100):
cache.mark_skip(f"new-{i}")
assert cache.skip_size == 100
assert statements == []
def test_results_stay_within_the_memory_budget_least_recently_used_first():
cache = CompressionCache(max_bytes=10_000)
for i in range(100):
@@ -480,3 +504,180 @@ def test_a_result_that_expires_while_a_read_waits_is_not_returned(tmp_path, monk
reader.join(5)
assert results == [None]
assert cache.get("k") is None
def test_invalidate_drops_cached_result_without_marking_skipped():
cache = CompressionCache(max_bytes=10_000)
cache.put("k", "compressed <<ccr:0123456789abcdef>>", 0.2, "log")
assert cache.invalidate("k") is True
assert cache.invalidate("k") is False
assert cache.get("k") is None
assert cache.is_skipped("k") is False
assert cache.stats["cache_bytes"] == 0
def test_compress_repopulates_ccr_store_after_capacity_eviction():
import copy
import re
from headroom import CompressConfig, compress
from headroom.cache.backends import InMemoryBackend
from headroom.cache.compression_store import get_compression_store, reset_compression_store
def messages(n: int) -> list[dict[str, str]]:
text = "\n".join(
f"2026-01-01 12:00:{i % 60:02d} INFO case{n} processed record {i}" for i in range(251)
)
return [{"role": "tool", "tool_call_id": f"case-{n}", "content": text}]
reset_compression_store()
try:
store = get_compression_store(max_entries=2, backend=InMemoryBackend())
config = CompressConfig(
kompress_model="disabled",
protect_recent=0,
min_tokens_to_compress=10,
compress_system_messages=False,
)
originals = [messages(n) for n in range(3)]
keys = []
for original in originals:
result = compress(copy.deepcopy(original), model="gpt-4o", config=config)
keys.append(re.findall(r"hash=([0-9a-f]{16,64})", result.messages[-1]["content"])[-1])
assert store.retrieve(keys[0]) is None
repeat = compress(copy.deepcopy(originals[0]), model="gpt-4o", config=config)
repeat_key = re.findall(r"hash=([0-9a-f]{16,64})", repeat.messages[-1]["content"])[-1]
retrieved = store.retrieve(repeat_key)
assert retrieved is not None
assert retrieved.original_content == originals[0][-1]["content"]
finally:
reset_compression_store()
def test_compress_block_content_repopulates_ccr_store_after_capacity_eviction():
import copy
import re
from headroom import CompressConfig, compress
from headroom.cache.backends import InMemoryBackend
from headroom.cache.compression_store import get_compression_store, reset_compression_store
def messages(n: int) -> list[dict]:
text = "\n".join(
f"2026-01-01 12:00:{i % 60:02d} INFO block{n} processed record {i}" for i in range(251)
)
return [
{
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": f"b-{n}", "content": text}],
}
]
reset_compression_store()
try:
store = get_compression_store(max_entries=2, backend=InMemoryBackend())
config = CompressConfig(
kompress_model="disabled",
protect_recent=0,
min_tokens_to_compress=10,
compress_system_messages=False,
)
originals = [messages(n) for n in range(3)]
keys = []
for original in originals:
result = compress(copy.deepcopy(original), model="gpt-4o", config=config)
compressed_text = result.messages[-1]["content"][0]["content"]
keys.append(re.findall(r"hash=([0-9a-f]{16,64})", compressed_text)[-1])
assert store.retrieve(keys[0]) is None
repeat = compress(copy.deepcopy(originals[0]), model="gpt-4o", config=config)
repeat_text = repeat.messages[-1]["content"][0]["content"]
repeat_key = re.findall(r"hash=([0-9a-f]{16,64})", repeat_text)[-1]
retrieved = store.retrieve(repeat_key)
assert retrieved is not None
assert retrieved.original_content == originals[0][-1]["content"][0]["content"]
finally:
reset_compression_store()
def test_router_invalidates_cached_marker_when_store_cleared():
from headroom.cache.backends import InMemoryBackend
from headroom.cache.compression_store import CompressionStore
from headroom.tokenizer import Tokenizer
from headroom.tokenizers.estimator import EstimatingTokenCounter
custom_store = CompressionStore(max_entries=4, backend=InMemoryBackend())
router = ContentRouter(ContentRouterConfig())
text = "\n".join(f"2026-01-01 12:00:{i % 60:02d} INFO custom {i}" for i in range(251))
msgs = [{"role": "tool", "tool_call_id": "t1", "content": text}]
stored_key = custom_store.store(text, "[compressed]")
cache_key = router._content_cache_key(text, bias=1.0, context="", gated=True)
router._cache.put(
cache_key,
f"[251 lines compressed. Retrieve more: hash={stored_key}]",
0.1,
"log",
marker_hashes=(stored_key,),
)
assert router._cached_markers_retrievable(cache_key, compression_store=custom_store)
custom_store.clear()
assert not router._cached_markers_retrievable(cache_key, compression_store=custom_store)
second = router.apply(
msgs,
Tokenizer(EstimatingTokenCounter()),
compression_store=custom_store,
min_tokens_to_compress=10,
)
assert second.transforms_applied
assert router._cache.get(cache_key) is not None
def test_compress_over_capacity_batch_then_repeat_evicted_original():
import copy
import re
from headroom import CompressConfig, compress
from headroom.cache.backends import InMemoryBackend
from headroom.cache.compression_store import get_compression_store, reset_compression_store
def make_msg(n: int) -> dict[str, str]:
text = "\n".join(
f"2026-01-01 12:00:{i % 60:02d} INFO batch{n} processed record {i}" for i in range(251)
)
return {"role": "tool", "tool_call_id": f"batch-{n}", "content": text}
reset_compression_store()
try:
store = get_compression_store(max_entries=2, backend=InMemoryBackend())
config = CompressConfig(
kompress_model="disabled",
protect_recent=0,
min_tokens_to_compress=10,
compress_system_messages=False,
)
originals = [make_msg(n) for n in range(3)]
batch_result = compress(copy.deepcopy(originals), model="gpt-4o", config=config)
batch_keys = [
re.findall(r"hash=([0-9a-f]{16,64})", msg["content"])[-1]
for msg in batch_result.messages
]
# Parallel tasks may finish in any thread order; with max_entries=2 and 3
# distinct entries, at least one entry is evicted before caching runs.
evicted_indices = [i for i, k in enumerate(batch_keys) if store.retrieve(k) is None]
assert evicted_indices, "expected at least one batch entry to be capacity-evicted"
# Repeating an evicted message alone must re-populate the store rather than
# reusing an unbacked marker.
evicted_idx = evicted_indices[0]
repeat = compress([copy.deepcopy(originals[evicted_idx])], model="gpt-4o", config=config)
repeat_key = re.findall(r"hash=([0-9a-f]{16,64})", repeat.messages[-1]["content"])[-1]
retrieved = store.retrieve(repeat_key)
assert retrieved is not None
assert retrieved.original_content == originals[evicted_idx]["content"]
finally:
reset_compression_store()
@@ -0,0 +1,221 @@
"""Literal ``cache_control`` fields inside model-visible payloads (#4272).
``cache_control`` is overloaded: a transport prompt-cache directive on content
blocks, and ordinary application data inside tool inputs, JSON Schema bodies and
their literal values. Stripping it everywhere made two requests that differ in
model-visible data share one key, so the second replayed the first's response.
"""
from __future__ import annotations
import copy
import pytest
from headroom.proxy.semantic_cache import SemanticCache
from headroom.proxy.semantic_cache_key_policy import (
compute_semantic_cache_key,
strip_cache_control,
)
MODEL = "fixture"
PARTITION = "caller"
RESPONSE = b'{"id":"first-response","choices":[{"message":{"content":"first"}}]}'
# Fields whose value Headroom may legitimately receive as a decoded dict and
# where ``cache_control`` is application data, not a transport directive. A JSON
# *string* value (what OpenAI actually sends for ``arguments``) was never at risk:
# the stripper leaves strings alone at any depth.
LITERAL_DICT_LOCATIONS = (
"tool_input", # Anthropic tool_use input
"tool_arguments_dict", # OpenAI function.arguments, decoded to a dict
"tool_schema", # Anthropic input_schema default
"response_schema", # OpenAI response_format json_schema const
)
def _payloads(location: str) -> tuple[list[dict], dict]:
"""(messages, key_fields) holding a literal ``cache_control`` at ``location``."""
messages: list[dict] = [{"role": "user", "content": "Configure the application."}]
fields: dict = {}
if location == "tool_input":
messages = [
{
"role": "assistant",
"content": [
{
"type": "tool_use",
"id": "call1",
"name": "configure",
"input": {"cache_control": "first"},
}
],
}
]
elif location == "tool_arguments_dict":
# OpenAI sends ``arguments`` as a JSON *string*, which the old stripper
# left alone (see the string guard below). Headroom also tolerates a
# decoded dict there -- ``handlers/openai.py`` parses either shape -- and
# for that shape the old stripper did erase the field, so this is the
# shape that demonstrates the OpenAI-path regression.
messages = [
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call1",
"type": "function",
"function": {"name": "configure", "arguments": {"cache_control": "first"}},
}
],
}
]
elif location == "tool_schema":
fields = {
"tools": [
{
"name": "configure",
"input_schema": {
"type": "object",
"properties": {
"value": {"type": "object", "default": {"cache_control": "first"}}
},
},
}
]
}
elif location == "response_schema":
fields = {
"response_format": {
"type": "json_schema",
"json_schema": {"name": "answer", "schema": {"const": {"cache_control": "first"}}},
}
}
else: # pragma: no cover - guards the parametrization
raise AssertionError(f"unknown location {location}")
return messages, fields
def _with_changed_value(messages: list[dict], fields: dict, location: str) -> tuple[list, dict]:
messages, fields = copy.deepcopy((messages, fields))
if location == "tool_input":
messages[0]["content"][0]["input"]["cache_control"] = "second"
elif location == "tool_arguments_dict":
messages[0]["tool_calls"][0]["function"]["arguments"]["cache_control"] = "second"
elif location == "tool_schema":
fields["tools"][0]["input_schema"]["properties"]["value"]["default"]["cache_control"] = (
"second"
)
else:
fields["response_format"]["json_schema"]["schema"]["const"]["cache_control"] = "second"
return messages, fields
@pytest.mark.parametrize("location", LITERAL_DICT_LOCATIONS)
@pytest.mark.asyncio
async def test_literal_cache_control_does_not_alias_cached_responses(location: str) -> None:
messages, fields = _payloads(location)
changed_messages, changed_fields = _with_changed_value(messages, fields, location)
cache = SemanticCache()
await cache.set(messages, MODEL, RESPONSE, {}, partition=PARTITION, **fields)
# The changed request must miss: its tool data / schema really differs.
assert await cache.get(changed_messages, MODEL, partition=PARTITION, **changed_fields) is None
# ...and the original still hits, so the fix does not merely widen the key.
original = await cache.get(messages, MODEL, partition=PARTITION, **fields)
assert original is not None and original.response_body == RESPONSE
@pytest.mark.parametrize("location", LITERAL_DICT_LOCATIONS)
def test_literal_cache_control_changes_the_key(location: str) -> None:
messages, fields = _payloads(location)
changed_messages, changed_fields = _with_changed_value(messages, fields, location)
assert compute_semantic_cache_key(
messages, MODEL, partition=PARTITION, **fields
) != compute_semantic_cache_key(changed_messages, MODEL, partition=PARTITION, **changed_fields)
def test_openai_arguments_string_is_not_rewritten() -> None:
"""OpenAI sends ``arguments`` as a JSON string; it must pass through verbatim.
This shape was never aliased by the old stripper (strings are returned
as-is at any depth), so it is a regression guard, not a bug demonstration.
"""
first = '{"cache_control": "first"}'
second = '{"cache_control": "second"}'
payload = {"function": {"name": "configure", "arguments": first}}
assert strip_cache_control(payload) == payload
assert compute_semantic_cache_key(
[{"role": "assistant", "content": None, "tool_calls": [{"id": "c", **payload}]}],
MODEL,
partition=PARTITION,
) != compute_semantic_cache_key(
[
{
"role": "assistant",
"content": None,
"tool_calls": [{"id": "c", "function": {"name": "configure", "arguments": second}}],
}
],
MODEL,
partition=PARTITION,
)
def test_transport_cache_control_is_still_ignored() -> None:
"""A moved breakpoint must not fragment the key (#327 intent)."""
block = {"type": "text", "text": "sys"}
with_block = [{**block, "cache_control": {"type": "ephemeral"}}]
assert compute_semantic_cache_key(
[{"role": "user", "content": "hello"}],
MODEL,
partition=PARTITION,
system=with_block,
tools=[{"name": "read", "cache_control": {"type": "ephemeral"}}],
) == compute_semantic_cache_key(
[{"role": "user", "content": "hello"}],
MODEL,
partition=PARTITION,
system=[block],
tools=[{"name": "read"}],
)
def test_strip_cache_control_keeps_schema_property_named_cache_control() -> None:
schema = {
"type": "object",
"properties": {
"cache_control": {"type": "boolean", "description": "Flush the application cache"}
},
}
assert strip_cache_control(schema) == schema
def test_strip_cache_control_still_drops_nested_transport_annotations() -> None:
assert strip_cache_control(
{
"cache_control": "drop-root",
"messages": [
{
"role": "assistant",
"content": [
{"type": "tool_use", "input": {"cache_control": "keep"}},
{"type": "text", "text": "hi", "cache_control": {"type": "ephemeral"}},
],
"cache_control": {"type": "ephemeral"},
}
],
}
) == {
"messages": [
{
"role": "assistant",
"content": [
{"type": "tool_use", "input": {"cache_control": "keep"}},
{"type": "text", "text": "hi"},
],
}
]
}
+148
View File
@@ -0,0 +1,148 @@
"""Scans over tool output must stay linear on long unclosed shapes.
The timing bounds are loose (the old code took minutes at these sizes); the
oracle comparison checks the banner scan still finds exactly what it did.
"""
from __future__ import annotations
import random
import re
import time
import pytest
from headroom.proxy.interceptors.astgrep import (
_detect_truncation,
_is_plausible_truncation_range,
)
from headroom.transforms.mixed_content import (
ContentType,
_extract_json_block,
_has_valid_json_block_with_text,
_JsonBlockScanner,
split_into_sections,
)
_PREVIOUS_BANNER = re.compile(
r"\[\s*truncated\s*:\s*partial\s+view\b"
r"[^\[\]]*?"
r"showing\s+lines?\s+(?P<start_line>\d+)\s*[-–]\s*(?P<end_line>\d+)"
r"\s+of\s+(?P<total_lines>\d+)\s+total"
r"[^\[\]]*\]",
re.IGNORECASE,
)
def _previous_detect(source: str) -> tuple[int, int] | None:
count = len(source.splitlines())
for m in _PREVIOUS_BANNER.finditer(source):
s, e, t = (int(m.group(g)) for g in ("start_line", "end_line", "total_lines"))
if _is_plausible_truncation_range(s, e, t, count):
return e, t
return None
def test_truncation_banner_still_recognised() -> None:
src = (
"x\n" * 50 + "[Truncated: PARTIAL view -- a.py: showing lines 1-40 of 90 total (x). Read.]"
)
assert _detect_truncation(src) == (40, 90)
def test_truncation_banner_matches_previous_regex() -> None:
rng = random.Random(1234)
parts = [
"[truncated: partial view", "[ Truncated : PARTIAL view", "]", "[", "\n",
" showing lines 1-10 of 50 total ", "showing line 3–4 of 9 total", "showing lines 5-5 of 5 total",
"x", " ", "path.py:", "showing lines", "total", "12", "(more)",
] # fmt: skip
for _ in range(3000):
src = "".join(rng.choice(parts) for _ in range(rng.randint(1, 25)))
assert _detect_truncation(src) == _previous_detect(src), repr(src)
def test_truncation_scan_is_linear_on_unclosed_banner() -> None:
src = "[truncated: partial view " + "showing lines 1-10 of 50 total " * 12000
start = time.perf_counter()
assert _detect_truncation(src) is None
assert time.perf_counter() - start < 5.0
def test_json_block_scans_are_bounded_on_unclosed_braces() -> None:
content = "\n".join(["{"] * 20000)
start = time.perf_counter()
assert _has_valid_json_block_with_text(content) is False
sections = split_into_sections(content)
assert time.perf_counter() - start < 10.0
assert "\n".join(s.content for s in sections).count("{") == 20000
def test_long_json_block_inside_text_still_found() -> None:
body = ",\n".join(f' {{"k": {i}}}' for i in range(5000))
content = "log line\n[\n" + body + "\n]\ntrailing"
assert _has_valid_json_block_with_text(content) is True
types = [s.content_type for s in split_into_sections(content)]
assert ContentType.JSON_ARRAY in types
@pytest.mark.parametrize("unclosed", [150, 20000])
def test_json_object_after_many_unclosed_braces_keeps_its_own_section(unclosed: int) -> None:
obj = '{"critical": "disk full"}'
content = "\n".join(["{"] * unclosed + ["some prose"] * 6 + [obj, "more prose"])
assert _has_valid_json_block_with_text(content) is True
json_sections = [
s for s in split_into_sections(content) if s.content_type is ContentType.JSON_ARRAY
]
assert [s.content for s in json_sections] == [obj]
@pytest.mark.parametrize("repeats", [1, 130])
def test_json_object_after_crossed_count_prefix_keeps_its_own_section(repeats: int) -> None:
# Each count reaches zero on its own but never on the same line, so no
# early rejection applies; the object after it must still be found.
prefix = (["{"] * 150 + ["[" + "}" * 150]) * repeats
obj = '{"critical": "disk full"}'
content = "\n".join(prefix + ["some prose"] * 6 + [obj, "more prose"])
start = time.perf_counter()
assert _has_valid_json_block_with_text(content) is True
json_sections = [
s for s in split_into_sections(content) if s.content_type is ContentType.JSON_ARRAY
]
assert time.perf_counter() - start < 10.0
assert [s.content for s in json_sections] == [obj]
def test_block_scanner_matches_walking_each_candidate() -> None:
rng = random.Random(7)
parts = ["{", "}", "[", "]", '"', "\\\\", "a", " ", ",", "{}", "[]", '"x"', "}}", "]]", "{["]
parts += ['{"' + chr(92), '"' + chr(92)] # lines ending inside a string, escaped
for _ in range(3000):
lines = [
"".join(rng.choice(parts) for _ in range(rng.randint(0, 5)))
for _ in range(rng.randint(1, 25))
]
scanner = _JsonBlockScanner(lines)
scanner._direct_steps_left = 0 # answer every candidate from the sweep
for i, line in enumerate(lines):
if line.strip().startswith(("[", "{")):
assert scanner.extract(i) == _extract_json_block(lines, i), (lines, i)
@pytest.mark.parametrize("pairs", [100, 10000])
def test_json_object_after_escaped_string_lines_keeps_its_own_section(pairs: int) -> None:
# Lines ending inside a string with a trailing backslash put each walk in
# a different string state, so candidates start walks that only merge
# later; every one must still be answered.
obj = '{"critical": "disk full"}'
prefix_line = '{"' + chr(92)
content = "\n".join(
["{"] + [prefix_line, '"'] * pairs + ["some prose"] * 6 + [obj, "more prose"]
)
start = time.perf_counter()
assert _has_valid_json_block_with_text(content) is True
json_sections = [
s.content for s in split_into_sections(content) if s.content_type is ContentType.JSON_ARRAY
]
assert time.perf_counter() - start < 10.0
assert json_sections == [obj]
@@ -252,3 +252,14 @@ def test_dictionary_cells_still_decode_edge_values() -> None:
{"tag": None},
{},
]
def test_container_shaped_string_cells_round_trip() -> None:
# A string whose text is a JSON container (`"[]"`, `"{}"`, `"[1,2]"`) must come back as
# that string, not as the value it spells. #4053 fixed the scalar-looking case; containers
# were still un-escaped by the classifier, which made both render byte-identically.
values = [[], "[]", [1, 2], "[1,2]", {}, "{}"]
records = [{"id": i, "v": v} for i, v in enumerate(values * 10)]
block = _crush(records)
assert block, "expected the table to compact"
assert expand_compacted(block) == records
+80 -20
View File
@@ -412,6 +412,69 @@ def test_anthropic_tool_result_lossy_without_marker_stays_verbatim(router, token
assert result.messages[0]["content"][0]["content"] == tool_content
def _multi_block_tool_result_messages(blocks: list[dict]) -> list[dict]:
return [
{"role": "user", "content": "fetch the worker logs"},
{
"role": "assistant",
"content": [{"type": "tool_use", "id": "tu1", "name": "mcp__logs__fetch", "input": {}}],
},
{
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": "tu1", "content": blocks}],
},
{"role": "user", "content": "any errors?"},
]
def test_list_form_tool_result_blocks_are_not_fused(router, tokenizer):
"""A list-form tool_result with several text blocks (an MCP tool returning
more than one TextContent) is flattened for the compressors. The blocks
must stay on separate lines: joining them with "" fused the last line of
one block with the first line of the next (#4729)."""
lines_a = [
f"2026-11-10T10:{i % 60:02d}:00Z INFO worker-{i % 3} batch {i} ok" for i in range(150)
]
lines_b = [f"2026-11-10T11:{i % 60:02d}:00Z WARN worker-{i % 3} retry {i}" for i in range(150)]
blocks = [
{"type": "text", "text": "\n".join(lines_a)},
{"type": "text", "text": "\n".join(lines_b)},
]
result = router.apply(
_multi_block_tool_result_messages(blocks),
tokenizer,
compress_user_messages=True,
min_tokens_to_compress=10,
read_protection_window=0,
)
out = result.messages[2]["content"][0]["content"]
assert isinstance(out, list) and len(out) == 1 and out[0]["type"] == "text"
text = out[0]["text"]
assert text != "\n".join(lines_a + lines_b), "compressor did not run"
original = set(lines_a) | set(lines_b)
emitted = [line for line in text.splitlines() if line.startswith("2026-11-10T")]
assert emitted, "no log lines survived compression"
assert [line for line in emitted if line not in original] == []
@pytest.mark.parametrize(
("texts", "expected"),
[
(["a\nb", "c"], "a\nb\nc"),
(["a\n", "b"], "a\nb"),
(["a", "", "b"], "a\nb"),
(["only"], "only"),
],
)
def test_join_tool_result_text_blocks(texts, expected):
from headroom.transforms.content_router import _join_tool_result_text_blocks
blocks = [{"type": "text", "text": t} for t in texts]
assert _join_tool_result_text_blocks(blocks) == expected
# =============================================================================
# TestContentRouterConfig
# =============================================================================
@@ -1589,23 +1652,25 @@ class TestSmartCrusherFallback:
f"{strategy_chain}"
)
def test_code_aware_fallback_also_uses_unified_block(self, router, monkeypatch):
"""CodeAware strategy also uses the unified fallback block.
Verify it doesn't double-invoke Kompress either."""
def test_code_aware_declining_never_falls_back_to_kompress(self, router, monkeypatch):
"""Code-aware declining a block leaves it unchanged; prose ML never runs (#4214).
Replaces the old "no double Kompress" check: with the CODE_AWARE ->
Kompress fallbacks removed, Kompress must not run even once.
"""
import headroom.transforms.content_router as crm
monkeypatch.setattr(
crm.ContentRouter,
"_try_ml_compressor",
lambda self, content, context="", question=None: (
content,
len(content.split()),
),
)
ml_calls: list[str] = []
def spy(self, content, context="", question=None):
ml_calls.append(content)
return content, len(content.split())
monkeypatch.setattr(crm.ContentRouter, "_try_ml_compressor", spy)
plain = "This is just plain text. " * 200
compressed, compressed_tokens, strategy_chain, _reversible = (
compressed, _compressed_tokens, strategy_chain, _reversible = (
router._apply_strategy_to_content(
plain,
CompressionStrategy.CODE_AWARE,
@@ -1613,15 +1678,10 @@ class TestSmartCrusherFallback:
)
)
# CodeAware should be in the chain
assert "code_aware" in strategy_chain
# No duplicate fallback entries
kompress_count = strategy_chain.count("kompress")
assert kompress_count <= 1, (
f"Kompress appeared {kompress_count} times; "
f"duplicate fallback in CodeAware path: {strategy_chain}"
)
assert "kompress" not in strategy_chain
assert ml_calls == []
assert compressed == plain
# =============================================================================
+156 -64
View File
@@ -1503,20 +1503,29 @@ def test_text_block_cache_control_protected_with_assistant_optin(
assert counts["cache_control_protected"] == 1
def test_tool_result_cache_control_protected(monkeypatch: pytest.MonkeyPatch) -> None:
def _marked_tool_result(text: str, nested: bool) -> dict[str, object]:
"""A tool_result carrying a cache_control marker either on the block
itself or on the text sub-block of its list content (both shapes are
accepted by the Messages API)."""
if nested:
return {
"type": "tool_result",
"tool_use_id": "abc",
"content": [{"type": "text", "text": text, "cache_control": {"type": "ephemeral"}}],
}
return {
"type": "tool_result",
"tool_use_id": "abc",
"content": text,
"cache_control": {"type": "ephemeral"},
}
@pytest.mark.parametrize("nested", [False, True], ids=["block_marker", "nested_marker"])
def test_tool_result_cache_control_protected(monkeypatch: pytest.MonkeyPatch, nested: bool) -> None:
router = _make_router_with_mock_compress(monkeypatch)
long_text = "Z" * 1000
msg = {
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "abc",
"content": long_text,
"cache_control": {"type": "ephemeral"},
}
],
}
msg = {"role": "user", "content": [_marked_tool_result(long_text, nested)]}
counts: dict[str, int] = {}
result = router._process_content_blocks(
msg,
@@ -1530,10 +1539,38 @@ def test_tool_result_cache_control_protected(monkeypatch: pytest.MonkeyPatch) ->
)
# cache_control hard-skip applies to tool_result too, on any message the
# provider may already hold under that key (anything but the final one).
assert result["content"][0]["content"] == long_text
assert result["content"][0] == _marked_tool_result(long_text, nested)
assert counts["cache_control_protected"] == 1
@pytest.mark.parametrize("nested", [False, True], ids=["block_marker", "nested_marker"])
def test_marked_tool_result_in_history_survives_apply(
monkeypatch: pytest.MonkeyPatch, nested: bool
) -> None:
# End to end through apply() (the compress() / /v1/compress path): a
# marked tool_result in an earlier turn may already be cached upstream
# under its marker, so it comes back byte-identical, marker included.
router = _make_router_with_mock_compress(monkeypatch)
long_text = "tool output line " * 200
messages = [
{"role": "user", "content": "run the tests"},
{
"role": "assistant",
"content": [{"type": "tool_use", "id": "abc", "name": "bash", "input": {}}],
},
{"role": "user", "content": [_marked_tool_result(long_text, nested)]},
{"role": "assistant", "content": "done"},
{"role": "user", "content": "now fix the lint"},
]
class FakeTokenizer:
def count_text(self, text: str) -> int:
return len(str(text).split())
out = router.apply(messages, FakeTokenizer(), model_limit=100_000)
assert out.messages[2]["content"][0] == _marked_tool_result(long_text, nested)
def test_tool_result_cache_control_compressed_in_final_message(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -2858,30 +2895,39 @@ def _noop_code_aware_router(monkeypatch: pytest.MonkeyPatch, kompress_out: str)
return router
def test_code_aware_noop_keeps_a_smaller_kompress_fallback(
monkeypatch: pytest.MonkeyPatch,
@pytest.mark.parametrize("layer_lossy", [False, True], ids=["default", "lossless-then-lossy"])
def test_code_aware_noop_never_hands_code_to_kompress(
monkeypatch: pytest.MonkeyPatch, layer_lossy: bool
) -> None:
"""The fallback is judged in tokens, the unit of the code_aware result.
"""A code_aware no-op leaves the block unchanged even if Kompress would shrink it (#4214).
With code_aware's result counted in words, a Kompress result at ~60% of the
tokens still "lost" to the unchanged block, so the inference always ran and
was always thrown away.
Kompress is a prose model: it drops keywords, so it never sees code, neither as
the CODE_AWARE fallback nor as the lossless-then-lossy inline attempt.
"""
kompressed = "\n".join(f"{i}\tvalue_{i} compute(&items[{i}..])" for i in range(1, 121))
assert _estimate_tokens(kompressed) < _estimate_tokens(_NUMBERED_RUST)
assert _estimate_tokens(kompressed) > len(_NUMBERED_RUST.split())
router = _noop_code_aware_router(monkeypatch, kompressed)
router._lossless_then_lossy = layer_lossy
calls: list[str] = []
kompress = router._try_ml_compressor
def counting(content: str, *args: object, **kwargs: object) -> tuple[str, int]:
calls.append(content)
return kompress(content, *args, **kwargs)
monkeypatch.setattr(router, "_try_ml_compressor", counting)
compressed, compressed_tokens, strategy_chain, _reversible = router._apply_strategy_to_content(
_NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
)
assert compressed == kompressed
assert compressed_tokens == _estimate_tokens(kompressed)
assert strategy_chain == ["code_aware", "kompress"]
assert compressed == _NUMBERED_RUST
assert compressed_tokens == _estimate_tokens(_NUMBERED_RUST)
assert strategy_chain == ["code_aware"]
assert calls == []
def test_code_aware_noop_reports_tokens_when_kompress_passes_through(
def test_code_aware_noop_reports_tokens_without_kompress(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""An unchanged block is reported at its own token count, never its word count."""
@@ -2895,58 +2941,104 @@ def test_code_aware_noop_reports_tokens_when_kompress_passes_through(
assert compressed_tokens == _estimate_tokens(_NUMBERED_RUST)
def test_code_aware_noop_runs_kompress_once_when_it_passes_through(
monkeypatch: pytest.MonkeyPatch,
@pytest.mark.parametrize(
("enabled", "preferred", "layer_lossy"),
[(False, True, False), (True, True, False), (True, False, False), (True, True, True)],
ids=["unavailable", "declined", "passthrough", "lossless-then-lossy"],
)
def test_fenced_code_keeps_keywords_when_code_compression_declines(
monkeypatch: pytest.MonkeyPatch, enabled: bool, preferred: bool, layer_lossy: bool
) -> None:
"""Lossless-then-lossy tries Kompress inline; a passthrough must not be retried."""
router = _noop_code_aware_router(monkeypatch, _NUMBERED_RUST)
router._lossless_then_lossy = True
calls: list[str] = []
kompress = router._try_ml_compressor
code = "\n\n".join(
f"def select_{i}(items):\n"
" result = []\n"
" for item in items:\n"
" if item is not None:\n"
" result.append(item)\n"
" return result"
for i in range(6)
)
router = _noop_code_aware_router(monkeypatch, code.replace("for ", "").replace("if ", ""))
router.config.enable_code_aware = enabled
router.config.prefer_code_aware_for_code = preferred
router._lossless_then_lossy = layer_lossy
prose = "\n\n".join(f"Section {i} describes the generated implementation." for i in range(6))
mixed = f"{prose}\n\n```python\n{code}\n```\n\nExecution finished."
def counting(content: str, *args: object, **kwargs: object) -> tuple[str, int]:
calls.append(content)
return kompress(content, *args, **kwargs)
monkeypatch.setattr(router, "_try_ml_compressor", counting)
compressed, compressed_tokens, _chain, _reversible = router._apply_strategy_to_content(
_NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
result = router.compress(
mixed, precomputed_detection=DetectionResult(ContentType.PLAIN_TEXT, 1.0, {})
)
assert compressed == _NUMBERED_RUST
assert compressed_tokens == _estimate_tokens(_NUMBERED_RUST)
assert len(calls) == 1
assert f"```python\n{code}\n```" in result.compressed
def test_code_aware_noop_keeps_a_smaller_inline_kompress(
monkeypatch: pytest.MonkeyPatch,
# The ctx_execute shape from #4214: a fenced Python script followed by its output.
# The reporter's own 1324-character fence is not published, so this is a
# reconstruction: it keeps the four lines quoted in the issue, parses, and is
# exactly 1324 characters. The fake Kompress deletes the keywords the issue lists.
_ISSUE_4214_SCRIPT = """import json, collections
d = json.load(open('turns.json'))
segs=[s for s in open('segs.txt').read().split() if s]
def load(path):
try:
return json.load(open(path))
except Exception as e: return None
for i,s in enumerate(segs):
t0=(d or {}).get('turns') or []
if not t0 or len(t0) < 2:
continue
else:
label = s if s else 'unknown'
counts = collections.Counter(x.get('role') for x in t0)
for role, n in counts.items():
if n > 1 or role == 'tool':
print(i, label, role, n)
else:
print(i, label, role)
total = sum(counts.values())
if total > 10 or label == 'big':
print('large session', label, total)
out = [k for k in counts if counts[k] > 0]
print(json.dumps(out))
summary = {s: i for i, s in enumerate(segs)}
for k, v in summary.items():
if v % 2 == 0 or k.startswith('a'):
print(k, v)
print('done', len(segs))"""
_ISSUE_4214_FENCE = _ISSUE_4214_SCRIPT + "\n#" + "x" * (1324 - len(_ISSUE_4214_SCRIPT) - 2)
@pytest.mark.parametrize("enabled", [False, True], ids=["code-aware-off", "code-aware-on"])
def test_issue_4214_fenced_script_survives_kompress_unchanged(
monkeypatch: pytest.MonkeyPatch, enabled: bool
) -> None:
"""Lossless-then-lossy's inline attempt keeps a Kompress result that wins.
import ast
import re
Measured in tokens, a code_aware no-op no longer looks like a shrink, so the
inline attempt fires and its smaller result is kept without a second call.
"""
kompressed = "\n".join(f"{i}\tvalue_{i} compute(&items[{i}..])" for i in range(1, 121))
router = _noop_code_aware_router(monkeypatch, kompressed)
router._lossless_then_lossy = True
calls: list[str] = []
kompress = router._try_ml_compressor
assert len(_ISSUE_4214_FENCE) == 1324
ast.parse(_ISSUE_4214_FENCE)
monkeypatch.delenv("HEADROOM_LOSSLESS_THEN_LOSSY", raising=False)
router = ContentRouter(ContentRouterConfig(enable_code_aware=enabled))
seen: list[str] = []
def counting(content: str, *args: object, **kwargs: object) -> tuple[str, int]:
calls.append(content)
return kompress(content, *args, **kwargs)
def drop_keywords(content: str, *_args: object, **_kwargs: object) -> tuple[str, int]:
seen.append(content)
dropped = re.sub(r"\b(for|in|if|as|or|else) ?", "", content)
return dropped, _estimate_tokens(dropped)
monkeypatch.setattr(router, "_try_ml_compressor", counting)
compressed, compressed_tokens, strategy_chain, _reversible = router._apply_strategy_to_content(
_NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
monkeypatch.setattr(router, "_try_ml_compressor", drop_keywords)
output = "\n".join(
f"Segment {i}: The job read the batch, checked each record against the schema "
"and wrote a summary line for the report because the operator asked."
for i in range(40)
)
content = f"```python\n{_ISSUE_4214_FENCE}\n```\n\n{output}"
assert compressed == kompressed
assert compressed_tokens == _estimate_tokens(kompressed)
assert strategy_chain == ["code_aware", "kompress"]
assert len(calls) == 1
result = router.compress(content, context="")
assert f"```python\n{_ISSUE_4214_FENCE}\n```" in result.compressed
assert not any("def load" in section for section in seen)
@pytest.mark.parametrize("as_block", [False, True], ids=["string-tool", "tool-result-block"])