Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat: add historical rollups and exports
Garm9a695249af71
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8888f706d..50d9aa3bc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,9 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Durable proxy savings history**- Persists proxy compression savings history locally at `~/.headroom/proxy_savings.json`- Supports `HEADROOM_SAVINGS_PATH` to override the storage location- - Adds `/stats-history` with lifetime totals plus hourly/daily rollups for frontends+ - Adds `/stats-history` with lifetime totals plus hourly/daily/weekly/monthly rollups+ - Supports JSON and CSV export from `/stats-history`- Extends `/stats` with a `persistent_savings` block while keeping `savings_history` backward compatible- - Adds a historical mode to `/dashboard` backed by `/stats-history`+ - Adds a historical mode to `/dashboard` backed by `/stats-history`, including export actions- **Proxy telemetry SDK override** via `HEADROOM_SDK`- Downstream apps can override the anonymous telemetry `sdk` field without patching installed files- Blank values fall back to the default `proxy` labeldiff --git a/docs/metrics.md b/docs/metrics.mdindex ade1ba9b0..6664fa989 100644--- a/docs/metrics.md+++ b/docs/metrics.md@@ -76,14 +76,32 @@ curl http://localhost:8787/stats-history],"series": {"hourly": [],- "daily": []+ "daily": [],+ "weekly": [],+ "monthly": []+ },+ "exports": {+ "default_format": "json",+ "available_formats": ["json", "csv"],+ "available_series": ["history", "hourly", "daily", "weekly", "monthly"]}}````/stats-history` is the stable frontend-facing API for durable proxycompression history. It survives proxy restarts, tolerates missing or malformed-state files, and powers the historical view in `/dashboard`.+state files, and powers the historical view in `/dashboard`. It now includes+hourly, daily, weekly, and monthly chart-ready rollups.++For export-friendly downloads:++```bash+curl "http://localhost:8787/stats-history?format=csv&series=daily"+curl "http://localhost:8787/stats-history?format=csv&series=monthly"+```++CSV exports are available for `history`, `hourly`, `daily`, `weekly`, and+`monthly`. Plain JSON remains the default response format.### Prometheus Metricsdiff --git a/docs/proxy.md b/docs/proxy.mdindex e59f21e73..90b7d5920 100644--- a/docs/proxy.md+++ b/docs/proxy.md@@ -122,12 +122,20 @@ other Headroom frontends. It returns:- lifetime proxy compression totals- bounded persisted checkpoint history-- derived hourly and daily rollups for charts+- derived hourly, daily, weekly, and monthly rollups for charts- UTC timestamps throughoutBy default the proxy stores this history at `~/.headroom/proxy_savings.json`.Set `HEADROOM_SAVINGS_PATH` to override the location.+`/dashboard` uses this endpoint directly for its historical view, including the+daily/weekly/monthly rollups and built-in JSON / CSV export buttons.++```bash+curl "http://localhost:8787/stats-history?format=csv&series=weekly"+curl "http://localhost:8787/stats-history?format=csv&series=monthly"+```+### Prometheus Metrics```bashdiff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.htmlindex f94590b24..203cb4c4f 100644--- a/headroom/dashboard/templates/dashboard.html+++ b/headroom/dashboard/templates/dashboard.html@@ -526,7 +526,36 @@<template x-if="viewMode === 'history'"><div>- <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">+ <div class="flex flex-col gap-4 mb-6 lg:flex-row lg:items-center lg:justify-between">+ <div>+ <div class="text-sm font-medium text-gray-300">Historical Proxy Compression</div>+ <div class="text-xs text-gray-500">+ Durable local savings history from <span class="font-mono">/stats-history</span>+ </div>+ </div>+ <div class="flex flex-col gap-3 sm:flex-row sm:items-center">+ <div class="inline-flex rounded-lg border border-border bg-surface p-1">+ <template x-for="[label, key] in historyGranularityOptions" :key="key">+ <button class="px-3 py-1.5 text-sm rounded-md transition-colors"+ :class="historyGranularity === key ? 'bg-accent text-black' : 'text-gray-400 hover:text-gray-200'"+ @click="historyGranularity = key"+ x-text="label"></button>+ </template>+ </div>+ <div class="flex items-center gap-2">+ <button class="px-3 py-1.5 text-sm rounded-md border border-border bg-surface text-gray-300 hover:text-white transition-colors"+ @click="downloadHistory('json')">+ Export JSON+ </button>+ <button class="px-3 py-1.5 text-sm rounded-md border border-border bg-surface text-gray-300 hover:text-white transition-colors"+ @click="downloadHistory('csv')">+ Export CSV+ </button>+ </div>+ </div>+ </div>++ <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-4 mb-6"><div class="bg-surface rounded-lg p-4 border border-border"><div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Lifetime Compression Savings</div><div class="flex items-baseline gap-2">@@ -557,6 +586,24 @@<div class="mt-2 text-xs text-gray-500" x-text="historyWindowLabel"></div></div>+ <div class="bg-surface rounded-lg p-4 border border-border">+ <div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Active Weeks</div>+ <div class="flex items-baseline gap-2">+ <span class="text-3xl font-light tabular-nums"+ x-text="formatNumber((historyStats.series?.weekly || []).length)"></span>+ </div>+ <div class="mt-2 text-xs text-gray-500">Weekly UTC rollups</div>+ </div>++ <div class="bg-surface rounded-lg p-4 border border-border">+ <div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Active Months</div>+ <div class="flex items-baseline gap-2">+ <span class="text-3xl font-light tabular-nums"+ x-text="formatNumber((historyStats.series?.monthly || []).length)"></span>+ </div>+ <div class="mt-2 text-xs text-gray-500">Monthly UTC rollups</div>+ </div>+<div class="bg-surface rounded-lg p-4 border border-border"><div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Average Saved / Day</div><div class="flex items-baseline gap-2">@@ -565,6 +612,15 @@</div><div class="mt-2 text-xs text-gray-500">Based on persisted daily buckets</div></div>++ <div class="bg-surface rounded-lg p-4 border border-border">+ <div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Average Saved / Week</div>+ <div class="flex items-baseline gap-2">+ <span class="text-3xl font-light tabular-nums"+ x-text="formatNumber(historyAverageTokensPerWeek)"></span>+ </div>+ <div class="mt-2 text-xs text-gray-500">Based on persisted weekly buckets</div>+ </div></div><template x-if="hasHistoricalData">@@ -575,6 +631,8 @@<span class="text-sm font-medium text-gray-300">Historical Savings Trend</span><span class="text-xs text-gray-500 font-mono" x-text="historyTrendLabel"></span></div>+ <div class="text-xs text-gray-500 mb-4"+ x-text="'Showing ' + formatNumber(historySelectedPointCount) + ' ' + historySelectedSeriesLabel.toLowerCase() + ' points'"></div><template x-if="historicalTrend.length >= 2"><div class="h-48"><svg class="w-full h-full" viewBox="0 0 200 64" preserveAspectRatio="none">@@ -593,7 +651,7 @@</template><template x-if="historicalTrend.length < 2"><div class="h-48 flex items-center justify-center text-sm text-gray-500 italic">- Historical trend data will appear after more saved checkpoints.+ Historical trend data will appear after more saved checkpoints in this granularity.</div></template></div>@@ -607,14 +665,19 @@x-text="formatNumber(historyStats.lifetime?.tokens_saved || 0) + ' tokens'"></span></div><div class="flex justify-between items-center">- <span class="text-sm text-gray-400">Hourly buckets</span>+ <span class="text-sm text-gray-400">Selected series</span><span class="font-mono text-sm"- x-text="formatNumber((historyStats.series?.hourly || []).length)"></span>+ x-text="historySelectedSeriesLabel"></span></div><div class="flex justify-between items-center">- <span class="text-sm text-gray-400">Daily buckets</span>+ <span class="text-sm text-gray-400">Selected points</span><span class="font-mono text-sm"- x-text="formatNumber((historyStats.series?.daily || []).length)"></span>+ x-text="formatNumber(historySelectedPointCount)"></span>+ </div>+ <div class="flex justify-between items-center">+ <span class="text-sm text-gray-400">Average / month</span>+ <span class="font-mono text-sm"+ x-text="formatNumber(historyAverageTokensPerMonth) + ' tokens'"></span></div><div class="flex justify-between items-center"><span class="text-sm text-gray-400">Retention</span>@@ -625,7 +688,7 @@</div></div>- <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-6"><div class="bg-surface rounded-lg p-4 border border-border"><div class="text-sm font-medium mb-4 text-gray-300">Daily Savings</div><template x-if="(historyStats.series?.daily || []).length > 0">@@ -655,23 +718,79 @@</div><div class="bg-surface rounded-lg p-4 border border-border">- <div class="text-sm font-medium mb-4 text-gray-300">Recent Historical Checkpoints</div>- <div class="space-y-3">- <template x-for="point in recentHistoricalPoints" :key="point.timestamp">- <div class="flex items-center justify-between">- <div>- <div class="text-sm text-gray-300" x-text="formatDateTime(point.timestamp)"></div>- <div class="text-xs text-gray-500">Cumulative proxy compression savings</div>+ <div class="text-sm font-medium mb-4 text-gray-300">Weekly Savings</div>+ <template x-if="(historyStats.series?.weekly || []).length > 0">+ <div class="space-y-3">+ <template x-for="point in recentWeeklyHistory" :key="point.timestamp">+ <div class="flex items-center justify-between">+ <div>+ <div class="text-sm text-gray-300" x-text="formatDate(point.timestamp)"></div>+ <div class="text-xs text-gray-500"+ x-text="formatNumber(point.total_tokens_saved) + ' cumulative'"></div>+ </div>+ <div class="text-right">+ <div class="font-mono text-sm text-accent"+ x-text="formatNumber(point.tokens_saved) + ' tokens'"></div>+ <div class="text-xs text-emerald-400"+ x-text="'$' + formatCurrency(point.compression_savings_usd_delta || 0)"></div>+ </div></div>- <div class="text-right">- <div class="font-mono text-sm text-accent"- x-text="formatNumber(point.total_tokens_saved) + ' tokens'"></div>- <div class="text-xs text-emerald-400"- x-text="'$' + formatCurrency(point.compression_savings_usd || 0)"></div>+ </template>+ </div>+ </template>+ <template x-if="(historyStats.series?.weekly || []).length === 0">+ <div class="text-sm text-gray-500 italic py-8 text-center">+ Weekly rollups will appear after persisted history spans multiple days.+ </div>+ </template>+ </div>++ <div class="bg-surface rounded-lg p-4 border border-border">+ <div class="text-sm font-medium mb-4 text-gray-300">Monthly Savings</div>+ <template x-if="(historyStats.series?.monthly || []).length > 0">+ <div class="space-y-3">+ <template x-for="point in recentMonthlyHistory" :key="point.timestamp">+ <div class="flex items-center justify-between">+ <div>+ <div class="text-sm text-gray-300" x-text="formatMonth(point.timestamp)"></div>+ <div class="text-xs text-gray-500"+ x-text="formatNumber(point.total_tokens_saved) + ' cumulative'"></div>+ </div>+ <div class="text-right">+ <div class="font-mono text-sm text-accent"+ x-text="formatNumber(point.tokens_saved) + ' tokens'"></div>+ <div class="text-xs text-emerald-400"+ x-text="'$' + formatCurrency(point.compression_savings_usd_delta || 0)"></div>+ </div></div>+ </template>+ </div>+ </template>+ <template x-if="(historyStats.series?.monthly || []).length === 0">+ <div class="text-sm text-gray-500 italic py-8 text-center">+ Monthly rollups will appear after persisted history spans multiple months.+ </div>+ </template>+ </div>+ </div>++ <div class="bg-surface rounded-lg p-4 border border-border">+ <div class="text-sm font-medium mb-4 text-gray-300">Recent Historical Checkpoints</div>+ <div class="grid grid-cols-1 md:grid-cols-2 gap-3">+ <template x-for="point in recentHistoricalPoints" :key="point.timestamp">+ <div class="flex items-center justify-between rounded-lg border border-border px-3 py-3">+ <div>+ <div class="text-sm text-gray-300" x-text="formatDateTime(point.timestamp)"></div>+ <div class="text-xs text-gray-500">Cumulative proxy compression savings</div></div>- </template>- </div>+ <div class="text-right">+ <div class="font-mono text-sm text-accent"+ x-text="formatNumber(point.total_tokens_saved) + ' tokens'"></div>+ <div class="text-xs text-emerald-400"+ x-text="'$' + formatCurrency(point.compression_savings_usd || 0)"></div>+ </div>+ </div>+ </template></div></div></div>@@ -711,6 +830,7 @@version: '0.3.0',lastUpdate: 'never',viewMode: 'session',+ historyGranularity: 'daily',requestHistory: [],savingsHistory: [],expandedRows: {},@@ -792,6 +912,14 @@});},+ formatMonth(ts) {+ if (!ts) return '-';+ return new Date(ts).toLocaleDateString(undefined, {+ month: 'short',+ year: 'numeric',+ });+ },+formatDateTime(ts) {if (!ts) return '-';return new Date(ts).toLocaleString(undefined, {@@ -811,24 +939,55 @@// --- Historical View ---+ get historyGranularityOptions() {+ return [+ ['Daily', 'daily'],+ ['Weekly', 'weekly'],+ ['Monthly', 'monthly'],+ ['Checkpoints', 'history'],+ ];+ },+get hasHistoricalData() {return (this.historyStats.history || []).length > 0;},+ get historySelectedSeriesKey() {+ return this.historyGranularity === 'history' ? 'history' : this.historyGranularity;+ },++ get historySelectedSeriesLabel() {+ const labels = {+ history: 'Checkpoints',+ daily: 'Daily',+ weekly: 'Weekly',+ monthly: 'Monthly',+ };+ return labels[this.historySelectedSeriesKey] || 'History';+ },++ get historySelectedPointCount() {+ if (this.historySelectedSeriesKey === 'history') {+ return (this.historyStats.history || []).length;+ }+ return (this.historyStats.series?.[this.historySelectedSeriesKey] || []).length;+ },+get historicalTrend() {- const daily = this.historyStats.series?.daily || [];- if (daily.length >= 2) return daily;- const hourly = this.historyStats.series?.hourly || [];- if (hourly.length >= 2) return hourly;- return this.historyStats.history || [];+ if (this.historySelectedSeriesKey === 'history') {+ return this.historyStats.history || [];+ }+ return this.historyStats.series?.[this.historySelectedSeriesKey] || [];},get historyTrendLabel() {- const daily = this.historyStats.series?.daily || [];- if (daily.length >= 2) return 'Daily cumulative savings';- const hourly = this.historyStats.series?.hourly || [];- if (hourly.length >= 2) return 'Hourly cumulative savings';- return 'Checkpoint history';+ const labels = {+ history: 'Checkpoint history',+ daily: 'Daily cumulative savings',+ weekly: 'Weekly cumulative savings',+ monthly: 'Monthly cumulative savings',+ };+ return labels[this.historySelectedSeriesKey] || 'Historical savings';},get historyWindowLabel() {@@ -847,14 +1006,53 @@return Math.round(lifetime / daily.length);},+ get historyAverageTokensPerWeek() {+ const weekly = this.historyStats.series?.weekly || [];+ const lifetime = this.historyStats.lifetime?.tokens_saved || 0;+ if (weekly.length === 0) return 0;+ return Math.round(lifetime / weekly.length);+ },++ get historyAverageTokensPerMonth() {+ const monthly = this.historyStats.series?.monthly || [];+ const lifetime = this.historyStats.lifetime?.tokens_saved || 0;+ if (monthly.length === 0) return 0;+ return Math.round(lifetime / monthly.length);+ },+get recentDailyHistory() {return [...(this.historyStats.series?.daily || [])].slice(-7).reverse();},+ get recentWeeklyHistory() {+ return [...(this.historyStats.series?.weekly || [])].slice(-6).reverse();+ },++ get recentMonthlyHistory() {+ return [...(this.historyStats.series?.monthly || [])].slice(-6).reverse();+ },+get recentHistoricalPoints() {return [...(this.historyStats.history || [])].slice(-8).reverse();},+ async downloadHistory(format = 'json', series = null) {+ const selectedSeries = series || this.historySelectedSeriesKey;+ const params = new URLSearchParams({ format, series: selectedSeries });+ const response = await fetch('/stats-history?' + params.toString());+ if (!response.ok) throw new Error('Failed to export history');++ const blob = await response.blob();+ const url = window.URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.href = url;+ link.download = `headroom-stats-history-${selectedSeries}.${format}`;+ document.body.appendChild(link);+ link.click();+ link.remove();+ window.URL.revokeObjectURL(url);+ },+// --- Prefix Cache ---get cacheSavingsPercent() {diff --git a/headroom/proxy/savings_tracker.py b/headroom/proxy/savings_tracker.pyindex 443234471..84b252234 100644--- a/headroom/proxy/savings_tracker.py+++ b/headroom/proxy/savings_tracker.py@@ -12,7 +12,9 @@ import loggingimport osimport tempfileimport threading+from csv import DictWriterfrom datetime import datetime, timedelta, timezone+from io import StringIOfrom pathlib import Pathfrom typing import Any@@ -64,6 +66,19 @@ def _parse_timestamp(value: Any) -> datetime | None:return dt.astimezone(timezone.utc)+def _bucket_start(timestamp: datetime, bucket: str) -> datetime:+ if bucket == "hour":+ return timestamp.replace(minute=0, second=0, microsecond=0)+ if bucket == "day":+ return timestamp.replace(hour=0, minute=0, second=0, microsecond=0)+ if bucket == "week":+ day_start = timestamp.replace(hour=0, minute=0, second=0, microsecond=0)+ return day_start - timedelta(days=day_start.weekday())+ if bucket == "month":+ return timestamp.replace(day=1, hour=0, minute=0, second=0, microsecond=0)+ raise ValueError(f"Unsupported savings history bucket: {bucket}")++def _coerce_int(value: Any, default: int = 0) -> int:try:return max(int(value), 0)@@ -230,19 +245,55 @@ class SavingsTracker:"""Return frontend-friendly historical data for `/stats-history`."""snapshot = self.snapshot()history = snapshot["history"]+ series = {+ "hourly": self._build_rollup(history, bucket="hour"),+ "daily": self._build_rollup(history, bucket="day"),+ "weekly": self._build_rollup(history, bucket="week"),+ "monthly": self._build_rollup(history, bucket="month"),+ }return {"schema_version": snapshot["schema_version"],"generated_at": _to_utc_iso(_utc_now()),"storage_path": snapshot["storage_path"],"lifetime": snapshot["lifetime"],"history": history,- "series": {- "hourly": self._build_rollup(history, bucket="hour"),- "daily": self._build_rollup(history, bucket="day"),+ "series": series,+ "exports": {+ "default_format": "json",+ "available_formats": ["json", "csv"],+ "available_series": ["history", *series.keys()],},"retention": snapshot["retention"],}+ def export_rows(self, series: str = "history") -> list[dict[str, Any]]:+ """Return export rows for history or a rollup series."""+ response = self.history_response()+ if series == "history":+ return [dict(item) for item in response["history"]]+ return [dict(item) for item in response["series"].get(series, [])]++ def export_csv(self, series: str = "history") -> str:+ """Export history or rollup series as CSV."""+ rows = self.export_rows(series=series)+ if series == "history":+ fieldnames = ["timestamp", "total_tokens_saved", "compression_savings_usd"]+ else:+ fieldnames = [+ "timestamp",+ "tokens_saved",+ "compression_savings_usd_delta",+ "total_tokens_saved",+ "compression_savings_usd",+ ]++ buffer = StringIO()+ writer = DictWriter(buffer, fieldnames=fieldnames)+ writer.writeheader()+ for row in rows:+ writer.writerow({name: row.get(name, "") for name in fieldnames})+ return buffer.getvalue()+def snapshot(self) -> dict[str, Any]:with self._lock:history = [dict(item) for item in self._state["history"]]@@ -392,10 +443,7 @@ class SavingsTracker:if timestamp is None:continue- if bucket == "hour":- bucket_start = timestamp.replace(minute=0, second=0, microsecond=0)- else:- bucket_start = timestamp.replace(hour=0, minute=0, second=0, microsecond=0)+ bucket_start = _bucket_start(timestamp, bucket)bucket_key = _to_utc_iso(bucket_start)total_tokens_saved = _coerce_int(point.get("total_tokens_saved"))diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex a329897fc..50ccb89ce 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -7292,8 +7292,19 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:}@app.get("/stats-history")- async def stats_history():+ async def stats_history(+ format: Literal["json", "csv"] = "json",+ series: Literal["history", "hourly", "daily", "weekly", "monthly"] = "history",+ ):"""Get durable proxy compression savings history for frontends."""+ if format == "csv":+ filename = f"headroom-stats-history-{series}.csv"+ return Response(+ content=proxy.metrics.savings_tracker.export_csv(series=series),+ media_type="text/csv; charset=utf-8",+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},+ )+return proxy.metrics.savings_tracker.history_response()@app.get("/metrics")diff --git a/tests/test_proxy_savings_history.py b/tests/test_proxy_savings_history.pyindex bc459b7b6..6cdb04f2e 100644--- a/tests/test_proxy_savings_history.py+++ b/tests/test_proxy_savings_history.py@@ -247,18 +247,24 @@ def test_savings_tracker_rollups_are_chart_friendly(tmp_path, monkeypatch):tokens_saved=10,timestamp="2026-03-28T08:00:00Z",)+ tracker.record_compression_savings(+ model="gpt-4o",+ tokens_saved=20,+ timestamp="2026-04-02T14:00:00Z",+ )response = tracker.history_response()- assert response["lifetime"]["tokens_saved"] == 185- assert response["lifetime"]["compression_savings_usd"] == pytest.approx(0.185)- assert len(response["history"]) == 4+ assert response["lifetime"]["tokens_saved"] == 205+ assert response["lifetime"]["compression_savings_usd"] == pytest.approx(0.205)+ assert len(response["history"]) == 5hourly = response["series"]["hourly"]assert [point["timestamp"] for point in hourly] == ["2026-03-27T09:00:00Z","2026-03-27T10:00:00Z","2026-03-28T08:00:00Z",+ "2026-04-02T14:00:00Z",]assert hourly[0]["tokens_saved"] == 150assert hourly[0]["total_tokens_saved"] == 150@@ -266,16 +272,50 @@ def test_savings_tracker_rollups_are_chart_friendly(tmp_path, monkeypatch):assert hourly[1]["total_tokens_saved"] == 175assert hourly[2]["tokens_saved"] == 10assert hourly[2]["total_tokens_saved"] == 185+ assert hourly[3]["tokens_saved"] == 20+ assert hourly[3]["total_tokens_saved"] == 205daily = response["series"]["daily"]assert [point["timestamp"] for point in daily] == ["2026-03-27T00:00:00Z","2026-03-28T00:00:00Z",+ "2026-04-02T00:00:00Z",]assert daily[0]["tokens_saved"] == 175assert daily[0]["total_tokens_saved"] == 175assert daily[1]["tokens_saved"] == 10assert daily[1]["total_tokens_saved"] == 185+ assert daily[2]["tokens_saved"] == 20+ assert daily[2]["total_tokens_saved"] == 205++ weekly = response["series"]["weekly"]+ assert [point["timestamp"] for point in weekly] == [+ "2026-03-23T00:00:00Z",+ "2026-03-30T00:00:00Z",+ ]+ assert weekly[0]["tokens_saved"] == 185+ assert weekly[0]["total_tokens_saved"] == 185+ assert weekly[1]["tokens_saved"] == 20+ assert weekly[1]["total_tokens_saved"] == 205++ monthly = response["series"]["monthly"]+ assert [point["timestamp"] for point in monthly] == [+ "2026-03-01T00:00:00Z",+ "2026-04-01T00:00:00Z",+ ]+ assert monthly[0]["tokens_saved"] == 185+ assert monthly[0]["total_tokens_saved"] == 185+ assert monthly[1]["tokens_saved"] == 20+ assert monthly[1]["total_tokens_saved"] == 205++ assert response["exports"]["available_formats"] == ["json", "csv"]+ assert response["exports"]["available_series"] == [+ "history",+ "hourly",+ "daily",+ "weekly",+ "monthly",+ ]def test_stats_history_persists_across_restarts_and_stats_stays_compatible(tmp_path, monkeypatch):@@ -306,7 +346,8 @@ def test_stats_history_persists_across_restarts_and_stats_stays_compatible(tmp_passert history_data["schema_version"] == 1assert history_data["storage_path"] == str(savings_path)assert history_data["lifetime"]["tokens_saved"] == 40- assert list(history_data["series"].keys()) == ["hourly", "daily"]+ assert list(history_data["series"].keys()) == ["hourly", "daily", "weekly", "monthly"]+ assert history_data["exports"]["available_series"][-2:] == ["weekly", "monthly"]with TestClient(create_app(config)) as client:history = client.get("/stats-history")@@ -323,6 +364,35 @@ def test_stats_history_persists_across_restarts_and_stats_stays_compatible(tmp_passert persisted["lifetime"]["tokens_saved"] == 55+def test_stats_history_csv_export_is_frontend_friendly(tmp_path, monkeypatch):+ savings_path = tmp_path / "proxy_savings.json"+ monkeypatch.setenv("HEADROOM_SAVINGS_PATH", str(savings_path))++ config = ProxyConfig(+ cache_enabled=False,+ rate_limit_enabled=False,+ log_requests=False,+ )++ with TestClient(create_app(config)) as client:+ _record_request(client, model="gpt-4o", tokens_saved=40)+ _record_request(client, model="gpt-4o", tokens_saved=10)++ response = client.get("/stats-history?format=csv&series=daily")+ assert response.status_code == 200+ assert response.headers["content-type"].startswith("text/csv")+ assert "attachment; filename=\"headroom-stats-history-daily.csv\"" == response.headers[+ "content-disposition"+ ]+ lines = response.text.strip().splitlines()+ assert lines[0] == (+ "timestamp,tokens_saved,compression_savings_usd_delta,total_tokens_saved,"+ "compression_savings_usd"+ )+ assert len(lines) >= 2+ assert "total_tokens_saved" in lines[0]++def test_malformed_savings_state_is_ignored_safely(tmp_path, monkeypatch):savings_path = tmp_path / "proxy_savings.json"savings_path.write_text("{not valid json", encoding="utf-8")@@ -359,3 +429,6 @@ def test_dashboard_includes_history_toggle_and_endpoint(tmp_path, monkeypatch):assert "Session" in htmlassert "Historical" in htmlassert "fetch('/stats-history')" in html+ assert "Export CSV" in html+ assert "Weekly Savings" in html+ assert "Monthly Savings" in html