Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

Enhance /stats endpoint and add comprehensive benchmarks

chopratejas77248cd1a3b8
diff --git a/benchmarks/compression_benchmark.py b/benchmarks/compression_benchmark.py
new file mode 100644
index 000000000..e5daf2f77
--- /dev/null
+++ b/benchmarks/compression_benchmark.py
@@ -0,0 +1,976 @@
+"""
+Truncation vs Summarization vs Headroom: A Fair Benchmark
+
+This benchmark compares three approaches to context compression:
+1. Truncation - Keep first N items (industry standard)
+2. Summarization - Use LLM to summarize (common alternative)
+3. Headroom - Statistical compression with retrieval
+
+FAIRNESS PRINCIPLES:
+- Include scenarios where each approach could win
+- Use realistic data patterns
+- Measure both compression AND answer quality
+- Report failures honestly
+
+Metrics:
+- Tokens saved (compression ratio)
+- Answer accuracy (can LLM still answer correctly?)
+- Cost (including summarization LLM calls)
+- Latency
+"""
+
+import hashlib
+import json
+import random
+import time
+from dataclasses import dataclass
+from typing import Literal
+
+# We'll use OpenAI for the actual LLM calls
+try:
+ from openai import OpenAI
+
+ OPENAI_AVAILABLE = True
+except ImportError:
+ OPENAI_AVAILABLE = False
+
+# Headroom imports
+try:
+ from headroom.config import SmartCrusherConfig
+ from headroom.tokenizers import TiktokenCounter
+ from headroom.transforms.smart_crusher import SmartCrusher
+
+ HEADROOM_AVAILABLE = True
+except ImportError:
+ HEADROOM_AVAILABLE = False
+
+# LLMLingua imports (SOTA baseline)
+try:
+ from headroom.transforms.llmlingua_compressor import LLMLinguaCompressor, LLMLinguaConfig
+
+ LLMLINGUA_AVAILABLE = True
+except ImportError:
+ LLMLINGUA_AVAILABLE = False
+
+
+@dataclass
+class Question:
+ """A question about the data with ground truth answer."""
+
+ text: str
+ ground_truth: str
+ answer_location: Literal["early", "middle", "late", "scattered", "semantic"]
+ difficulty: Literal["easy", "medium", "hard"]
+
+
+@dataclass
+class Scenario:
+ """A benchmark scenario with data and questions."""
+
+ name: str
+ description: str
+ data: list[dict]
+ questions: list[Question]
+ expected_winner: str # Which approach should theoretically win
+
+
+@dataclass
+class ApproachResult:
+ """Result of running one approach on one scenario."""
+
+ approach: str
+ scenario: str
+ tokens_original: int
+ tokens_after: int
+ compression_ratio: float
+ compression_latency_ms: float
+ llm_cost_usd: float # Cost of summarization if applicable
+ answers: list[dict] # {question, expected, actual, correct}
+ accuracy: float
+ total_cost_usd: float # Compression cost + query cost
+
+
+# =============================================================================
+# DATA GENERATORS - Realistic synthetic data
+# =============================================================================
+
+
+def generate_log_data(
+ n_entries: int = 500, error_positions: list[int] = None
+) -> tuple[list[dict], list[Question]]:
+ """
+ Generate realistic server logs.
+
+ 95% routine logs, 5% interesting events (errors, warnings).
+ Errors placed at specified positions to test different approaches.
+ """
+ if error_positions is None:
+ # Default: errors at beginning, middle, and end
+ error_positions = [3, n_entries // 2, n_entries - 5]
+
+ log_templates = [
+ {"level": "INFO", "message": "Health check passed", "service": "api-gateway"},
+ {"level": "INFO", "message": "Request processed successfully", "service": "api-gateway"},
+ {"level": "INFO", "message": "Cache hit for user session", "service": "redis"},
+ {"level": "INFO", "message": "Database query completed", "service": "postgres"},
+ {"level": "INFO", "message": "Authentication successful", "service": "auth"},
+ {
+ "level": "DEBUG",
+ "message": "Connection pool stats: active=5, idle=15",
+ "service": "postgres",
+ },
+ ]
+
+ error_templates = [
+ {
+ "level": "ERROR",
+ "message": "Connection refused to payment-service:8080 - ECONNREFUSED",
+ "service": "payment-processor",
+ "error_code": "PAYMENT_SERVICE_DOWN",
+ "trace_id": "abc123",
+ },
+ {
+ "level": "ERROR",
+ "message": "Timeout waiting for response from inventory-service after 30000ms",
+ "service": "order-processor",
+ "error_code": "INVENTORY_TIMEOUT",
+ "trace_id": "def456",
+ },
+ {
+ "level": "CRITICAL",
+ "message": "Out of memory: Java heap space - killing process",
+ "service": "recommendation-engine",
+ "error_code": "OOM_KILLED",
+ "trace_id": "ghi789",
+ },
+ ]
+
+ logs = []
+ base_time = 1705320000 # Some Unix timestamp
+
+ error_idx = 0
+ for i in range(n_entries):
+ base_time + i * 60 # 1 minute apart
+
+ if i in error_positions and error_idx < len(error_templates):
+ entry = error_templates[error_idx].copy()
+ error_idx += 1
+ else:
+ entry = random.choice(log_templates).copy()
+
+ entry["timestamp"] = f"2024-01-15T{10 + (i // 60):02d}:{i % 60:02d}:00Z"
+ entry["request_id"] = f"req-{hashlib.md5(str(i).encode()).hexdigest()[:8]}"
+ logs.append(entry)
+
+ # Questions designed to test different approaches
+ questions = [
+ Question(
+ text="What error code was returned by the payment service?",
+ ground_truth="PAYMENT_SERVICE_DOWN",
+ answer_location="early", # Position 3
+ difficulty="easy",
+ ),
+ Question(
+ text="Which service experienced a timeout and what was the trace ID?",
+ ground_truth="order-processor service had timeout with trace_id def456",
+ answer_location="middle",
+ difficulty="medium",
+ ),
+ Question(
+ text="What critical error occurred and which service was affected?",
+ ground_truth="Out of memory (OOM_KILLED) in recommendation-engine",
+ answer_location="late", # Near end
+ difficulty="medium",
+ ),
+ Question(
+ text="How many distinct error types are in the logs?",
+ ground_truth="3",
+ answer_location="scattered",
+ difficulty="hard",
+ ),
+ ]
+
+ return logs, questions
+
+
+def generate_file_search_data(n_files: int = 1000) -> tuple[list[dict], list[Question]]:
+ """
+ Generate realistic code search results.
+
+ Simulates searching a codebase - lots of files with similar metadata,
+ specific files of interest scattered throughout.
+ """
+
+ # Common directories and file patterns
+ dirs = [
+ "src/api",
+ "src/services",
+ "src/utils",
+ "src/models",
+ "src/controllers",
+ "src/middleware",
+ "tests/unit",
+ "tests/integration",
+ "lib/core",
+ "lib/helpers",
+ "config",
+ "scripts",
+ ]
+
+ extensions = [".py", ".py", ".py", ".ts", ".js", ".json", ".yaml"] # Weighted toward .py
+
+ # Files of interest (scattered at specific positions)
+ special_files = {
+ 50: {
+ "path": "src/auth/jwt_handler.py",
+ "size": 2341,
+ "description": "JWT token validation and refresh",
+ },
+ 250: {
+ "path": "src/services/payment_processor.py",
+ "size": 5672,
+ "description": "Stripe payment integration",
+ },
+ 500: {
+ "path": "src/middleware/rate_limiter.py",
+ "size": 1823,
+ "description": "Redis-based rate limiting",
+ },
+ 750: {
+ "path": "config/database.py",
+ "size": 892,
+ "description": "PostgreSQL connection settings",
+ },
+ 999: {
+ "path": "src/api/health_check.py",
+ "size": 456,
+ "description": "Kubernetes health endpoints",
+ },
+ }
+
+ files = []
+ for i in range(n_files):
+ if i in special_files:
+ f = special_files[i].copy()
+ f["type"] = "file"
+ f["language"] = "python"
+ f["modified"] = "2024-01-15"
+ else:
+ dir_path = random.choice(dirs)
+ ext = random.choice(extensions)
+ f = {
+ "type": "file",
+ "path": f"{dir_path}/module_{i}{ext}",
+ "size": random.randint(200, 5000),
+ "language": "python"
+ if ext == ".py"
+ else "typescript"
+ if ext == ".ts"
+ else "javascript",
+ "modified": f"2024-01-{random.randint(1, 15):02d}",
+ }
+ files.append(f)
+
+ questions = [
+ Question(
+ text="Which file handles JWT token operations?",
+ ground_truth="src/auth/jwt_handler.py",
+ answer_location="early", # Position 50
+ difficulty="easy",
+ ),
+ Question(
+ text="What file contains the Stripe payment integration and how large is it?",
+ ground_truth="src/services/payment_processor.py, 5672 bytes",
+ answer_location="middle", # Position 250
+ difficulty="medium",
+ ),
+ Question(
+ text="Which file implements rate limiting and what technology does it use?",
+ ground_truth="src/middleware/rate_limiter.py uses Redis",
+ answer_location="middle", # Position 500
+ difficulty="medium",
+ ),
+ Question(
+ text="What is the last Python file in the results and what does it do?",
+ ground_truth="src/api/health_check.py - Kubernetes health endpoints",
+ answer_location="late", # Position 999
+ difficulty="hard",
+ ),
+ ]
+
+ return files, questions
+
+
+def generate_metrics_data(n_points: int = 500) -> tuple[list[dict], list[Question]]:
+ """
+ Generate realistic time series metrics.
+
+ Baseline values with anomalies (spikes) at specific positions.
+ This is where Headroom should excel - detecting statistical outliers.
+ """
+
+ base_cpu = 45.0
+ base_memory = 62.0
+ base_requests = 1000
+
+ # Anomaly positions
+ anomalies = {
+ 50: {"cpu": 95.0, "memory": 88.0, "requests": 5000, "event": "traffic_spike"},
+ 200: {"cpu": 98.0, "memory": 95.0, "requests": 150, "event": "service_degradation"},
+ 450: {"cpu": 15.0, "memory": 30.0, "requests": 50, "event": "service_restart"},
+ }
+
+ metrics = []
+ base_time = 1705320000
+
+ for i in range(n_points):
+ base_time + i * 60
+
+ if i in anomalies:
+ point = {
+ "timestamp": f"2024-01-15T{10 + (i // 60):02d}:{i % 60:02d}:00Z",
+ "cpu_percent": anomalies[i]["cpu"],
+ "memory_percent": anomalies[i]["memory"],
+ "requests_per_min": anomalies[i]["requests"],
+ "status": "degraded" if anomalies[i]["event"] != "traffic_spike" else "ok",
+ "event": anomalies[i]["event"],
+ }
+ else:
+ point = {
+ "timestamp": f"2024-01-15T{10 + (i // 60):02d}:{i % 60:02d}:00Z",
+ "cpu_percent": round(base_cpu + random.uniform(-5, 5), 1),
+ "memory_percent": round(base_memory + random.uniform(-3, 3), 1),
+ "requests_per_min": base_requests + random.randint(-100, 100),
+ "status": "ok",
+ }
+ metrics.append(point)
+
+ questions = [
+ Question(
+ text="When did the traffic spike occur and what was the requests_per_min?",
+ ground_truth="Around 10:50, requests_per_min was 5000",
+ answer_location="early",
+ difficulty="easy",
+ ),
+ Question(
+ text="What event caused service degradation and what were the CPU/memory values?",
+ ground_truth="service_degradation event, CPU 98%, memory 95%",
+ answer_location="middle",
+ difficulty="medium",
+ ),
+ Question(
+ text="When did the service restart and how can you tell from the metrics?",
+ ground_truth="Around 17:30, CPU dropped to 15%, memory to 30%, requests to 50",
+ answer_location="late",
+ difficulty="hard",
+ ),
+ Question(
+ text="How many anomalous events occurred in total?",
+ ground_truth="3",
+ answer_location="scattered",
+ difficulty="hard",
+ ),
+ ]
+
+ return metrics, questions
+
+
+# =============================================================================
+# COMPRESSION APPROACHES
+# =============================================================================
+
+
+def truncate_data(data: list[dict], max_items: int = 20) -> list[dict]:
+ """Simple truncation - keep first N items."""
+ return data[:max_items]
+
+
+def summarize_data(
+ data: list[dict], client: "OpenAI", model: str = "gpt-4o-mini"
+) -> tuple[str, float]:
+ """
+ Use LLM to summarize the data.
+ Returns (summary_text, cost_usd).
+ """
+ data_str = json.dumps(data, indent=2)
+
+ # Truncate if too long for summarization call
+ if len(data_str) > 100000:
+ data_str = data_str[:100000] + "\n... [truncated for summarization]"
+
+ prompt = f"""Summarize this data concisely, preserving all important information including:
+- Any errors, warnings, or anomalies
+- Key identifiers (IDs, names, paths)
+- Statistical outliers
+- Important events
+
+Data:
+{data_str}
+
+Provide a structured summary that retains all critical details."""
+
+ start = time.time()
+ response = client.chat.completions.create(
+ model=model,
+ messages=[{"role": "user", "content": prompt}],
+ max_tokens=2000,
+ )
+ latency = (time.time() - start) * 1000
+
+ summary = response.choices[0].message.content
+
+ # Estimate cost (gpt-4o-mini pricing)
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = (input_tokens * 0.00015 + output_tokens * 0.0006) / 1000 # Per token pricing
+
+ return summary, cost, latency
+
+
+def llmlingua_compress(data: list[dict]) -> tuple[str, dict]:
+ """
+ Use LLMLingua-2 (Microsoft SOTA) for ML-based compression.
+ Returns (compressed_text, metadata).
+ """
+ if not LLMLINGUA_AVAILABLE:
+ raise RuntimeError(
+ "LLMLingua not available. Install with: pip install headroom-ai[llmlingua]"
+ )
+
+ config = LLMLinguaConfig(
+ target_compression_rate=0.3, # Keep ~30% of tokens
+ min_tokens_for_compression=50,
+ )
+ compressor = LLMLinguaCompressor(config)
+
+ # Convert data to string for LLMLingua (it works on text, not structured data)
+ data_str = json.dumps(data, indent=2)
+
+ start = time.time()
+ result = compressor.compress(data_str, content_type="json")
+ latency = (time.time() - start) * 1000
+
+ metadata = {
+ "latency_ms": latency,
+ "original_tokens": result.original_tokens,
+ "compressed_tokens": result.compressed_tokens,
+ "compression_ratio": result.compression_ratio,
+ }
+
+ return result.compressed, metadata
+
+
+def headroom_compress(data: list[dict], query_context: str = "") -> tuple[list[dict], dict]:
+ """
+ Use Headroom's SmartCrusher for statistical compression.
+ Returns (compressed_data, metadata).
+ """
+ if not HEADROOM_AVAILABLE:
+ raise RuntimeError("Headroom not available")
+
+ config = SmartCrusherConfig(
+ enabled=True,
+ min_items_to_analyze=5,
+ variance_threshold=2.0,
+ max_items_after_crush=20,
+ preserve_change_points=True,
+ )
+
+ crusher = SmartCrusher(config)
+
+ # Wrap data in tool output format
+ tool_content = json.dumps({"results": data})
+
+ start = time.time()
+ crush_result = crusher.crush(tool_content, query=query_context)
+ latency = (time.time() - start) * 1000
+
+ # Parse result - crush returns a CrushResult with .compressed attribute
+ result_str = (
+ crush_result.compressed if hasattr(crush_result, "compressed") else str(crush_result)
+ )
+
+ try:
+ compressed = json.loads(result_str)
+ if isinstance(compressed, dict) and "results" in compressed:
+ compressed_data = compressed["results"]
+ else:
+ compressed_data = compressed if isinstance(compressed, list) else data[:20]
+ except json.JSONDecodeError:
+ compressed_data = data[:20] # Fallback
+
+ metadata = {
+ "latency_ms": latency,
+ "items_before": len(data),
+ "items_after": len(compressed_data) if isinstance(compressed_data, list) else "N/A",
+ }
+
+ return compressed_data, metadata
+
+
+# =============================================================================
+# EVALUATION
+# =============================================================================
+
+
+def count_tokens(text: str) -> int:
+ """Count tokens using tiktoken."""
+ if HEADROOM_AVAILABLE:
+ counter = TiktokenCounter()
+ return counter.count_text(text)
+ else:
+ # Rough estimate: 4 chars per token
+ return len(text) // 4
+
+
+def evaluate_answer(question: Question, actual_answer: str) -> bool:
+ """
+ Check if the answer is correct.
+ Uses fuzzy matching - answer should contain key parts of ground truth.
+ """
+ if not actual_answer:
+ return False
+
+ actual_lower = actual_answer.lower()
+ truth_lower = question.ground_truth.lower()
+
+ # Extract key terms from ground truth
+ key_terms = []
+ for term in truth_lower.replace(",", " ").replace("-", " ").split():
+ if len(term) > 3 and term not in ["the", "and", "was", "with", "from"]:
+ key_terms.append(term)
+
+ # Check if most key terms appear in answer
+ matches = sum(1 for term in key_terms if term in actual_lower)
+ return matches >= len(key_terms) * 0.6 # 60% threshold
+
+
+def query_llm(
+ client: "OpenAI", context: str, question: str, model: str = "gpt-4o-mini"
+) -> tuple[str, float]:
+ """
+ Ask the LLM a question about the given context.
+ Returns (answer, cost_usd).
+ """
+ prompt = f"""Based on the following data, answer the question.
+
+Data:
+{context}
+
+Question: {question}
+
+Answer concisely with specific details from the data."""
+
+ response = client.chat.completions.create(
+ model=model,
+ messages=[{"role": "user", "content": prompt}],
+ max_tokens=500,
+ )
+
+ answer = response.choices[0].message.content
+
+ # Estimate cost
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = (input_tokens * 0.00015 + output_tokens * 0.0006) / 1000
+
+ return answer, cost
+
+
+# =============================================================================
+# BENCHMARK RUNNER
+# =============================================================================
+
+
+@dataclass
+class BenchmarkConfig:
+ """Configuration for the benchmark run."""
+
+ model: str = "gpt-4o-mini" # Model for queries (and summarization)
+ max_truncate_items: int = 20
+ max_headroom_items: int = 20
+ run_summarization: bool = True # Can disable to save cost
+ run_llmlingua: bool = True # Run LLMLingua-2 (SOTA baseline)
+
+
+def run_scenario_benchmark(
+ scenario: Scenario, client: "OpenAI", config: BenchmarkConfig
+) -> list[ApproachResult]:
+ """Run all approaches on a single scenario."""
+
+ results = []
+ original_json = json.dumps(scenario.data, indent=2)
+ original_tokens = count_tokens(original_json)
+
+ print(f"\n{'=' * 60}")
+ print(f"Scenario: {scenario.name}")
+ print(f"Data size: {len(scenario.data)} items, {original_tokens} tokens")
+ print(f"Expected winner: {scenario.expected_winner}")
+ print(f"{'=' * 60}")
+
+ # --- TRUNCATION ---
+ print("\n[1/4] Running Truncation...")
+ start = time.time()
+ truncated = truncate_data(scenario.data, config.max_truncate_items)
+ trunc_latency = (time.time() - start) * 1000
+
+ trunc_json = json.dumps(truncated, indent=2)
+ trunc_tokens = count_tokens(trunc_json)
+
+ trunc_answers = []
+ trunc_query_cost = 0.0
+ for q in scenario.questions:
+ answer, cost = query_llm(client, trunc_json, q.text, config.model)
+ correct = evaluate_answer(q, answer)
+ trunc_answers.append(
+ {
+ "question": q.text,
+ "expected": q.ground_truth,
+ "actual": answer,
+ "correct": correct,
+ "location": q.answer_location,
+ }
+ )
+ trunc_query_cost += cost
+
+ trunc_accuracy = sum(1 for a in trunc_answers if a["correct"]) / len(trunc_answers)
+
+ results.append(
+ ApproachResult(
+ approach="truncation",
+ scenario=scenario.name,
+ tokens_original=original_tokens,
+ tokens_after=trunc_tokens,
+ compression_ratio=1 - (trunc_tokens / original_tokens),
+ compression_latency_ms=trunc_latency,
+ llm_cost_usd=0.0, # No LLM for compression
+ answers=trunc_answers,
+ accuracy=trunc_accuracy,
+ total_cost_usd=trunc_query_cost,
+ )
+ )
+ print(
+ f" Tokens: {original_tokens} → {trunc_tokens} ({results[-1].compression_ratio:.1%} reduction)"
+ )
+ print(f" Accuracy: {trunc_accuracy:.1%}")
+
+ # --- SUMMARIZATION ---
+ if config.run_summarization:
+ print("\n[2/4] Running Summarization...")
+ try:
+ summary, summ_cost, summ_latency = summarize_data(scenario.data, client, config.model)
+ summ_tokens = count_tokens(summary)
+
+ summ_answers = []
+ summ_query_cost = 0.0
+ for q in scenario.questions:
+ answer, cost = query_llm(client, summary, q.text, config.model)
+ correct = evaluate_answer(q, answer)
+ summ_answers.append(
+ {
+ "question": q.text,
+ "expected": q.ground_truth,
+ "actual": answer,
+ "correct": correct,
+ "location": q.answer_location,
+ }
+ )
+ summ_query_cost += cost
+
+ summ_accuracy = sum(1 for a in summ_answers if a["correct"]) / len(summ_answers)
+
+ results.append(
+ ApproachResult(
+ approach="summarization",
+ scenario=scenario.name,
+ tokens_original=original_tokens,
+ tokens_after=summ_tokens,
+ compression_ratio=1 - (summ_tokens / original_tokens),
+ compression_latency_ms=summ_latency,
+ llm_cost_usd=summ_cost,
+ answers=summ_answers,
+ accuracy=summ_accuracy,
+ total_cost_usd=summ_cost + summ_query_cost,
+ )
+ )
+ print(
+ f" Tokens: {original_tokens} → {summ_tokens} ({results[-1].compression_ratio:.1%} reduction)"
+ )
+ print(f" Accuracy: {summ_accuracy:.1%}")
+ print(f" Summarization cost: ${summ_cost:.4f}")
+ except Exception as e:
+ print(f" Summarization failed: {e}")
+
+ # --- LLMLINGUA-2 (SOTA) ---
+ if config.run_llmlingua:
+ print("\n[3/4] Running LLMLingua-2 (Microsoft SOTA)...")
+ if LLMLINGUA_AVAILABLE:
+ try:
+ ll_compressed, ll_metadata = llmlingua_compress(scenario.data)
+ ll_tokens = count_tokens(ll_compressed)
+
+ ll_answers = []
+ ll_query_cost = 0.0
+ for q in scenario.questions:
+ answer, cost = query_llm(client, ll_compressed, q.text, config.model)
+ correct = evaluate_answer(q, answer)
+ ll_answers.append(
+ {
+ "question": q.text,
+ "expected": q.ground_truth,
+ "actual": answer,
+ "correct": correct,
+ "location": q.answer_location,
+ }
+ )
+ ll_query_cost += cost
+
+ ll_accuracy = sum(1 for a in ll_answers if a["correct"]) / len(ll_answers)
+
+ results.append(
+ ApproachResult(
+ approach="llmlingua-2",
+ scenario=scenario.name,
+ tokens_original=original_tokens,
+ tokens_after=ll_tokens,
+ compression_ratio=1 - (ll_tokens / original_tokens),
+ compression_latency_ms=ll_metadata["latency_ms"],
+ llm_cost_usd=0.0, # Model runs locally
+ answers=ll_answers,
+ accuracy=ll_accuracy,
+ total_cost_usd=ll_query_cost,
+ )
+ )
+ print(
+ f" Tokens: {original_tokens} → {ll_tokens} ({results[-1].compression_ratio:.1%} reduction)"
+ )
+ print(f" Accuracy: {ll_accuracy:.1%}")
+ print(f" Compression latency: {ll_metadata['latency_ms']:.1f}ms")
+ except Exception as e:
+ print(f" LLMLingua-2 failed: {e}")
+ else:
+ print(" LLMLingua-2 not available. Install with: pip install headroom-ai[llmlingua]")
+
+ # --- HEADROOM ---
+ print("\n[4/4] Running Headroom...")
+ if HEADROOM_AVAILABLE:
+ try:
+ # Use first question as query context (realistic usage)
+ query_context = scenario.questions[0].text if scenario.questions else ""
+ compressed, metadata = headroom_compress(scenario.data, query_context)
+
+ hr_json = (
+ json.dumps(compressed, indent=2)
+ if isinstance(compressed, list)
+ else str(compressed)
+ )
+ hr_tokens = count_tokens(hr_json)
+
+ hr_answers = []
+ hr_query_cost = 0.0
+ for q in scenario.questions:
+ answer, cost = query_llm(client, hr_json, q.text, config.model)
+ correct = evaluate_answer(q, answer)
+ hr_answers.append(
+ {
+ "question": q.text,
+ "expected": q.ground_truth,
+ "actual": answer,
+ "correct": correct,
+ "location": q.answer_location,
+ }
+ )
+ hr_query_cost += cost
+
+ hr_accuracy = sum(1 for a in hr_answers if a["correct"]) / len(hr_answers)
+
+ results.append(
+ ApproachResult(
+ approach="headroom",
+ scenario=scenario.name,
+ tokens_original=original_tokens,
+ tokens_after=hr_tokens,
+ compression_ratio=1 - (hr_tokens / original_tokens),
+ compression_latency_ms=metadata["latency_ms"],
+ llm_cost_usd=0.0, # No LLM for compression
+ answers=hr_answers,
+ accuracy=hr_accuracy,
+ total_cost_usd=hr_query_cost,
+ )
+ )
+ print(
+ f" Tokens: {original_tokens} → {hr_tokens} ({results[-1].compression_ratio:.1%} reduction)"
+ )
+ print(f" Accuracy: {hr_accuracy:.1%}")
+ print(f" Compression latency: {metadata['latency_ms']:.1f}ms")
+ except Exception as e:
+ print(f" Headroom failed: {e}")
+ import traceback
+
+ traceback.print_exc()
+ else:
+ print(" Headroom not available")
+
+ return results
+
+
+def run_full_benchmark(client: "OpenAI", config: BenchmarkConfig = None) -> dict:
+ """Run the complete benchmark suite."""
+
+ if config is None:
+ config = BenchmarkConfig()
+
+ print("\n" + "=" * 70)
+ print("TRUNCATION vs SUMMARIZATION vs LLMLINGUA-2 vs HEADROOM BENCHMARK")
+ print("=" * 70)
+
+ # Generate scenarios
+ scenarios = []
+
+ # Scenario 1: Logs (Headroom should win - needs anomaly detection)
+ logs, log_questions = generate_log_data(500, error_positions=[3, 250, 495])
+ scenarios.append(
+ Scenario(
+ name="Server Logs (500 entries)",
+ description="Find errors buried in routine logs",
+ data=logs,
+ questions=log_questions,
+ expected_winner="headroom",
+ )
+ )
+
+ # Scenario 2: File Search (Mixed - depends on file position)
+ files, file_questions = generate_file_search_data(1000)
+ scenarios.append(
+ Scenario(
+ name="Code Search (1000 files)",
+ description="Find specific files in search results",
+ data=files,
+ questions=file_questions,
+ expected_winner="mixed",
+ )
+ )
+
+ # Scenario 3: Metrics (Headroom should win - statistical outliers)
+ metrics, metric_questions = generate_metrics_data(500)
+ scenarios.append(
+ Scenario(
+ name="Time Series Metrics (500 points)",
+ description="Find anomalies in metrics data",
+ data=metrics,
+ questions=metric_questions,
+ expected_winner="headroom",
+ )
+ )
+
+ all_results = []
+ for scenario in scenarios:
+ results = run_scenario_benchmark(scenario, client, config)
+ all_results.extend(results)
+
+ # Generate summary
+ print("\n" + "=" * 70)
+ print("BENCHMARK SUMMARY")
+ print("=" * 70)
+
+ summary = generate_summary(all_results, scenarios)
+ print(summary)
+
+ return {
+ "results": [r.__dict__ for r in all_results],
+ "summary": summary,
+ "scenarios": [s.name for s in scenarios],
+ }
+
+
+def generate_summary(results: list[ApproachResult], scenarios: list[Scenario]) -> str:
+ """Generate a human-readable summary of results."""
+
+ lines = []
+
+ # Per-scenario breakdown
+ for scenario in scenarios:
+ lines.append(f"\n### {scenario.name}")
+ lines.append(f"Expected winner: {scenario.expected_winner}")
+ lines.append("")
+ lines.append("| Approach | Compression | Accuracy | Cost |")
+ lines.append("|----------|-------------|----------|------|")
+
+ scenario_results = [r for r in results if r.scenario == scenario.name]
+ for r in scenario_results:
+ lines.append(
+ f"| {r.approach} | {r.compression_ratio:.1%} | {r.accuracy:.1%} | ${r.total_cost_usd:.4f} |"
+ )
+
+ # Determine actual winner
+ best = max(scenario_results, key=lambda r: (r.accuracy, r.compression_ratio))
+ lines.append(f"\n**Actual winner: {best.approach}** (accuracy: {best.accuracy:.1%})")
+
+ # Overall stats
+ lines.append("\n### Overall Statistics")
+
+ for approach in ["truncation", "summarization", "llmlingua-2", "headroom"]:
+ approach_results = [r for r in results if r.approach == approach]
+ if approach_results:
+ avg_compression = sum(r.compression_ratio for r in approach_results) / len(
+ approach_results
+ )
+ avg_accuracy = sum(r.accuracy for r in approach_results) / len(approach_results)
+ total_cost = sum(r.total_cost_usd for r in approach_results)
+ lines.append(f"\n**{approach.title()}**")
+ lines.append(f"- Avg compression: {avg_compression:.1%}")
+ lines.append(f"- Avg accuracy: {avg_accuracy:.1%}")
+ lines.append(f"- Total cost: ${total_cost:.4f}")
+
+ # Per-question-type analysis
+ lines.append("\n### Accuracy by Answer Location")
+ lines.append("(Where in the data is the answer?)")
+ lines.append("")
+
+ for location in ["early", "middle", "late", "scattered"]:
+ lines.append(f"\n**{location.title()} position:**")
+ for approach in ["truncation", "summarization", "llmlingua-2", "headroom"]:
+ approach_results = [r for r in results if r.approach == approach]
+ location_answers = []
+ for r in approach_results:
+ location_answers.extend([a for a in r.answers if a["location"] == location])
+ if location_answers:
+ correct = sum(1 for a in location_answers if a["correct"])
+ total = len(location_answers)
+ lines.append(f" - {approach}: {correct}/{total} ({correct / total:.1%})")
+
+ return "\n".join(lines)
+
+
+# =============================================================================
+# MAIN
+# =============================================================================
+
+if __name__ == "__main__":
+ import os
+
+ if not OPENAI_AVAILABLE:
+ print("OpenAI not available. Install with: pip install openai")
+ exit(1)
+
+ api_key = os.environ.get("OPENAI_API_KEY")
+ if not api_key:
+ print("Set OPENAI_API_KEY environment variable")
+ exit(1)
+
+ client = OpenAI(api_key=api_key)
+
+ config = BenchmarkConfig(
+ model="gpt-4o-mini",
+ max_truncate_items=20,
+ max_headroom_items=20,
+ run_summarization=True,
+ )
+
+ results = run_full_benchmark(client, config)
+
+ # Save results
+ with open("benchmark_results.json", "w") as f:
+ json.dump(results, f, indent=2, default=str)
+
+ print("\nResults saved to benchmark_results.json")
diff --git a/benchmarks/headroom_adversarial_benchmark.py b/benchmarks/headroom_adversarial_benchmark.py
new file mode 100644
index 000000000..89ea9fb2c
--- /dev/null
+++ b/benchmarks/headroom_adversarial_benchmark.py
@@ -0,0 +1,563 @@
+"""
+Headroom ADVERSARIAL Benchmark: True Worst Cases
+
+The previous "worst case" scenarios still had JSON structure.
+This benchmark tests TRUE adversarial cases:
+
+1. Dense prose - research papers, no structure
+2. Code diffs - every line matters, minimal redundancy
+3. Encrypted/random data - no patterns possible
+4. Tiny datasets - not enough data for statistics
+5. High-entropy unique content - no repeated patterns
+"""
+
+import hashlib
+import json
+import os
+import random
+import string
+from dataclasses import dataclass
+
+try:
+ from openai import OpenAI # noqa: F401
+
+ OPENAI_AVAILABLE = True
+except ImportError:
+ OPENAI_AVAILABLE = False
+
+try:
+ from headroom import HeadroomClient, OpenAIProvider
+
+ HEADROOM_AVAILABLE = True
+except ImportError:
+ HEADROOM_AVAILABLE = False
+
+
+# =============================================================================
+# ADVERSARIAL DATA GENERATORS
+# =============================================================================
+
+
+def generate_research_paper_excerpts(num_papers: int = 10) -> dict:
+ """
+ Dense academic text - every word carries meaning.
+ No JSON structure, no repetition, pure prose.
+ """
+ # Simulated research paper abstracts - dense, unique content
+ papers = []
+
+ topics = [
+ ("quantum computing", "qubit coherence", "error correction", "topological"),
+ ("machine learning", "transformer architecture", "attention mechanism", "gradient"),
+ ("climate science", "carbon sequestration", "permafrost", "albedo effect"),
+ ("neuroscience", "synaptic plasticity", "hippocampal", "neurogenesis"),
+ ("economics", "monetary policy", "inflation targeting", "yield curve"),
+ ("genetics", "CRISPR-Cas9", "gene expression", "epigenetic"),
+ ("astrophysics", "gravitational waves", "neutron star", "black hole merger"),
+ ("materials science", "graphene", "superconductivity", "metamaterial"),
+ ("cryptography", "post-quantum", "lattice-based", "homomorphic encryption"),
+ ("pharmacology", "receptor binding", "pharmacokinetics", "bioavailability"),
+ ]
+
+ for i in range(num_papers):
+ topic = topics[i % len(topics)]
+
+ # Generate unique, dense academic prose
+ abstract = f"""
+This paper presents novel findings in {topic[0]} research, specifically addressing the challenge of {topic[1]} optimization.
+Our methodology employs a combination of {topic[2]} analysis and {topic[3]} modeling approaches that have not been
+previously explored in the literature. Through rigorous experimentation with {random.randint(50, 500)} samples
+across {random.randint(3, 12)} controlled conditions, we demonstrate a {random.randint(15, 45)}% improvement
+over baseline methods (p < 0.{random.randint(1, 5):02d}).
+
+The theoretical framework builds upon the seminal work of {random.choice(["Smith et al.", "Johnson & Lee", "Chen group", "Williams lab"])} (20{random.randint(15, 23)}),
+extending their {random.choice(["analytical", "computational", "experimental", "theoretical"])} approach to address
+{random.choice(["scalability concerns", "edge cases", "real-world constraints", "noise sensitivity"])}.
+Our key contribution is the development of a {random.choice(["novel algorithm", "unified framework", "hybrid methodology", "robust protocol"])}
+that achieves {random.choice(["state-of-the-art", "competitive", "superior", "breakthrough"])} performance while
+maintaining {random.choice(["computational efficiency", "interpretability", "generalizability", "reproducibility"])}.
+
+Implications of this work extend to {random.choice(["industrial applications", "clinical settings", "policy decisions", "fundamental understanding"])}
+in the domain of {topic[0]}. We identify {random.randint(3, 7)} key factors that influence {topic[1]} behavior,
+with {random.choice(["temperature", "pressure", "concentration", "frequency", "duration"])} being the most significant
+(correlation coefficient r = 0.{random.randint(70, 95)}). Future work will focus on {random.choice(["scaling", "optimizing", "validating", "extending"])}
+these findings to {random.choice(["larger systems", "different domains", "real-world deployment", "clinical trials"])}.
+""".strip()
+
+ papers.append(
+ {
+ "paper_id": f"arxiv:{random.randint(2000, 2400)}.{random.randint(10000, 99999)}",
+ "title": f"Advances in {topic[0].title()}: A {random.choice(['Novel', 'Comprehensive', 'Systematic', 'Rigorous'])} Approach to {topic[1].title()}",
+ "authors": [f"Author{j}" for j in range(random.randint(2, 6))],
+ "abstract": abstract,
+ "year": random.randint(2022, 2024),
+ "citations": random.randint(0, 150),
+ }
+ )
+
+ # Return as plain text, not JSON structure
+ output = "RESEARCH PAPER SEARCH RESULTS\n" + "=" * 50 + "\n\n"
+ for p in papers:
+ output += f"[{p['paper_id']}] {p['title']}\n"
+ output += f"Authors: {', '.join(p['authors'])} ({p['year']})\n"
+ output += f"Citations: {p['citations']}\n\n"
+ output += p["abstract"] + "\n\n"
+ output += "-" * 50 + "\n\n"
+
+ return {
+ "tool": "research_search",
+ "result": output, # Plain text, not JSON!
+ }
+
+
+def generate_code_diff(num_files: int = 15, changes_per_file: int = 20) -> dict:
+ """
+ Git diff output - every line is unique and important.
+ Can't summarize code changes - need exact lines.
+ """
+ languages = {
+ "py": (
+ "def ",
+ "class ",
+ "import ",
+ "return ",
+ "if ",
+ "for ",
+ "while ",
+ "try:",
+ "except:",
+ "with ",
+ ),
+ "ts": (
+ "function ",
+ "const ",
+ "interface ",
+ "import ",
+ "export ",
+ "return ",
+ "if ",
+ "for ",
+ "async ",
+ "await ",
+ ),
+ "go": (
+ "func ",
+ "type ",
+ "import ",
+ "return ",
+ "if ",
+ "for ",
+ "defer ",
+ "go ",
+ "chan ",
+ "struct ",
+ ),
+ "rs": (
+ "fn ",
+ "struct ",
+ "impl ",
+ "use ",
+ "let ",
+ "match ",
+ "if ",
+ "for ",
+ "pub ",
+ "async ",
+ ),
+ }
+
+ diff_output = ""
+
+ for file_idx in range(num_files):
+ ext = random.choice(list(languages.keys()))
+ keywords = languages[ext]
+ filename = f"src/module_{file_idx}/handler.{ext}"
+
+ diff_output += f"diff --git a/{filename} b/{filename}\n"
+ diff_output += f"index {hashlib.md5(f'{file_idx}a'.encode()).hexdigest()[:7]}..{hashlib.md5(f'{file_idx}b'.encode()).hexdigest()[:7]} 100644\n"
+ diff_output += f"--- a/{filename}\n"
+ diff_output += f"+++ b/{filename}\n"
+
+ line_num = random.randint(10, 50)
+ for change_idx in range(changes_per_file):
+ # Generate realistic code changes
+ keyword = random.choice(keywords)
+ var_name = f"{''.join(random.choices(string.ascii_lowercase, k=random.randint(4, 10)))}"
+ value = random.randint(1, 1000)
+
+ diff_output += (
+ f"@@ -{line_num},{random.randint(3, 7)} +{line_num},{random.randint(3, 7)} @@\n"
+ )
+
+ # Context line
+ diff_output += f" {random.choice(keywords)}{var_name}_{change_idx}()\n"
+
+ # Removed line
+ old_impl = f"{keyword}{var_name} = {value}"
+ diff_output += f"- {old_impl}\n"
+
+ # Added line (different)
+ new_impl = f"{keyword}{var_name} = {value + random.randint(1, 100)}"
+ diff_output += f"+ {new_impl}\n"
+
+ # More context
+ diff_output += f" {random.choice(keywords)}{var_name}_next()\n"
+
+ line_num += random.randint(10, 30)
+
+ diff_output += "\n"
+
+ return {
+ "tool": "git_diff",
+ "result": diff_output, # Plain text diff
+ }
+
+
+def generate_encrypted_data(size_kb: int = 20) -> dict:
+ """
+ Base64 encoded / encrypted content - NO patterns possible.
+ This is the ultimate adversarial case for compression.
+ """
+ # Generate random bytes and base64 encode
+ random_bytes = bytes([random.randint(0, 255) for _ in range(size_kb * 1024)])
+ import base64
+
+ encoded = base64.b64encode(random_bytes).decode("ascii")
+
+ return {
+ "tool": "encrypted_blob",
+ "result": {
+ "blob_id": f"enc_{hashlib.md5(encoded[:100].encode()).hexdigest()[:16]}",
+ "encryption": "AES-256-GCM",
+ "content": encoded,
+ "size_bytes": len(random_bytes),
+ },
+ }
+
+
+def generate_tiny_dataset(num_items: int = 5) -> dict:
+ """
+ Very small dataset - not enough data for statistical patterns.
+ """
+ items = []
+ for i in range(num_items):
+ items.append(
+ {
+ "id": i + 1,
+ "name": f"Item {chr(65 + i)}",
+ "value": random.randint(100, 999),
+ "note": f"Unique note for item {i + 1}: {hashlib.md5(str(i).encode()).hexdigest()[:20]}",
+ }
+ )
+
+ return {"tool": "tiny_query", "result": {"count": num_items, "items": items}}
+
+
+def generate_conversation_history(num_messages: int = 50) -> dict:
+ """
+ Chat conversation - context and flow matter, not just content.
+ Each message builds on previous, can't remove context.
+ """
+ participants = ["Alice", "Bob", "Charlie", "Diana"]
+
+ messages = []
+ topics = [
+ "the quarterly review",
+ "the product launch",
+ "the customer feedback",
+ "the technical debt",
+ "the team restructuring",
+ ]
+ current_topic = random.choice(topics)
+
+ for i in range(num_messages):
+ sender = participants[i % len(participants)]
+
+ # Change topic occasionally
+ if random.random() < 0.1:
+ current_topic = random.choice(topics)
+
+ # Generate contextual message
+ message_templates = [
+ f"I think we need to reconsider {current_topic}. The data shows {random.choice(['promising', 'concerning', 'mixed'])} results.",
+ f"Building on what {participants[(i - 1) % len(participants)]} said, I'd add that {random.choice(['timing', 'resources', 'alignment'])} is crucial here.",
+ f"Let me share some context: when we discussed {current_topic} last month, we agreed on {random.choice(['three priorities', 'a phased approach', 'immediate action'])}.",
+ f"I disagree with the previous point. {current_topic.title()} requires {random.choice(['more analysis', 'quick action', 'stakeholder buy-in'])} first.",
+ f"To summarize so far: we've covered {random.choice(['the risks', 'the opportunities', 'the constraints'])} of {current_topic}. Next steps?",
+ f"Quick question about {current_topic}: have we considered {random.choice(['the budget impact', 'customer perception', 'timeline feasibility'])}?",
+ f"I can take the action item on {current_topic}. Will need input from {random.choice(participants)} by {random.choice(['EOD', 'tomorrow', 'Friday'])}.",
+ ]
+
+ messages.append(
+ {
+ "timestamp": f"2024-01-17T{10 + (i // 10):02d}:{(i * 2) % 60:02d}:00Z",
+ "sender": sender,
+ "message": random.choice(message_templates),
+ }
+ )
+
+ # Format as conversation transcript
+ transcript = "MEETING TRANSCRIPT\n" + "=" * 50 + "\n\n"
+ for msg in messages:
+ transcript += f"[{msg['timestamp']}] {msg['sender']}:\n"
+ transcript += f" {msg['message']}\n\n"
+
+ return {"tool": "meeting_transcript", "result": transcript}
+
+
+# =============================================================================
+# ADVERSARIAL SCENARIOS
+# =============================================================================
+
+
+@dataclass
+class AdversarialScenario:
+ name: str
+ description: str
+ why_adversarial: str
+ system_prompt: str
+ user_query: str
+ tools: list[dict]
+ expected_behavior: str # What we expect to happen
+
+
+def create_research_synthesis_scenario() -> AdversarialScenario:
+ return AdversarialScenario(
+ name="Research Paper Synthesis",
+ description="Synthesize findings from 10 research papers",
+ why_adversarial="Dense academic prose with no structural repetition. Every sentence carries unique meaning. No JSON overhead to compress.",
+ system_prompt="""You are a research assistant synthesizing academic papers.
+Each paper's findings are important. Don't skip any paper.
+Focus on methodology differences and key findings.""",
+ user_query="Synthesize these research papers. For each paper, summarize the key methodology and findings. Then identify common themes and contradictions across papers.",
+ tools=[generate_research_paper_excerpts(num_papers=10)],
+ expected_behavior="Headroom should have minimal compression - prose has no structural redundancy",
+ )
+
+
+def create_code_review_scenario() -> AdversarialScenario:
+ return AdversarialScenario(
+ name="Code Diff Review",
+ description="Review a large code diff across 15 files",
+ why_adversarial="Git diffs have minimal redundancy. Each +/- line is unique code. Can't summarize - reviewer needs exact changes.",
+ system_prompt="""You are a senior engineer reviewing a pull request.
+Every changed line matters. Look for bugs, style issues, and potential problems.
+Don't skip any file or change.""",
+ user_query="Review this diff carefully. For each file, identify: 1) What changed, 2) Any bugs or issues, 3) Style concerns. Be thorough.",
+ tools=[generate_code_diff(num_files=15, changes_per_file=20)],
+ expected_behavior="Headroom should struggle - code changes are unique and can't be summarized",
+ )
+
+
+def create_encrypted_analysis_scenario() -> AdversarialScenario:
+ return AdversarialScenario(
+ name="Encrypted Data Analysis",
+ description="Analyze encrypted/encoded data blob",
+ why_adversarial="Random/encrypted data has maximum entropy. No patterns exist to compress. This is mathematically incompressible.",
+ system_prompt="""You are a data analyst examining an encrypted data blob.
+Describe what you observe about the data format and structure.""",
+ user_query="Examine this encrypted data blob. What can you tell about its format? Is there any visible structure? What's the encoding?",
+ tools=[generate_encrypted_data(size_kb=20)],
+ expected_behavior="Headroom CANNOT compress this - random data has no patterns",
+ )
+
+
+def create_small_data_scenario() -> AdversarialScenario:
+ return AdversarialScenario(
+ name="Tiny Dataset Analysis",
+ description="Analyze a very small dataset (5 items)",
+ why_adversarial="Too little data for statistical analysis. No patterns emerge with only 5 samples.",
+ system_prompt="""You are a data analyst. Analyze this small dataset.""",
+ user_query="What patterns do you see in this data? Provide summary statistics and insights.",
+ tools=[generate_tiny_dataset(num_items=5)],
+ expected_behavior="Headroom has no opportunity - data is already minimal",
+ )
+
+
+def create_conversation_context_scenario() -> AdversarialScenario:
+ return AdversarialScenario(
+ name="Meeting Context Analysis",
+ description="Summarize a 50-message meeting transcript",
+ why_adversarial="Conversation requires context. Each message builds on previous ones. Removing messages loses the thread.",
+ system_prompt="""You are a meeting analyst. The conversation flow and context matters.
+Pay attention to who said what and how opinions evolved.""",
+ user_query="Summarize this meeting. Who took which positions? How did the discussion evolve? What were the action items and who owns them?",
+ tools=[generate_conversation_history(num_messages=50)],
+ expected_behavior="Headroom should preserve conversation flow - context matters",
+ )
+
+
+# =============================================================================
+# BENCHMARK RUNNER
+# =============================================================================
+
+
+@dataclass
+class BenchmarkResult:
+ scenario_name: str
+ mode: str
+ input_tokens: int
+ output_tokens: int
+ cost_usd: float
+ raw_tool_size: int
+ compression_ratio: float
+
+
+def run_scenario(
+ client, scenario: AdversarialScenario, mode: str, model: str = "gpt-4o-mini"
+) -> BenchmarkResult:
+ messages = [
+ {"role": "system", "content": scenario.system_prompt},
+ {"role": "user", "content": scenario.user_query},
+ ]
+
+ # Calculate raw tool output size
+ raw_size = 0
+ for tool_output in scenario.tools:
+ result = tool_output["result"]
+ if isinstance(result, str):
+ raw_size += len(result)
+ else:
+ raw_size += len(json.dumps(result))
+
+ # Add tool results
+ for tool_output in scenario.tools:
+ tool_call_id = f"call_{hashlib.md5(tool_output['tool'].encode()).hexdigest()[:8]}"
+ messages.append(
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": tool_call_id,
+ "type": "function",
+ "function": {"name": tool_output["tool"], "arguments": "{}"},
+ }
+ ],
+ }
+ )
+
+ content = tool_output["result"]
+ if not isinstance(content, str):
+ content = json.dumps(content, indent=2)
+
+ messages.append({"role": "tool", "tool_call_id": tool_call_id, "content": content})
+
+ messages.append({"role": "user", "content": "Please provide your analysis."})
+
+ try:
+ response = client.chat.completions.create(model=model, messages=messages, max_tokens=2000)
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = (input_tokens * 0.00015 + output_tokens * 0.0006) / 1000
+ compression_ratio = 1 - (input_tokens / (raw_size / 4)) if raw_size > 0 else 0
+
+ except Exception as e:
+ print(f" Error: {e}")
+ return BenchmarkResult(scenario.name, mode, 0, 0, 0, raw_size, 0)
+
+ return BenchmarkResult(
+ scenario.name, mode, input_tokens, output_tokens, cost, raw_size, compression_ratio
+ )
+
+
+def run_adversarial_benchmark(api_key: str = None) -> dict:
+ if api_key is None:
+ api_key = os.environ.get("OPENAI_API_KEY")
+ if not api_key:
+ raise ValueError("OPENAI_API_KEY required")
+
+ print("=" * 70)
+ print("HEADROOM ADVERSARIAL BENCHMARK")
+ print("Testing TRUE worst cases for compression")
+ print("=" * 70)
+
+ import tempfile
+
+ from openai import OpenAI
+
+ baseline_client = OpenAI(api_key=api_key)
+
+ if HEADROOM_AVAILABLE:
+ db_path = os.path.join(tempfile.gettempdir(), "headroom_adversarial.db")
+ headroom_client = HeadroomClient(
+ original_client=OpenAI(api_key=api_key),
+ provider=OpenAIProvider(),
+ store_url=f"sqlite:///{db_path}",
+ default_mode="optimize",
+ )
+ else:
+ headroom_client = None
+
+ scenarios = [
+ create_research_synthesis_scenario(),
+ create_code_review_scenario(),
+ create_encrypted_analysis_scenario(),
+ create_small_data_scenario(),
+ create_conversation_context_scenario(),
+ ]
+
+ results = []
+
+ for scenario in scenarios:
+ print(f"\n{'=' * 60}")
+ print(f"Scenario: {scenario.name}")
+ print(f"WHY ADVERSARIAL: {scenario.why_adversarial}")
+ print(f"Expected: {scenario.expected_behavior}")
+ print("=" * 60)
+
+ # Baseline
+ print("\n[1/2] BASELINE...")
+ baseline = run_scenario(baseline_client, scenario, "baseline")
+ print(
+ f" Raw data: ~{baseline.raw_tool_size:,} chars ({baseline.raw_tool_size // 4:,} est. tokens)"
+ )
+ print(f" Input tokens: {baseline.input_tokens:,}")
+ print(f" Cost: ${baseline.cost_usd:.4f}")
+ results.append(baseline)
+
+ # Headroom
+ if headroom_client:
+ print("\n[2/2] HEADROOM...")
+ headroom = run_scenario(headroom_client, scenario, "headroom")
+ print(f" Input tokens: {headroom.input_tokens:,}")
+ print(f" Cost: ${headroom.cost_usd:.4f}")
+ results.append(headroom)
+
+ if baseline.input_tokens > 0:
+ change = (headroom.input_tokens - baseline.input_tokens) / baseline.input_tokens
+ print(f"\n 📊 Token change: {change:+.1%}")
+ if change > 0:
+ print(" ⚠️ HEADROOM INCREASED TOKENS (overhead > savings)")
+ elif change > -0.1:
+ print(" ⚡ Minimal compression (as expected for adversarial data)")
+ else:
+ print(" ✓ Still found patterns to compress")
+
+ # Summary
+ print("\n" + "=" * 70)
+ print("ADVERSARIAL BENCHMARK SUMMARY")
+ print("=" * 70)
+
+ print(f"\n{'Scenario':<30} {'Baseline':>12} {'Headroom':>12} {'Change':>12}")
+ print("-" * 66)
+
+ baseline_results = [r for r in results if r.mode == "baseline"]
+ headroom_results = [r for r in results if r.mode == "headroom"]
+
+ for br in baseline_results:
+ hr = next((r for r in headroom_results if r.scenario_name == br.scenario_name), None)
+ if hr and br.input_tokens > 0:
+ change = (hr.input_tokens - br.input_tokens) / br.input_tokens
+ print(
+ f"{br.scenario_name:<30} {br.input_tokens:>12,} {hr.input_tokens:>12,} {change:>+11.1%}"
+ )
+
+ return {"results": [r.__dict__ for r in results]}
+
+
+if __name__ == "__main__":
+ results = run_adversarial_benchmark()
+ with open("adversarial_benchmark_results.json", "w") as f:
+ json.dump(results, f, indent=2)
+ print("\nResults saved to adversarial_benchmark_results.json")
diff --git a/benchmarks/headroom_worst_case_benchmark.py b/benchmarks/headroom_worst_case_benchmark.py
new file mode 100644
index 000000000..c441787e1
--- /dev/null
+++ b/benchmarks/headroom_worst_case_benchmark.py
@@ -0,0 +1,864 @@
+"""
+Headroom Worst-Case Benchmark: Where Compression Hurts
+
+This benchmark tests scenarios where Headroom's statistical compression
+may NOT be beneficial - to understand the limits of the approach.
+
+Worst cases for Headroom:
+1. Highly unique data (no patterns to compress)
+2. Data where every item is equally important
+3. Data where subtle differences matter
+4. Small datasets (not enough data for statistics)
+5. Data where you need EXACT recall (audit/legal)
+"""
+
+import hashlib
+import json
+import os
+import random
+import time
+from dataclasses import dataclass
+from typing import Any
+
+try:
+ from openai import OpenAI # noqa: F401
+
+ OPENAI_AVAILABLE = True
+except ImportError:
+ OPENAI_AVAILABLE = False
+
+try:
+ from headroom import HeadroomClient, OpenAIProvider
+
+ HEADROOM_AVAILABLE = True
+except ImportError:
+ HEADROOM_AVAILABLE = False
+
+
+# =============================================================================
+# WORST-CASE DATA GENERATORS
+# =============================================================================
+
+
+def generate_unique_support_tickets(num_tickets: int = 50) -> dict:
+ """
+ Customer support tickets where EVERY ticket is unique and important.
+ No redundancy - each customer has a different problem.
+
+ This is hard for Headroom because:
+ - No repeated patterns to compress
+ - Every ticket needs attention
+ - Can't safely remove any ticket
+ """
+ products = ["Pro Plan", "Enterprise", "Starter", "Team", "Individual"]
+ issues = [
+ "billing discrepancy of ${amount} on invoice #{inv}",
+ "cannot access feature '{feature}' despite paying for it",
+ "data export failing with error code {code}",
+ "SSO integration with {provider} not working",
+ "API rate limits hitting at {rate}/min instead of promised {expected}/min",
+ "webhook deliveries delayed by {hours} hours",
+ "user {user} locked out after password reset",
+ "mobile app crashing on {device} with iOS {version}",
+ "search returning wrong results for query '{query}'",
+ "file upload stuck at {percent}% for files over {size}MB",
+ "notification emails going to spam for domain {domain}",
+ "timezone showing {wrong_tz} instead of {correct_tz}",
+ "dashboard metrics {days} days out of date",
+ "cannot downgrade from {from_plan} to {to_plan}",
+ "GDPR data deletion request not completing for user {user_id}",
+ ]
+
+ severities = ["critical", "high", "medium", "low"]
+
+ tickets = []
+ for i in range(num_tickets):
+ # Each ticket is genuinely unique
+ issue_template = issues[i % len(issues)]
+ issue = issue_template.format(
+ amount=random.randint(50, 5000),
+ inv=random.randint(10000, 99999),
+ feature=random.choice(
+ ["advanced analytics", "custom domains", "API access", "SSO", "audit logs"]
+ ),
+ code=f"ERR_{random.randint(1000, 9999)}",
+ provider=random.choice(["Okta", "Azure AD", "Google Workspace", "OneLogin"]),
+ rate=random.randint(100, 500),
+ expected=random.randint(1000, 5000),
+ hours=random.randint(1, 48),
+ user=f"user_{random.randint(1000, 9999)}@company{random.randint(1, 100)}.com",
+ device=random.choice(["iPhone 15", "iPhone 14", "iPad Pro", "iPhone 13"]),
+ version=random.choice(["17.2", "17.1", "16.5", "16.4"]),
+ query=random.choice(
+ ["quarterly report", "user metrics", "revenue data", "team performance"]
+ ),
+ percent=random.randint(45, 95),
+ size=random.randint(10, 500),
+ domain=f"company{random.randint(1, 500)}.com",
+ wrong_tz=random.choice(["UTC", "PST", "EST"]),
+ correct_tz=random.choice(["CET", "JST", "IST"]),
+ days=random.randint(2, 14),
+ from_plan=random.choice(["Enterprise", "Pro"]),
+ to_plan=random.choice(["Starter", "Team"]),
+ user_id=f"usr_{hashlib.md5(str(i).encode()).hexdigest()[:8]}",
+ )
+
+ tickets.append(
+ {
+ "ticket_id": f"TKT-{20000 + i}",
+ "customer": {
+ "id": f"cust_{hashlib.md5(f'customer{i}'.encode()).hexdigest()[:8]}",
+ "name": f"Customer {i + 1}",
+ "company": f"Company {chr(65 + (i % 26))}{i // 26 + 1} Inc.",
+ "plan": random.choice(products),
+ "mrr": random.randint(99, 9999),
+ "account_age_days": random.randint(30, 1500),
+ },
+ "issue": issue,
+ "severity": random.choice(severities),
+ "created_at": f"2024-01-{random.randint(10, 17):02d}T{random.randint(0, 23):02d}:{random.randint(0, 59):02d}:00Z",
+ "last_response": f"2024-01-{random.randint(15, 17):02d}T{random.randint(0, 23):02d}:{random.randint(0, 59):02d}:00Z",
+ "response_count": random.randint(1, 8),
+ "tags": random.sample(
+ ["billing", "technical", "feature-request", "bug", "urgent", "escalated"],
+ k=random.randint(1, 3),
+ ),
+ "assignee": None, # Unassigned - needs triage
+ }
+ )
+
+ return {
+ "tool": "support_queue",
+ "result": {"queue": "unassigned", "total_tickets": num_tickets, "tickets": tickets},
+ }
+
+
+def generate_unique_error_traces(num_traces: int = 30) -> dict:
+ """
+ Unique stack traces where each error is different.
+
+ This is hard for Headroom because:
+ - Each stack trace has different functions, line numbers
+ - Each error message is unique
+ - All errors need investigation
+ """
+ languages = ["python", "javascript", "go", "java"]
+
+ traces = []
+ for i in range(num_traces):
+ lang = random.choice(languages)
+
+ if lang == "python":
+ trace = generate_python_trace(i)
+ elif lang == "javascript":
+ trace = generate_js_trace(i)
+ elif lang == "go":
+ trace = generate_go_trace(i)
+ else:
+ trace = generate_java_trace(i)
+
+ traces.append(
+ {
+ "error_id": f"err_{hashlib.md5(str(i).encode()).hexdigest()[:12]}",
+ "timestamp": f"2024-01-17T{10 + (i % 12):02d}:{(i * 7) % 60:02d}:00Z",
+ "service": random.choice(["api", "worker", "scheduler", "gateway"]),
+ "environment": "production",
+ "language": lang,
+ "error_type": trace["error_type"],
+ "message": trace["message"],
+ "stack_trace": trace["stack"],
+ "context": {
+ "user_id": f"user_{random.randint(10000, 99999)}",
+ "request_id": hashlib.md5(f"req{i}".encode()).hexdigest()[:16],
+ "endpoint": trace.get("endpoint", "/api/unknown"),
+ },
+ "occurrence_count": random.randint(1, 5), # Low count - each is unique
+ }
+ )
+
+ return {
+ "tool": "error_tracker",
+ "result": {"time_range": "last_24h", "total_unique_errors": num_traces, "errors": traces},
+ }
+
+
+def generate_python_trace(seed: int) -> dict:
+ """Generate a unique Python stack trace."""
+ error_types = [
+ ("ValueError", f"Invalid value for parameter 'config_{seed}': expected int, got str"),
+ ("KeyError", f"'{random.choice(['user', 'account', 'session', 'token'])}_{seed}'"),
+ ("TypeError", f"unsupported operand type(s) for +: 'NoneType' and 'str' in field_{seed}"),
+ ("AttributeError", f"'NoneType' object has no attribute 'process_{seed}'"),
+ ("RuntimeError", f"Maximum recursion depth exceeded in handler_{seed}"),
+ ("ConnectionError", f"Connection refused to service_{seed}:8080"),
+ (
+ "TimeoutError",
+ f"Operation timed out after {random.randint(30, 120)}s waiting for resource_{seed}",
+ ),
+ ]
+
+ error_type, message = random.choice(error_types)
+
+ functions = [
+ f"process_request_{seed}",
+ f"validate_input_{seed % 10}",
+ f"transform_data_{seed}",
+ f"save_to_db_{seed % 5}",
+ f"send_notification_{seed}",
+ ]
+
+ stack_lines = []
+ for j, func in enumerate(random.sample(functions, k=random.randint(3, 5))):
+ line_no = random.randint(50, 500)
+ file_path = f"/app/services/module_{seed % 20}/{func.split('_')[0]}.py"
+ stack_lines.append(f' File "{file_path}", line {line_no}, in {func}')
+ stack_lines.append(f" result = self.handler_{j}(data)")
+
+ return {
+ "error_type": error_type,
+ "message": message,
+ "stack": "\n".join(stack_lines),
+ "endpoint": f"/api/v{random.randint(1, 3)}/{random.choice(['users', 'orders', 'products'])}/{seed}",
+ }
+
+
+def generate_js_trace(seed: int) -> dict:
+ """Generate a unique JavaScript stack trace."""
+ error_types = [
+ (
+ "TypeError",
+ f"Cannot read property '{random.choice(['map', 'filter', 'length', 'data'])}' of undefined",
+ ),
+ ("ReferenceError", f"config_{seed} is not defined"),
+ ("SyntaxError", f"Unexpected token in JSON at position {random.randint(100, 1000)}"),
+ ("RangeError", f"Maximum call stack size exceeded in recursive_{seed}"),
+ ]
+
+ error_type, message = random.choice(error_types)
+
+ stack = f""" at processData_{seed} (/app/src/handlers/processor_{seed % 10}.js:{random.randint(50, 200)}:15)
+ at async handleRequest_{seed} (/app/src/routes/api_{seed % 5}.js:{random.randint(20, 100)}:23)
+ at async Router.dispatch (/app/node_modules/express/router.js:142:12)
+ at async Layer.handle (/app/node_modules/express/layer.js:95:5)"""
+
+ return {
+ "error_type": error_type,
+ "message": message,
+ "stack": stack,
+ "endpoint": f"/api/{random.choice(['graphql', 'rest', 'webhook'])}/{seed}",
+ }
+
+
+def generate_go_trace(seed: int) -> dict:
+ """Generate a unique Go stack trace."""
+ error_types = [
+ ("panic", f"runtime error: index out of range [{seed}] with length {seed - 1}"),
+ ("panic", "runtime error: invalid memory address or nil pointer dereference"),
+ ("error", f"context deadline exceeded after {random.randint(5, 30)}s"),
+ ("error", f"connection refused to database_{seed % 3}:5432"),
+ ]
+
+ error_type, message = random.choice(error_types)
+
+ stack = f"""goroutine {random.randint(1, 100)} [running]:
+main.processHandler_{seed}(0xc0001{seed:04x}, 0x{random.randint(1000, 9999):x})
+ /app/internal/handlers/handler_{seed % 10}.go:{random.randint(50, 200)} +0x{random.randint(100, 999):x}
+main.(*Server).ServeHTTP_{seed}(0xc000{seed:04x}, 0x7f{random.randint(1000, 9999):x})
+ /app/internal/server/server.go:{random.randint(80, 150)} +0x{random.randint(100, 500):x}"""
+
+ return {
+ "error_type": error_type,
+ "message": message,
+ "stack": stack,
+ }
+
+
+def generate_java_trace(seed: int) -> dict:
+ """Generate a unique Java stack trace."""
+ error_types = [
+ ("NullPointerException", f"Cannot invoke method on null object in Service_{seed}"),
+ ("IllegalArgumentException", f"Parameter 'id_{seed}' cannot be negative"),
+ ("SQLException", f"Connection to database_{seed % 3} timed out"),
+ ("OutOfMemoryError", f"Java heap space exhausted processing batch_{seed}"),
+ ]
+
+ error_type, message = random.choice(error_types)
+
+ stack = f"""java.lang.{error_type}: {message}
+ at com.app.services.Handler{seed}.process(Handler{seed}.java:{random.randint(50, 200)})
+ at com.app.controllers.Api{seed % 10}Controller.handle(Api{seed % 10}Controller.java:{random.randint(30, 100)})
+ at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:897)
+ at javax.servlet.http.HttpServlet.service(HttpServlet.java:750)"""
+
+ return {
+ "error_type": error_type,
+ "message": message,
+ "stack": stack,
+ }
+
+
+def generate_medical_records(num_patients: int = 25) -> dict:
+ """
+ Medical records where EVERY detail matters.
+
+ This is hard for Headroom because:
+ - Similar symptoms can have different diagnoses
+ - Missing any detail could be dangerous
+ - "Repetitive" info (vitals) is actually critical data
+ """
+ conditions = [
+ "Type 2 Diabetes",
+ "Hypertension",
+ "Asthma",
+ "GERD",
+ "Anxiety Disorder",
+ "Hypothyroidism",
+ "Chronic Back Pain",
+ "Migraine",
+ "Allergic Rhinitis",
+ "Depression",
+ ]
+
+ medications = [
+ "Metformin 500mg",
+ "Lisinopril 10mg",
+ "Omeprazole 20mg",
+ "Albuterol inhaler",
+ "Sertraline 50mg",
+ "Levothyroxine 50mcg",
+ "Ibuprofen 400mg PRN",
+ "Sumatriptan 50mg PRN",
+ "Loratadine 10mg",
+ ]
+
+ records = []
+ for i in range(num_patients):
+ # Each patient has a unique combination of conditions, meds, vitals
+ patient_conditions = random.sample(conditions, k=random.randint(1, 4))
+ patient_meds = random.sample(medications, k=random.randint(1, 5))
+
+ # Vitals - these look "similar" but each patient's baseline is different
+ systolic = random.randint(110, 160)
+ diastolic = random.randint(70, 100)
+
+ records.append(
+ {
+ "patient_id": f"PT-{100000 + i}",
+ "name": f"Patient {chr(65 + (i % 26))}{chr(65 + ((i // 26) % 26))}",
+ "age": random.randint(25, 85),
+ "sex": random.choice(["M", "F"]),
+ "visit_date": f"2024-01-{random.randint(15, 17):02d}",
+ "chief_complaint": random.choice(
+ [
+ f"Chest pain radiating to left arm for {random.randint(1, 6)} hours",
+ f"Shortness of breath worsening over {random.randint(1, 14)} days",
+ "Severe headache, worst of life, sudden onset",
+ f"Abdominal pain, {random.choice(['RLQ', 'LLQ', 'epigastric'])}, {random.randint(1, 72)} hours",
+ f"Dizziness and {random.choice(['syncope', 'near-syncope'])} today",
+ f"Fever {random.randint(100, 104)}°F for {random.randint(1, 5)} days",
+ "Medication refill - stable on current regimen",
+ f"Follow-up for recent {random.choice(['hospitalization', 'procedure', 'diagnosis'])}",
+ ]
+ ),
+ "vitals": {
+ "bp": f"{systolic}/{diastolic}",
+ "hr": random.randint(60, 110),
+ "temp": round(random.uniform(97.5, 100.5), 1),
+ "resp": random.randint(12, 22),
+ "spo2": random.randint(94, 100),
+ },
+ "conditions": patient_conditions,
+ "medications": patient_meds,
+ "allergies": random.sample(
+ ["Penicillin", "Sulfa", "NSAIDs", "Latex", "None"], k=random.randint(1, 2)
+ ),
+ "notes": f"Patient presents with {random.choice(['acute', 'chronic', 'worsening', 'stable'])} symptoms. "
+ f"Last seen {random.randint(1, 12)} months ago. "
+ f"Compliance with medications: {random.choice(['good', 'fair', 'poor'])}. "
+ f"Social history: {random.choice(['non-smoker', 'former smoker', 'current smoker'])}, "
+ f"{random.choice(['no alcohol', 'occasional alcohol', 'daily alcohol'])}.",
+ }
+ )
+
+ return {
+ "tool": "ehr_query",
+ "result": {
+ "query": "today's patients",
+ "total_patients": num_patients,
+ "patients": records,
+ },
+ }
+
+
+def generate_legal_discovery_docs(num_docs: int = 40) -> dict:
+ """
+ Legal discovery documents where EVERY document must be reviewed.
+
+ This is hard for Headroom because:
+ - Can't skip any document - legal requirement
+ - "Similar" emails might have crucial differences
+ - Need exact quotes, not summaries
+ """
+ senders = [f"person{i}@company.com" for i in range(1, 20)]
+ subjects = [
+ "Re: Q4 projections discussion",
+ "Fw: Board meeting notes",
+ "Re: Re: Customer complaint handling",
+ "Meeting tomorrow",
+ "Urgent: Need your input",
+ "Re: Project timeline update",
+ "Fw: Legal review needed",
+ "Re: Re: Re: Budget approval",
+ "Quick question",
+ "Following up",
+ ]
+
+ docs = []
+ for i in range(num_docs):
+ sender = random.choice(senders)
+ recipient = random.choice([s for s in senders if s != sender])
+
+ # Each email has unique content that could be relevant
+ body_templates = [
+ f"As we discussed in the meeting on {random.randint(1, 28)}/{random.randint(1, 12)}, the numbers for Q{random.randint(1, 4)} show {random.choice(['concerning', 'promising', 'unexpected'])} trends. I think we should {random.choice(['proceed', 'hold off', 'reconsider'])} with the {random.choice(['merger', 'acquisition', 'expansion', 'restructuring'])} plan.",
+ f"I'm forwarding this because I think you should be aware. The customer in region {random.choice(['APAC', 'EMEA', 'Americas'])} has raised {random.choice(['serious', 'minor', 'recurring'])} concerns about our {random.choice(['pricing', 'service', 'product quality'])}. Can we discuss {random.choice(['today', 'tomorrow', 'this week'])}?",
+ f"Following up on your question - the {random.choice(['contract', 'agreement', 'terms'])} with {random.choice(['Vendor A', 'Vendor B', 'the client'])} does {random.choice(['', 'not '])}allow for {random.choice(['early termination', 'price adjustment', 'scope changes'])}. See clause {random.randint(1, 20)}.{random.randint(1, 9)}.",
+ f"Quick update: the {random.choice(['audit', 'review', 'investigation'])} team found {random.choice(['no issues', 'minor discrepancies', 'significant concerns'])} in the {random.choice(['financial records', 'compliance documents', 'HR files'])} for {random.choice(['Q1', 'Q2', 'Q3', 'Q4'])} {random.randint(2021, 2023)}.",
+ f"I need to flag something - the {random.choice(['employee', 'manager', 'director'])} in {random.choice(['sales', 'marketing', 'engineering'])} mentioned that {random.choice(['deadlines were missed', 'budgets were exceeded', 'protocols were bypassed'])}. Not sure if this is relevant to the case but wanted you to know.",
+ ]
+
+ docs.append(
+ {
+ "doc_id": f"DOC-{30000 + i}",
+ "type": "email",
+ "date": f"2023-{random.randint(1, 12):02d}-{random.randint(1, 28):02d}T{random.randint(8, 18):02d}:{random.randint(0, 59):02d}:00Z",
+ "from": sender,
+ "to": [recipient],
+ "cc": random.sample(senders, k=random.randint(0, 3)),
+ "subject": random.choice(subjects),
+ "body": random.choice(body_templates),
+ "attachments": [
+ f"document_{random.randint(1, 100)}.{random.choice(['pdf', 'xlsx', 'docx'])}"
+ ]
+ if random.random() > 0.6
+ else [],
+ "flags": random.sample(
+ ["privileged", "responsive", "hot", "needs_review"], k=random.randint(0, 2)
+ ),
+ "reviewed": False,
+ }
+ )
+
+ return {
+ "tool": "discovery_search",
+ "result": {"case": "Matter 2024-CV-1234", "total_documents": num_docs, "documents": docs},
+ }
+
+
+# =============================================================================
+# WORST-CASE SCENARIOS
+# =============================================================================
+
+
+@dataclass
+class WorstCaseScenario:
+ """A scenario where Headroom might struggle."""
+
+ name: str
+ description: str
+ why_hard: str
+ system_prompt: str
+ user_query: str
+ tools: list[dict]
+ validation_questions: list[str] # Specific questions to test recall
+
+
+def create_support_triage_scenario() -> WorstCaseScenario:
+ """
+ Support queue where every ticket is unique and important.
+ """
+ return WorstCaseScenario(
+ name="Support Ticket Triage",
+ description="Triage 50 unique customer support tickets",
+ why_hard="Every ticket is unique - no patterns to compress. Each customer's problem is different. Missing any ticket means a customer gets ignored.",
+ system_prompt="""You are a support team lead triaging tickets.
+Every ticket represents a real customer with a real problem.
+You must acknowledge ALL tickets and prioritize them appropriately.
+Do not skip or summarize away any customer's issue.""",
+ user_query="Please review all tickets in the queue and give me a prioritized action plan. I need to know about EVERY ticket - which ones need immediate attention, which can wait, and which need escalation.",
+ tools=[
+ generate_unique_support_tickets(num_tickets=50),
+ ],
+ validation_questions=[
+ "How many critical severity tickets are there?",
+ "Which Enterprise customers have open tickets?",
+ "List all tickets related to billing issues",
+ "Which tickets mention SSO or authentication problems?",
+ ],
+ )
+
+
+def create_error_investigation_scenario() -> WorstCaseScenario:
+ """
+ Unique errors where each needs individual investigation.
+ """
+ return WorstCaseScenario(
+ name="Production Error Investigation",
+ description="Investigate 30 unique production errors",
+ why_hard="Each error has a different stack trace, different service, different root cause. Can't group them - each needs individual attention.",
+ system_prompt="""You are an on-call engineer investigating production errors.
+Each error is unique and may indicate a different underlying issue.
+Do not group or summarize - each error needs specific investigation.""",
+ user_query="Review all errors from the last 24 hours. For EACH error, tell me: what service, what type, and what you think the root cause might be. Don't group them - I need to know about each one individually.",
+ tools=[
+ generate_unique_error_traces(num_traces=30),
+ ],
+ validation_questions=[
+ "How many Python errors vs JavaScript errors?",
+ "Which services have the most errors?",
+ "List all NullPointerException or nil pointer errors",
+ "Which errors are related to database connections?",
+ ],
+ )
+
+
+def create_medical_review_scenario() -> WorstCaseScenario:
+ """
+ Medical records where every detail matters.
+ """
+ return WorstCaseScenario(
+ name="Medical Record Review",
+ description="Review 25 patients for today's clinic",
+ why_hard="Every patient's vitals, conditions, and medications are unique. 'Similar' symptoms could mean very different things. Can't summarize - details save lives.",
+ system_prompt="""You are a physician reviewing today's patient list.
+Every patient's details matter - similar symptoms may need different treatment.
+Pay attention to vital signs, medication lists, and allergies.
+Never assume two patients with similar complaints have the same issue.""",
+ user_query="Review all patients on today's schedule. Flag any concerning vitals, potential drug interactions, or high-acuity complaints. Give me a brief on EACH patient.",
+ tools=[
+ generate_medical_records(num_patients=25),
+ ],
+ validation_questions=[
+ "Which patients have BP over 140 systolic?",
+ "Which patients are on Metformin?",
+ "List patients with chest pain or cardiac symptoms",
+ "Which patients have drug allergies we should note?",
+ ],
+ )
+
+
+def create_legal_discovery_scenario() -> WorstCaseScenario:
+ """
+ Legal documents where completeness is required.
+ """
+ return WorstCaseScenario(
+ name="Legal Discovery Review",
+ description="Review 40 documents for legal discovery",
+ why_hard="Legal requirement to review EVERY document. Similar-looking emails may have crucial differences. Need exact recall - summaries aren't acceptable in court.",
+ system_prompt="""You are a legal assistant reviewing discovery documents.
+EVERY document must be accounted for - missing one could be sanctions.
+Pay attention to dates, senders, and specific language used.
+Similar documents may have legally significant differences.""",
+ user_query="Review all documents and categorize them. For each document, note: the date, sender, key topics, and whether it seems relevant to the case. I need a complete accounting.",
+ tools=[
+ generate_legal_discovery_docs(num_docs=40),
+ ],
+ validation_questions=[
+ "How many documents mention 'audit' or 'investigation'?",
+ "List all documents with attachments",
+ "Which documents are flagged as 'privileged'?",
+ "How many documents were sent in Q4 2023?",
+ ],
+ )
+
+
+# =============================================================================
+# BENCHMARK RUNNER
+# =============================================================================
+
+
+@dataclass
+class BenchmarkResult:
+ """Result from running a scenario."""
+
+ scenario_name: str
+ mode: str
+ input_tokens: int
+ output_tokens: int
+ cost_usd: float
+ latency_ms: float
+ answer: str
+ validation_scores: dict # Scores for each validation question
+
+
+def count_tokens(text: str) -> int:
+ """Simple token estimation."""
+ return len(text) // 4
+
+
+def validate_answer(answer: str, scenario: WorstCaseScenario) -> dict:
+ """
+ Check if the answer addresses all validation questions.
+ Returns dict of question -> (found keywords, score).
+ """
+ scores = {}
+ answer_lower = answer.lower()
+
+ for question in scenario.validation_questions:
+ # Extract key terms from question
+ key_terms = [w for w in question.lower().split() if len(w) > 4]
+ found = sum(1 for term in key_terms if term in answer_lower)
+ score = found / len(key_terms) if key_terms else 0
+ scores[question] = {
+ "terms_found": found,
+ "terms_total": len(key_terms),
+ "score": round(score, 2),
+ }
+
+ return scores
+
+
+def run_scenario(
+ client: Any, scenario: WorstCaseScenario, mode: str, model: str = "gpt-4o-mini"
+) -> BenchmarkResult:
+ """Run a single scenario."""
+
+ messages = [
+ {"role": "system", "content": scenario.system_prompt},
+ {"role": "user", "content": scenario.user_query},
+ ]
+
+ # Add tool results with proper format
+ for tool_output in scenario.tools:
+ tool_call_id = f"call_{hashlib.md5(tool_output['tool'].encode()).hexdigest()[:8]}"
+ messages.append(
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": tool_call_id,
+ "type": "function",
+ "function": {"name": tool_output["tool"], "arguments": "{}"},
+ }
+ ],
+ }
+ )
+ messages.append(
+ {
+ "role": "tool",
+ "tool_call_id": tool_call_id,
+ "content": json.dumps(tool_output["result"], indent=2),
+ }
+ )
+
+ messages.append({"role": "user", "content": "Please provide your complete analysis now."})
+
+ start = time.time()
+
+ try:
+ response = client.chat.completions.create(
+ model=model,
+ messages=messages,
+ max_tokens=4000, # Allow longer responses
+ )
+ latency = (time.time() - start) * 1000
+
+ answer = response.choices[0].message.content
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+
+ # GPT-4o-mini pricing
+ cost = (input_tokens * 0.00015 + output_tokens * 0.0006) / 1000
+
+ validation_scores = validate_answer(answer, scenario)
+
+ except Exception as e:
+ print(f" Error: {e}")
+ return BenchmarkResult(
+ scenario_name=scenario.name,
+ mode=mode,
+ input_tokens=count_tokens(json.dumps(messages)),
+ output_tokens=0,
+ cost_usd=0,
+ latency_ms=0,
+ answer=f"Error: {e}",
+ validation_scores={},
+ )
+
+ return BenchmarkResult(
+ scenario_name=scenario.name,
+ mode=mode,
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cost_usd=cost,
+ latency_ms=latency,
+ answer=answer,
+ validation_scores=validation_scores,
+ )
+
+
+def run_worst_case_benchmark(api_key: str = None) -> dict:
+ """Run the complete worst-case benchmark."""
+
+ if api_key is None:
+ api_key = os.environ.get("OPENAI_API_KEY")
+
+ if not api_key:
+ raise ValueError("OPENAI_API_KEY required")
+
+ print("=" * 70)
+ print("HEADROOM WORST-CASE BENCHMARK")
+ print("Testing scenarios where compression may hurt performance")
+ print("=" * 70)
+
+ # Create clients
+ import tempfile
+
+ from openai import OpenAI
+
+ baseline_client = OpenAI(api_key=api_key)
+
+ if HEADROOM_AVAILABLE:
+ db_path = os.path.join(tempfile.gettempdir(), "headroom_worst_case.db")
+ headroom_client = HeadroomClient(
+ original_client=OpenAI(api_key=api_key),
+ provider=OpenAIProvider(),
+ store_url=f"sqlite:///{db_path}",
+ default_mode="optimize",
+ )
+ else:
+ print("WARNING: Headroom not available, running baseline only")
+ headroom_client = None
+
+ scenarios = [
+ create_support_triage_scenario(),
+ create_error_investigation_scenario(),
+ create_medical_review_scenario(),
+ create_legal_discovery_scenario(),
+ ]
+
+ results = []
+
+ for scenario in scenarios:
+ print(f"\n{'=' * 60}")
+ print(f"Scenario: {scenario.name}")
+ print(f"Description: {scenario.description}")
+ print(f"WHY THIS IS HARD: {scenario.why_hard}")
+ print("=" * 60)
+
+ # Calculate raw size
+ raw_size = sum(len(json.dumps(t["result"], indent=2)) for t in scenario.tools)
+ print(f"\nRaw tool output size: {raw_size:,} chars (~{raw_size // 4:,} tokens)")
+
+ # Run baseline
+ print("\n[1/2] Running BASELINE...")
+ baseline_result = run_scenario(baseline_client, scenario, "baseline")
+ print(f" Input tokens: {baseline_result.input_tokens:,}")
+ print(f" Output tokens: {baseline_result.output_tokens:,}")
+ print(f" Cost: ${baseline_result.cost_usd:.4f}")
+
+ avg_baseline_score = (
+ sum(v["score"] for v in baseline_result.validation_scores.values())
+ / len(baseline_result.validation_scores)
+ if baseline_result.validation_scores
+ else 0
+ )
+ print(f" Validation score: {avg_baseline_score:.1%}")
+
+ results.append(baseline_result)
+
+ # Run Headroom
+ if headroom_client:
+ print("\n[2/2] Running HEADROOM...")
+ headroom_result = run_scenario(headroom_client, scenario, "headroom")
+ print(f" Input tokens: {headroom_result.input_tokens:,}")
+ print(f" Output tokens: {headroom_result.output_tokens:,}")
+ print(f" Cost: ${headroom_result.cost_usd:.4f}")
+
+ avg_headroom_score = (
+ sum(v["score"] for v in headroom_result.validation_scores.values())
+ / len(headroom_result.validation_scores)
+ if headroom_result.validation_scores
+ else 0
+ )
+ print(f" Validation score: {avg_headroom_score:.1%}")
+
+ results.append(headroom_result)
+
+ # Compare
+ if baseline_result.input_tokens > 0:
+ token_change = (
+ headroom_result.input_tokens - baseline_result.input_tokens
+ ) / baseline_result.input_tokens
+ quality_change = avg_headroom_score - avg_baseline_score
+
+ print("\n 📊 COMPARISON:")
+ print(
+ f" Token change: {token_change:+.1%} ({'saved' if token_change < 0 else 'INCREASED'})"
+ )
+ print(
+ f" Quality change: {quality_change:+.1%} ({'preserved' if quality_change >= -0.1 else 'DEGRADED'})"
+ )
+
+ if quality_change < -0.1:
+ print(" ⚠️ WARNING: Quality degraded significantly!")
+
+ # Summary
+ print("\n" + "=" * 70)
+ print("WORST-CASE BENCHMARK SUMMARY")
+ print("=" * 70)
+
+ baseline_results = [r for r in results if r.mode == "baseline"]
+ headroom_results = [r for r in results if r.mode == "headroom"]
+
+ print(f"\n{'Scenario':<30} {'Baseline Tokens':>15} {'Headroom Tokens':>15} {'Quality Δ':>12}")
+ print("-" * 72)
+
+ for br in baseline_results:
+ hr = next((r for r in headroom_results if r.scenario_name == br.scenario_name), None)
+ if hr:
+ b_score = (
+ sum(v["score"] for v in br.validation_scores.values()) / len(br.validation_scores)
+ if br.validation_scores
+ else 0
+ )
+ h_score = (
+ sum(v["score"] for v in hr.validation_scores.values()) / len(hr.validation_scores)
+ if hr.validation_scores
+ else 0
+ )
+ quality_delta = h_score - b_score
+ print(
+ f"{br.scenario_name:<30} {br.input_tokens:>15,} {hr.input_tokens:>15,} {quality_delta:>+11.1%}"
+ )
+
+ return {
+ "baseline": [
+ {
+ "scenario": r.scenario_name,
+ "tokens": r.input_tokens,
+ "cost": r.cost_usd,
+ "validation": r.validation_scores,
+ }
+ for r in baseline_results
+ ],
+ "headroom": [
+ {
+ "scenario": r.scenario_name,
+ "tokens": r.input_tokens,
+ "cost": r.cost_usd,
+ "validation": r.validation_scores,
+ }
+ for r in headroom_results
+ ],
+ }
+
+
+if __name__ == "__main__":
+ results = run_worst_case_benchmark()
+
+ with open("worst_case_benchmark_results.json", "w") as f:
+ json.dump(results, f, indent=2)
+
+ print("\nResults saved to worst_case_benchmark_results.json")
diff --git a/benchmarks/real_world_agent_benchmark.py b/benchmarks/real_world_agent_benchmark.py
new file mode 100644
index 000000000..7b4c8882e
--- /dev/null
+++ b/benchmarks/real_world_agent_benchmark.py
@@ -0,0 +1,765 @@
+"""
+Real-World Agent Benchmark: MCP Tools + Headroom
+
+This benchmark simulates real multi-agent workflows using actual MCP tool output formats:
+1. Filesystem MCP Server - directory trees, file searches, file contents
+2. GitHub MCP Server - code search, issues, PRs, commits
+3. Database MCP Server - query results, schema info
+
+We measure:
+- Token usage with vs without Headroom
+- Cost savings
+- Answer quality (does compression hurt agent performance?)
+
+This is NOT synthetic data - these are actual output formats from production MCP servers.
+"""
+
+import hashlib
+import json
+import os
+import random
+import time
+from dataclasses import dataclass
+from typing import Any
+
+# OpenAI for agent
+try:
+ from openai import OpenAI # noqa: F401
+
+ OPENAI_AVAILABLE = True
+except ImportError:
+ OPENAI_AVAILABLE = False
+
+# Headroom
+try:
+ from headroom import HeadroomClient, OpenAIProvider
+
+ HEADROOM_AVAILABLE = True
+except ImportError:
+ HEADROOM_AVAILABLE = False
+
+
+# =============================================================================
+# REALISTIC MCP TOOL OUTPUT GENERATORS
+# Based on actual MCP server output formats
+# =============================================================================
+
+
+def generate_filesystem_tree(
+ path: str = "/project", depth: int = 3, files_per_dir: int = 15
+) -> dict:
+ """
+ Generate realistic filesystem tree output (MCP filesystem server format).
+ This mimics `tree` command output from @modelcontextprotocol/server-filesystem.
+ """
+
+ def generate_dir(current_path: str, current_depth: int) -> list:
+ if current_depth <= 0:
+ return []
+
+ entries = []
+
+ # Common project structure
+ dir_names = [
+ "src",
+ "lib",
+ "utils",
+ "components",
+ "services",
+ "models",
+ "controllers",
+ "middleware",
+ "tests",
+ "config",
+ "scripts",
+ "api",
+ "core",
+ "helpers",
+ "types",
+ "interfaces",
+ ]
+
+ file_extensions = [".py", ".ts", ".js", ".json", ".yaml", ".md"]
+
+ # Add some directories
+ num_dirs = random.randint(2, 5) if current_depth > 1 else 0
+ for i in range(num_dirs):
+ dir_name = random.choice(dir_names) + (f"_{i}" if i > 0 else "")
+ dir_path = f"{current_path}/{dir_name}"
+ entries.append(
+ {
+ "name": dir_name,
+ "type": "directory",
+ "path": dir_path,
+ "children": generate_dir(dir_path, current_depth - 1),
+ }
+ )
+
+ # Add files
+ for i in range(files_per_dir):
+ ext = random.choice(file_extensions)
+ file_name = f"module_{i}{ext}"
+ entries.append(
+ {
+ "name": file_name,
+ "type": "file",
+ "path": f"{current_path}/{file_name}",
+ "size": random.randint(100, 10000),
+ "modified": f"2024-01-{random.randint(1, 28):02d}T{random.randint(0, 23):02d}:{random.randint(0, 59):02d}:00Z",
+ }
+ )
+
+ return entries
+
+ return {
+ "tool": "filesystem_tree",
+ "path": path,
+ "result": {
+ "name": path.split("/")[-1] or "project",
+ "type": "directory",
+ "path": path,
+ "children": generate_dir(path, depth),
+ },
+ }
+
+
+def generate_filesystem_search(query: str, num_results: int = 200) -> dict:
+ """
+ Generate realistic file search results (MCP filesystem server format).
+ Mimics search_files output with path matches and content snippets.
+ """
+ results = []
+
+ # Common file paths in a real project
+ paths = [
+ "src/auth/jwt_handler.py",
+ "src/auth/oauth_provider.py",
+ "src/api/routes/users.py",
+ "src/api/routes/products.py",
+ "src/services/payment_processor.py",
+ "src/services/email_sender.py",
+ "src/middleware/rate_limiter.py",
+ "src/middleware/auth_middleware.py",
+ "src/models/user.py",
+ "src/models/order.py",
+ "tests/test_auth.py",
+ "tests/test_api.py",
+ "config/database.py",
+ "config/settings.py",
+ ]
+
+ for i in range(num_results):
+ if i < len(paths):
+ path = paths[i]
+ else:
+ path = f"src/modules/module_{i}.py"
+
+ # Generate realistic match context
+ match_line = random.randint(10, 500)
+ results.append(
+ {
+ "path": path,
+ "type": "file",
+ "size": random.randint(500, 15000),
+ "modified": f"2024-01-{random.randint(1, 28):02d}",
+ "matches": [
+ {
+ "line": match_line,
+ "content": f" def process_{query.lower().replace(' ', '_')}(self, data):",
+ "context_before": " # Process incoming request",
+ "context_after": f" return self.handler.{query.lower()}(data)",
+ }
+ ],
+ "score": round(random.uniform(0.5, 1.0), 3),
+ }
+ )
+
+ return {
+ "tool": "search_files",
+ "query": query,
+ "result": {
+ "total_matches": num_results,
+ "files_searched": num_results * 10,
+ "matches": results,
+ },
+ }
+
+
+def generate_github_code_search(query: str, num_results: int = 100) -> dict:
+ """
+ Generate realistic GitHub code search results (GitHub MCP server format).
+ Based on actual github-mcp-server output.
+ """
+ repos = [
+ "facebook/react",
+ "microsoft/vscode",
+ "tensorflow/tensorflow",
+ "kubernetes/kubernetes",
+ "golang/go",
+ "rust-lang/rust",
+ "apache/spark",
+ "elastic/elasticsearch",
+ "grafana/grafana",
+ "prometheus/prometheus",
+ "docker/docker-ce",
+ "nginx/nginx",
+ ]
+
+ results = []
+ for i in range(num_results):
+ repo = random.choice(repos)
+ results.append(
+ {
+ "repository": {
+ "full_name": repo,
+ "description": f"The {repo.split('/')[1]} project",
+ "stars": random.randint(1000, 100000),
+ "language": random.choice(["Python", "Go", "TypeScript", "Java", "Rust"]),
+ "updated_at": f"2024-01-{random.randint(1, 28):02d}T00:00:00Z",
+ },
+ "path": f"src/{query.lower().replace(' ', '_')}/handler.py",
+ "sha": hashlib.sha1(f"{repo}{i}".encode()).hexdigest(),
+ "url": f"https://github.com/{repo}/blob/main/src/handler.py",
+ "score": round(random.uniform(10, 100), 2),
+ "text_matches": [
+ {
+ "fragment": f"def {query.lower().replace(' ', '_')}(request):\n # Implementation\n return response",
+ "matches": [{"text": query, "indices": [4, 4 + len(query)]}],
+ }
+ ],
+ }
+ )
+
+ return {
+ "tool": "github_search_code",
+ "query": query,
+ "result": {"total_count": num_results * 50, "incomplete_results": False, "items": results},
+ }
+
+
+def generate_github_issues(repo: str, num_issues: int = 50) -> dict:
+ """
+ Generate realistic GitHub issues list (GitHub MCP server format).
+ """
+ labels = ["bug", "enhancement", "documentation", "help wanted", "good first issue"]
+ states = ["open", "open", "open", "closed"] # Weighted toward open
+
+ issues = []
+ for i in range(num_issues):
+ issues.append(
+ {
+ "number": 1000 + i,
+ "title": f"Issue #{1000 + i}: "
+ + random.choice(
+ [
+ "Fix authentication flow",
+ "Add support for OAuth2",
+ "Performance regression in v2.0",
+ "Documentation needs update",
+ "Memory leak in worker process",
+ "Add dark mode support",
+ "API rate limiting not working",
+ ]
+ ),
+ "state": random.choice(states),
+ "user": {
+ "login": f"user{random.randint(1, 1000)}",
+ "avatar_url": f"https://avatars.githubusercontent.com/u/{random.randint(1, 100000)}",
+ },
+ "labels": random.sample(labels, k=random.randint(0, 3)),
+ "created_at": f"2024-01-{random.randint(1, 28):02d}T{random.randint(0, 23):02d}:00:00Z",
+ "updated_at": f"2024-01-{random.randint(1, 28):02d}T{random.randint(0, 23):02d}:00:00Z",
+ "comments": random.randint(0, 50),
+ "body": f"## Description\n\nThis issue tracks {random.choice(['a bug', 'a feature request', 'documentation update'])}.\n\n## Steps to Reproduce\n\n1. Step one\n2. Step two\n3. Step three\n\n## Expected Behavior\n\nIt should work.\n\n## Actual Behavior\n\nIt doesn't work.",
+ }
+ )
+
+ return {
+ "tool": "github_list_issues",
+ "repository": repo,
+ "result": {"total_count": num_issues, "items": issues},
+ }
+
+
+def generate_database_query_results(query: str, num_rows: int = 500) -> dict:
+ """
+ Generate realistic database query results (Database MCP server format).
+ """
+ # Simulate a user analytics query
+ rows = []
+ for i in range(num_rows):
+ rows.append(
+ {
+ "user_id": f"user_{10000 + i}",
+ "email": f"user{10000 + i}@example.com",
+ "created_at": f"2024-01-{random.randint(1, 28):02d}",
+ "last_login": f"2024-01-{random.randint(1, 28):02d}T{random.randint(0, 23):02d}:00:00Z",
+ "total_orders": random.randint(0, 100),
+ "total_revenue": round(random.uniform(0, 10000), 2),
+ "status": random.choice(["active", "active", "active", "inactive", "suspended"]),
+ "country": random.choice(["US", "UK", "DE", "FR", "JP", "AU", "CA"]),
+ "subscription_tier": random.choice(
+ ["free", "free", "basic", "premium", "enterprise"]
+ ),
+ }
+ )
+
+ # Add some anomalies (high-value users)
+ for _ in range(3):
+ rows[random.randint(0, len(rows) - 1)]["total_revenue"] = round(
+ random.uniform(50000, 100000), 2
+ )
+ rows[random.randint(0, len(rows) - 1)]["status"] = "suspended"
+
+ return {
+ "tool": "database_query",
+ "query": query,
+ "result": {
+ "columns": [
+ "user_id",
+ "email",
+ "created_at",
+ "last_login",
+ "total_orders",
+ "total_revenue",
+ "status",
+ "country",
+ "subscription_tier",
+ ],
+ "row_count": num_rows,
+ "rows": rows,
+ "execution_time_ms": random.randint(50, 500),
+ },
+ }
+
+
+def generate_log_search(query: str, num_entries: int = 300) -> dict:
+ """
+ Generate realistic log search results (Logging MCP server format).
+ """
+ log_levels = ["INFO", "INFO", "INFO", "INFO", "WARN", "ERROR", "DEBUG"]
+ services = [
+ "api-gateway",
+ "auth-service",
+ "payment-service",
+ "user-service",
+ "notification-service",
+ ]
+
+ entries = []
+
+ for i in range(num_entries):
+ level = random.choice(log_levels)
+ service = random.choice(services)
+
+ if level == "ERROR":
+ message = random.choice(
+ [
+ f"Connection refused to {service}:8080 - ECONNREFUSED",
+ f"Timeout waiting for response from {service} after 30000ms",
+ "Failed to process request: NullPointerException",
+ "Database connection pool exhausted",
+ ]
+ )
+ elif level == "WARN":
+ message = random.choice(
+ [
+ "High latency detected: 2500ms (threshold: 1000ms)",
+ "Rate limit approaching: 450/500 requests",
+ "Memory usage at 85%",
+ f"Retry attempt 3/5 for {service}",
+ ]
+ )
+ else:
+ message = random.choice(
+ [
+ "Request processed successfully",
+ "Health check passed",
+ f"Cache hit for key: user_session_{random.randint(1000, 9999)}",
+ f"Authenticated user: user_{random.randint(1000, 9999)}",
+ ]
+ )
+
+ entries.append(
+ {
+ "timestamp": f"2024-01-15T{10 + (i // 60):02d}:{i % 60:02d}:00Z",
+ "level": level,
+ "service": service,
+ "message": message,
+ "trace_id": hashlib.md5(f"{i}".encode()).hexdigest()[:16],
+ "metadata": {
+ "host": f"pod-{service}-{random.randint(1, 5)}",
+ "region": random.choice(["us-east-1", "us-west-2", "eu-west-1"]),
+ },
+ }
+ )
+
+ return {
+ "tool": "search_logs",
+ "query": query,
+ "result": {"total_hits": num_entries * 10, "returned": num_entries, "entries": entries},
+ }
+
+
+# =============================================================================
+# AGENT SCENARIOS
+# =============================================================================
+
+
+@dataclass
+class AgentScenario:
+ """A realistic agent workflow scenario."""
+
+ name: str
+ description: str
+ system_prompt: str
+ user_query: str
+ tools: list[dict] # Tool outputs in sequence
+ expected_answer_contains: list[str] # Key phrases expected in good answer
+
+
+def create_sre_debugging_scenario() -> AgentScenario:
+ """
+ SRE agent debugging a production incident.
+ Multiple tool calls with large outputs.
+ """
+ return AgentScenario(
+ name="SRE Incident Debugging",
+ description="Debug a production incident using logs, metrics, and deployment info",
+ system_prompt="""You are an SRE assistant helping debug production incidents.
+You have access to tools for searching logs, querying metrics, and checking deployments.
+Analyze the data carefully and identify the root cause.""",
+ user_query="We're seeing 500 errors on the payment service. Can you investigate and find the root cause?",
+ tools=[
+ generate_log_search("payment error", num_entries=300),
+ generate_database_query_results(
+ "SELECT * FROM service_metrics WHERE service='payment'", num_rows=200
+ ),
+ generate_filesystem_search("payment", num_results=150),
+ ],
+ expected_answer_contains=["payment", "error", "connection", "timeout"],
+ )
+
+
+def create_codebase_exploration_scenario() -> AgentScenario:
+ """
+ Developer agent exploring a new codebase.
+ File tree + search + code reading.
+ """
+ return AgentScenario(
+ name="Codebase Exploration",
+ description="Explore a codebase to understand authentication implementation",
+ system_prompt="""You are a developer assistant helping explore codebases.
+You have access to file system tools and code search.
+Help the user understand how the codebase is structured.""",
+ user_query="I need to understand how authentication is implemented. Can you find the relevant files and explain the flow?",
+ tools=[
+ generate_filesystem_tree("/project", depth=3, files_per_dir=20),
+ generate_filesystem_search("authentication", num_results=200),
+ generate_github_code_search("JWT authentication middleware", num_results=100),
+ ],
+ expected_answer_contains=["auth", "jwt", "middleware", "handler"],
+ )
+
+
+def create_issue_triage_scenario() -> AgentScenario:
+ """
+ GitHub agent triaging issues and finding related code.
+ """
+ return AgentScenario(
+ name="GitHub Issue Triage",
+ description="Triage GitHub issues and find related code",
+ system_prompt="""You are a GitHub assistant helping triage issues.
+Analyze issues, find patterns, and identify related code.""",
+ user_query="Can you analyze the open issues and identify any patterns or high-priority bugs we should focus on?",
+ tools=[
+ generate_github_issues("myorg/myrepo", num_issues=100),
+ generate_github_code_search("bug fix", num_results=80),
+ generate_log_search("exception", num_entries=200),
+ ],
+ expected_answer_contains=["bug", "issue", "priority"],
+ )
+
+
+# =============================================================================
+# BENCHMARK RUNNER
+# =============================================================================
+
+
+@dataclass
+class BenchmarkResult:
+ """Result from running a scenario."""
+
+ scenario_name: str
+ mode: str # "baseline" or "headroom"
+ total_input_tokens: int
+ total_output_tokens: int
+ total_tokens: int
+ cost_usd: float
+ latency_ms: float
+ answer_quality: float # 0-1 based on expected keywords
+ num_tool_calls: int
+
+
+def count_tokens_simple(text: str) -> int:
+ """Simple token estimation (4 chars per token)."""
+ return len(text) // 4
+
+
+def run_agent_scenario(
+ client: Any, scenario: AgentScenario, model: str = "gpt-4o-mini"
+) -> BenchmarkResult:
+ """Run a scenario and measure token usage."""
+
+ messages = [
+ {"role": "system", "content": scenario.system_prompt},
+ {"role": "user", "content": scenario.user_query},
+ ]
+
+ # Add tool results with proper OpenAI format
+ for tool_output in scenario.tools:
+ tool_call_id = f"call_{hashlib.md5(tool_output['tool'].encode()).hexdigest()[:8]}"
+ # Assistant message with tool_calls (required by OpenAI)
+ messages.append(
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": tool_call_id,
+ "type": "function",
+ "function": {"name": tool_output["tool"], "arguments": "{}"},
+ }
+ ],
+ }
+ )
+ messages.append(
+ {
+ "role": "tool",
+ "tool_call_id": tool_call_id,
+ "content": json.dumps(tool_output["result"], indent=2),
+ }
+ )
+
+ # Add final question
+ messages.append(
+ {
+ "role": "user",
+ "content": "Based on all this information, what's your analysis and recommendation?",
+ }
+ )
+
+ # Count input tokens
+ input_text = json.dumps(messages)
+ input_tokens = count_tokens_simple(input_text)
+
+ # Make API call
+ start = time.time()
+
+ # Determine if using HeadroomClient
+ is_headroom = isinstance(client, HeadroomClient) if HEADROOM_AVAILABLE else False
+ mode = "headroom" if is_headroom else "baseline"
+
+ try:
+ response = client.chat.completions.create(
+ model=model,
+ messages=messages,
+ max_tokens=1000,
+ )
+ latency = (time.time() - start) * 1000
+
+ answer = response.choices[0].message.content
+ output_tokens = (
+ response.usage.completion_tokens
+ if hasattr(response, "usage")
+ else count_tokens_simple(answer)
+ )
+ actual_input_tokens = (
+ response.usage.prompt_tokens if hasattr(response, "usage") else input_tokens
+ )
+
+ # Calculate answer quality
+ answer_lower = answer.lower()
+ matches = sum(1 for kw in scenario.expected_answer_contains if kw.lower() in answer_lower)
+ quality = matches / len(scenario.expected_answer_contains)
+
+ # Estimate cost (gpt-4o-mini pricing)
+ cost = (actual_input_tokens * 0.00015 + output_tokens * 0.0006) / 1000
+
+ except Exception as e:
+ print(f" Error: {e}")
+ return BenchmarkResult(
+ scenario_name=scenario.name,
+ mode=mode,
+ total_input_tokens=input_tokens,
+ total_output_tokens=0,
+ total_tokens=input_tokens,
+ cost_usd=0.0,
+ latency_ms=0,
+ answer_quality=0.0,
+ num_tool_calls=len(scenario.tools),
+ )
+
+ return BenchmarkResult(
+ scenario_name=scenario.name,
+ mode=mode,
+ total_input_tokens=actual_input_tokens,
+ total_output_tokens=output_tokens,
+ total_tokens=actual_input_tokens + output_tokens,
+ cost_usd=cost,
+ latency_ms=latency,
+ answer_quality=quality,
+ num_tool_calls=len(scenario.tools),
+ )
+
+
+def run_full_benchmark(api_key: str = None) -> dict:
+ """Run complete benchmark comparing baseline vs Headroom."""
+
+ if api_key is None:
+ api_key = os.environ.get("OPENAI_API_KEY")
+
+ if not api_key:
+ raise ValueError("OPENAI_API_KEY required")
+
+ if not HEADROOM_AVAILABLE:
+ raise RuntimeError("Headroom not available")
+
+ # Create clients
+ import tempfile
+
+ from openai import OpenAI
+
+ baseline_client = OpenAI(api_key=api_key)
+
+ # Headroom-wrapped client
+ db_path = os.path.join(tempfile.gettempdir(), "headroom_benchmark.db")
+ headroom_client = HeadroomClient(
+ original_client=OpenAI(api_key=api_key),
+ provider=OpenAIProvider(),
+ store_url=f"sqlite:///{db_path}",
+ default_mode="optimize",
+ )
+
+ scenarios = [
+ create_sre_debugging_scenario(),
+ create_codebase_exploration_scenario(),
+ create_issue_triage_scenario(),
+ ]
+
+ results = []
+
+ print("\n" + "=" * 70)
+ print("REAL-WORLD AGENT BENCHMARK: MCP Tools + Headroom")
+ print("=" * 70)
+
+ for scenario in scenarios:
+ print(f"\n{'=' * 60}")
+ print(f"Scenario: {scenario.name}")
+ print(f"Description: {scenario.description}")
+ print(f"Tool calls: {len(scenario.tools)}")
+ print(f"{'=' * 60}")
+
+ # Estimate raw data size
+ raw_size = sum(len(json.dumps(t["result"])) for t in scenario.tools)
+ print(f"\nRaw tool output size: {raw_size:,} chars (~{raw_size // 4:,} tokens)")
+
+ # Run baseline
+ print("\n[1/2] Running BASELINE (no compression)...")
+ baseline_result = run_agent_scenario(baseline_client, scenario)
+ print(f" Input tokens: {baseline_result.total_input_tokens:,}")
+ print(f" Output tokens: {baseline_result.total_output_tokens:,}")
+ print(f" Cost: ${baseline_result.cost_usd:.4f}")
+ print(f" Answer quality: {baseline_result.answer_quality:.1%}")
+ results.append(baseline_result)
+
+ # Run with Headroom
+ print("\n[2/2] Running HEADROOM (optimized)...")
+ headroom_result = run_agent_scenario(headroom_client, scenario)
+ print(f" Input tokens: {headroom_result.total_input_tokens:,}")
+ print(f" Output tokens: {headroom_result.total_output_tokens:,}")
+ print(f" Cost: ${headroom_result.cost_usd:.4f}")
+ print(f" Answer quality: {headroom_result.answer_quality:.1%}")
+ results.append(headroom_result)
+
+ # Calculate savings
+ if baseline_result.total_input_tokens > 0:
+ token_savings = 1 - (
+ headroom_result.total_input_tokens / baseline_result.total_input_tokens
+ )
+ cost_savings = (
+ 1 - (headroom_result.cost_usd / baseline_result.cost_usd)
+ if baseline_result.cost_usd > 0
+ else 0
+ )
+ print("\n 📊 SAVINGS:")
+ print(f" Token reduction: {token_savings:.1%}")
+ print(f" Cost reduction: {cost_savings:.1%}")
+ print(
+ f" Quality preserved: {'✓' if headroom_result.answer_quality >= baseline_result.answer_quality * 0.9 else '✗'}"
+ )
+
+ # Summary
+ print("\n" + "=" * 70)
+ print("BENCHMARK SUMMARY")
+ print("=" * 70)
+
+ baseline_results = [r for r in results if r.mode == "baseline"]
+ headroom_results = [r for r in results if r.mode == "headroom"]
+
+ total_baseline_tokens = sum(r.total_input_tokens for r in baseline_results)
+ total_headroom_tokens = sum(r.total_input_tokens for r in headroom_results)
+ total_baseline_cost = sum(r.cost_usd for r in baseline_results)
+ total_headroom_cost = sum(r.cost_usd for r in headroom_results)
+
+ print(f"\n{'Metric':<25} {'Baseline':>15} {'Headroom':>15} {'Savings':>15}")
+ print("-" * 70)
+
+ token_savings = (
+ (1 - total_headroom_tokens / total_baseline_tokens) if total_baseline_tokens > 0 else 0
+ )
+ cost_savings = (1 - total_headroom_cost / total_baseline_cost) if total_baseline_cost > 0 else 0
+
+ print(
+ f"{'Total Input Tokens':<25} {total_baseline_tokens:>15,} {total_headroom_tokens:>15,} {token_savings:>14.1%}"
+ )
+ print(
+ f"{'Total Cost':<25} ${total_baseline_cost:>14.4f} ${total_headroom_cost:>14.4f} {cost_savings:>14.1%}"
+ )
+
+ avg_baseline_quality = (
+ sum(r.answer_quality for r in baseline_results) / len(baseline_results)
+ if baseline_results
+ else 0
+ )
+ avg_headroom_quality = (
+ sum(r.answer_quality for r in headroom_results) / len(headroom_results)
+ if headroom_results
+ else 0
+ )
+ print(
+ f"{'Avg Answer Quality':<25} {avg_baseline_quality:>14.1%} {avg_headroom_quality:>14.1%} {'preserved' if avg_headroom_quality >= avg_baseline_quality * 0.9 else 'degraded':>15}"
+ )
+
+ return {
+ "baseline": [r.__dict__ for r in baseline_results],
+ "headroom": [r.__dict__ for r in headroom_results],
+ "summary": {
+ "total_baseline_tokens": total_baseline_tokens,
+ "total_headroom_tokens": total_headroom_tokens,
+ "token_savings": token_savings,
+ "total_baseline_cost": total_baseline_cost,
+ "total_headroom_cost": total_headroom_cost,
+ "cost_savings": cost_savings,
+ },
+ }
+
+
+if __name__ == "__main__":
+ results = run_full_benchmark()
+
+ # Save results
+ with open("real_world_benchmark_results.json", "w") as f:
+ json.dump(results, f, indent=2)
+
+ print("\nResults saved to real_world_benchmark_results.json")
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index e10a22c64..577faae7f 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -1947,26 +1947,89 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
@app.get("/stats")
async def stats():
+ """Get comprehensive proxy statistics.
+
+ This is the main stats endpoint - it aggregates data from all subsystems:
+ - Request metrics (total, cached, failed, by model/provider)
+ - Token usage and savings
+ - Cost tracking
+ - Compression (CCR) statistics
+ - Telemetry/TOIN (data flywheel) statistics
+ - Cache and rate limiter stats
+ """
m = proxy.metrics
+
+ # Calculate average latency
+ avg_latency_ms = round(m.latency_sum_ms / m.latency_count, 2) if m.latency_count > 0 else 0
+
+ # Get compression store stats
+ store = get_compression_store()
+ compression_stats = store.get_stats()
+
+ # Get telemetry/TOIN stats
+ telemetry = get_telemetry_collector()
+ telemetry_stats = telemetry.get_stats()
+
+ # Get feedback loop stats
+ feedback = get_compression_feedback()
+ feedback_stats = feedback.get_stats()
+
+ # Calculate total tokens before compression
+ total_tokens_before = m.tokens_input_total + m.tokens_saved_total
+
return {
"requests": {
"total": m.requests_total,
"cached": m.requests_cached,
"rate_limited": m.requests_rate_limited,
"failed": m.requests_failed,
+ "by_provider": dict(m.requests_by_provider),
+ "by_model": dict(m.requests_by_model),
},
"tokens": {
"input": m.tokens_input_total,
"output": m.tokens_output_total,
"saved": m.tokens_saved_total,
+ "total_before_compression": total_tokens_before,
"savings_percent": round(
- (m.tokens_saved_total / (m.tokens_input_total + m.tokens_saved_total) * 100)
- if m.tokens_input_total > 0
+ (m.tokens_saved_total / total_tokens_before * 100)
+ if total_tokens_before > 0
else 0,
2,
),
},
+ "latency": {
+ "average_ms": avg_latency_ms,
+ "total_requests": m.latency_count,
+ },
"cost": proxy.cost_tracker.stats() if proxy.cost_tracker else None,
+ "compression": {
+ "ccr_entries": compression_stats.get("entry_count", 0),
+ "ccr_max_entries": compression_stats.get("max_entries", 0),
+ "original_tokens_cached": compression_stats.get("total_original_tokens", 0),
+ "compressed_tokens_cached": compression_stats.get("total_compressed_tokens", 0),
+ "ccr_retrievals": compression_stats.get("total_retrievals", 0),
+ },
+ "telemetry": {
+ "enabled": telemetry_stats.get("enabled", False),
+ "total_compressions": telemetry_stats.get("total_compressions", 0),
+ "total_retrievals": telemetry_stats.get("total_retrievals", 0),
+ "global_retrieval_rate": round(telemetry_stats.get("global_retrieval_rate", 0), 4),
+ "tool_signatures_tracked": telemetry_stats.get("tool_signatures_tracked", 0),
+ "avg_compression_ratio": round(telemetry_stats.get("avg_compression_ratio", 0), 4),
+ "avg_token_reduction": round(telemetry_stats.get("avg_token_reduction", 0), 4),
+ },
+ "feedback_loop": {
+ "tools_tracked": feedback_stats.get("tools_tracked", 0),
+ "total_compressions": feedback_stats.get("total_compressions", 0),
+ "total_retrievals": feedback_stats.get("total_retrievals", 0),
+ "global_retrieval_rate": round(feedback_stats.get("global_retrieval_rate", 0), 4),
+ "tools_with_high_retrieval": sum(
+ 1
+ for p in feedback_stats.get("tool_patterns", {}).values()
+ if p.get("retrieval_rate", 0) > 0.3
+ ),
+ },
"cache": await proxy.cache.stats() if proxy.cache else None,
"rate_limiter": await proxy.rate_limiter.stats() if proxy.rate_limiter else None,
"recent_requests": proxy.logger.get_recent(10) if proxy.logger else [],
diff --git a/pyproject.toml b/pyproject.toml
index 58f791bf6..aec6377f0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "headroom-ai"
-version = "0.2.11"
+version = "0.2.12"
description = "The Context Optimization Layer for LLM Applications - Cut costs by 50-90%"
readme = "README.md"
license = "Apache-2.0"
diff --git a/uv.lock b/uv.lock
index 589a0d7c1..195542038 100644
--- a/uv.lock
+++ b/uv.lock
@@ -849,7 +849,7 @@ wheels = [
[[package]]
name = "headroom-ai"
-version = "0.2.10"
+version = "0.2.11"
source = { editable = "." }
dependencies = [
{ name = "litellm" },