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(utils): normalize timezone-aware datetimes in format_timestamp (#3116)

Abhay Singhb625d188c507
diff --git a/headroom/utils.py b/headroom/utils.py
index a0deb5c80..9ff9e0404 100644
--- a/headroom/utils.py
+++ b/headroom/utils.py
@@ -106,9 +106,19 @@ def compute_prefix_hash(messages: list[dict[str, Any]], prefix_count: int | None
def format_timestamp(dt: datetime | None = None) -> str:
- """Format datetime as ISO8601 string."""
+ """Format a datetime as an ISO 8601 UTC string with a ``Z`` suffix.
+
+ A timezone-aware ``dt`` is converted to UTC first; a naive ``dt`` is assumed
+ to already be UTC. This keeps the output valid: appending ``Z`` to an aware
+ datetime's ``isoformat()`` would emit ``...+00:00Z`` (which even
+ ``datetime.fromisoformat`` rejects), and for a non-UTC offset it would label
+ the wrong instant as UTC. Shipped integrations pass
+ ``datetime.now(timezone.utc)`` (aware), so this path is live.
+ """
if dt is None:
- dt = datetime.now(timezone.utc).replace(tzinfo=None)
+ dt = datetime.now(timezone.utc)
+ if dt.tzinfo is not None:
+ dt = dt.astimezone(timezone.utc).replace(tzinfo=None)
return dt.isoformat() + "Z"
diff --git a/tests/test_utils.py b/tests/test_utils.py
index ecf36f17f..84b79e8b5 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from datetime import datetime
+from datetime import datetime, timedelta, timezone
from headroom import utils
@@ -78,6 +78,22 @@ def test_timestamp_marker_and_json_helpers() -> None:
assert utils.parse_timestamp(ts) == datetime(2026, 4, 23, 6, 0, 0)
assert utils.parse_timestamp("2026-04-23T06:00:00") == datetime(2026, 4, 23, 6, 0, 0)
+
+def test_format_timestamp_normalizes_aware_datetimes() -> None:
+ # Shipped integrations pass datetime.now(timezone.utc) (aware). Appending a
+ # bare "Z" to an aware isoformat used to emit "...+00:00Z" — invalid ISO
+ # 8601 that datetime.fromisoformat itself rejects.
+ aware_utc = datetime(2026, 4, 23, 6, 0, 0, tzinfo=timezone.utc)
+ ts = utils.format_timestamp(aware_utc)
+ assert ts == "2026-04-23T06:00:00Z"
+ # The stored string must round-trip through a strict parser.
+ assert datetime.fromisoformat(ts.rstrip("Z")) == datetime(2026, 4, 23, 6, 0, 0)
+
+ # A non-UTC offset must be converted to UTC, not just stamped "Z" onto the
+ # local wall-clock time (which would mislabel the instant).
+ east = datetime(2026, 4, 23, 6, 0, 0, tzinfo=timezone(timedelta(hours=5)))
+ assert utils.format_timestamp(east) == "2026-04-23T01:00:00Z"
+
marker = utils.create_marker("tool_digest", sha256="abc", count="2")
assert marker == '<headroom:tool_digest sha256="abc" count="2">'
assert utils.create_tool_digest_marker("abc") == '<headroom:tool_digest sha256="abc">'