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.

fix(storage): normalize timezone-aware JSONL time filters (#4063)

hi-neasonbf34ccf58861
diff --git a/headroom/storage/jsonl.py b/headroom/storage/jsonl.py
index 0e7ec78d2..e87d7b9a0 100644
--- a/headroom/storage/jsonl.py
+++ b/headroom/storage/jsonl.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import heapq
import json
from collections.abc import Iterator
-from datetime import datetime
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -14,6 +14,13 @@ from ..utils import format_timestamp, parse_timestamp
from .base import Storage
+def _utc_bound(dt: datetime | None) -> datetime | None:
+ """Normalize a filter bound to the naive UTC used by stored timestamps."""
+ if dt is not None and dt.tzinfo is not None:
+ return dt.astimezone(timezone.utc).replace(tzinfo=None)
+ return dt
+
+
class JSONLStorage(Storage):
"""JSONL file-based metrics storage."""
@@ -130,6 +137,10 @@ class JSONLStorage(Storage):
if limit == 0:
return []
+ # Stored timestamps are naive UTC; apply the same normalization to filters.
+ start_time = _utc_bound(start_time)
+ end_time = _utc_bound(end_time)
+
def _matches(metrics: RequestMetrics) -> bool:
if start_time is not None and metrics.timestamp < start_time:
return False
@@ -156,6 +167,9 @@ class JSONLStorage(Storage):
mode: str | None = None,
) -> int:
"""Count metrics matching filters."""
+ start_time = _utc_bound(start_time)
+ end_time = _utc_bound(end_time)
+
count = 0
for metrics in self.iter_all():
@@ -194,6 +208,9 @@ class JSONLStorage(Storage):
end_time: datetime | None = None,
) -> dict[str, Any]:
"""Get summary statistics."""
+ start_time = _utc_bound(start_time)
+ end_time = _utc_bound(end_time)
+
total_requests = 0
total_tokens_before = 0
total_tokens_after = 0
diff --git a/tests/test_storage/test_jsonl.py b/tests/test_storage/test_jsonl.py
index 4d18e8150..737a60b5c 100644
--- a/tests/test_storage/test_jsonl.py
+++ b/tests/test_storage/test_jsonl.py
@@ -1,6 +1,7 @@
"""Tests for JSONL storage query paging (shared newest-first contract)."""
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
import pytest
@@ -64,6 +65,31 @@ def _ids(metrics: list[RequestMetrics]) -> list[str]:
return [m.request_id for m in metrics]
[email protected]("method", ["query", "count", "get_summary_stats"])
+def test_jsonl_aware_time_bounds_are_inclusive(method: str, tmp_path: Path) -> None:
+ """Aware bounds preserve their UTC instant and include the exact boundary."""
+ boundary = datetime(2026, 4, 23, 23, 59, 59, 500000, tzinfo=timezone.utc)
+ local_boundary = boundary.astimezone(timezone(timedelta(hours=5, minutes=30)))
+ with JSONLStorage(str(tmp_path / "metrics.jsonl")) as storage:
+ for request_id, delta in [("before", -1), ("boundary", 0), ("after", 1)]:
+ storage.save(_metrics(request_id, boundary + timedelta(microseconds=delta)))
+ scenarios = [
+ ({"start_time": local_boundary}, ["after", "boundary"]),
+ ({"end_time": local_boundary}, ["boundary", "before"]),
+ ({"start_time": local_boundary, "end_time": local_boundary}, ["boundary"]),
+ ]
+ for filters, expected_ids in scenarios:
+ result = getattr(storage, method)(**filters)
+ if method == "query":
+ assert _ids(result) == expected_ids, filters
+ elif method == "count":
+ assert result == len(expected_ids), filters
+ else:
+ assert result["total_requests"] == len(expected_ids), filters
+ assert result["total_tokens_before"] == 1000 * len(expected_ids), filters
+ assert result["total_tokens_after"] == 800 * len(expected_ids), filters
+
+
def _assert_timestamp_desc(metrics: list[RequestMetrics]) -> None:
stamps = [m.timestamp for m in metrics]
assert stamps == sorted(stamps, reverse=True)