Skip to content

The agent that grows with you

fix(gateway): handle early local timestamp strings on Windows

tank321476268f16732
diff --git a/gateway/message_timestamps.py b/gateway/message_timestamps.py
index 484a14334e6..51e3567027b 100644
--- a/gateway/message_timestamps.py
+++ b/gateway/message_timestamps.py
@@ -7,7 +7,10 @@ persisted message content should stay clean so replay does not accumulate
from __future__ import annotations
+import errno
import re
+import sys
+import time
from datetime import datetime, timezone
from typing import Any, Optional, Tuple
@@ -28,11 +31,29 @@ _TIMESTAMP_PREFIX_RE = re.compile(
)
-def _localize(dt: datetime, tz) -> float:
- """Epoch for ``dt``; naive values take ``tz`` if given, else the local zone."""
- if dt.tzinfo is None:
- dt = dt.replace(tzinfo=tz) if tz is not None else dt.astimezone()
- return float(dt.timestamp())
+def _localize(dt: datetime, tz) -> Optional[float]:
+ """Epoch for ``dt`` in ``tz`` or the local zone; None outside platform limits."""
+ naive_local = dt.tzinfo is None and tz is None
+ try:
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=tz) if tz is not None else dt.astimezone()
+ return float(dt.timestamp())
+ except (OverflowError, ValueError):
+ return None
+ except OSError as exc:
+ if not (sys.platform == "win32" and naive_local and exc.errno == errno.EINVAL):
+ return None
+ # Windows' fold probe can reject the first Unix day. mktime can
+ # resolve those local wall times without changing their meaning.
+ # Limit recovery to that fold-free interval and reject normalization.
+ wall_time = dt.timetuple()
+ try:
+ epoch = time.mktime(wall_time)
+ if 0 <= epoch < 86_400 and time.localtime(epoch)[:6] == wall_time[:6]:
+ return float(epoch + dt.microsecond / 1_000_000)
+ except (OSError, OverflowError, ValueError):
+ pass
+ return None
def _parse_iso(text: str, tz=None) -> Optional[float]:
@@ -83,9 +104,12 @@ def format_message_timestamp(ts_value: Any, tz=None) -> str:
epoch = coerce_message_timestamp(ts_value, tz=tz)
if epoch is None:
return ""
- # An early positive epoch can fall in 1969 locally. Starting from aware UTC
- # avoids Windows' negative-time mktime path in naive astimezone().
- dt = datetime.fromtimestamp(epoch, tz=tz) if tz is not None else datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone()
+ try:
+ # An early positive epoch can fall in 1969 locally. Starting from aware
+ # UTC avoids Windows' negative-time fold probe in naive astimezone().
+ dt = datetime.fromtimestamp(epoch, tz=tz) if tz is not None else datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone()
+ except (OSError, OverflowError, ValueError):
+ return ""
return f"[{safe_strftime(dt, '%a %Y-%m-%d %H:%M:%S %Z')}]"
diff --git a/tests/gateway/test_message_timestamps.py b/tests/gateway/test_message_timestamps.py
index 93f68581fe8..b9134b6dfd6 100644
--- a/tests/gateway/test_message_timestamps.py
+++ b/tests/gateway/test_message_timestamps.py
@@ -1,3 +1,4 @@
+import sys
from datetime import datetime, timezone
from unittest.mock import Mock
from zoneinfo import ZoneInfo
@@ -6,6 +7,8 @@ import pytest
from gateway import message_timestamps
from gateway.message_timestamps import (
+ coerce_message_timestamp,
+ format_message_timestamp,
render_user_content_with_timestamp,
)
from hermes_time import safe_strftime
@@ -28,6 +31,121 @@ def test_render_numeric_timestamp_preserves_instant_in_system_timezone(epoch):
assert render_user_content_with_timestamp("hello", epoch) == f"[{prefix}] hello"
[email protected]("epoch", [0.0, 1.123456, 86_399.0])
+def test_early_naive_iso_preserves_system_local_instant(epoch):
+ local = datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone()
+ text = local.replace(tzinfo=None).isoformat()
+
+ assert coerce_message_timestamp(text) == pytest.approx(epoch, rel=0, abs=1e-6)
+
+
[email protected]("style", ["human", "iso"])
[email protected]("epoch", [0.0, 1.0, 86_399.0])
+def test_early_embedded_local_time_preserves_instant(style, epoch):
+ local = datetime.fromtimestamp(epoch, tz=timezone.utc).astimezone()
+ stamp = (safe_strftime(local, "%a %Y-%m-%d %H:%M:%S") if style == "human"
+ else local.replace(tzinfo=None).isoformat())
+ content = f"[{stamp}] hello"
+
+ assert render_user_content_with_timestamp(content, 1_000_000_000.0) == (
+ render_user_content_with_timestamp("hello", epoch)
+ )
+
+
[email protected]("style", ["human", "iso"])
[email protected]("enabled", [False, True])
+def test_early_embedded_local_time_replays_with_injection_on_or_off(style, enabled):
+ from gateway.run import _build_gateway_agent_history
+
+ local = datetime.fromtimestamp(1.0, tz=timezone.utc).astimezone()
+ stamp = (safe_strftime(local, "%a %Y-%m-%d %H:%M:%S") if style == "human"
+ else local.replace(tzinfo=None).isoformat())
+ content = f"[{stamp}] hello"
+ history, _ = _build_gateway_agent_history(
+ [{"role": "user", "content": content, "timestamp": 1_000_000_000.0},
+ {"role": "assistant", "content": "hi"}],
+ inject_timestamps=enabled,
+ )
+
+ expected = render_user_content_with_timestamp("hello", 1.0) if enabled else content
+ assert history[0]["content"] == expected
+ assert history[1]["content"] == "hi"
+
+
+def test_early_embedded_local_time_renders_in_observed_context():
+ from gateway.run import _build_gateway_agent_history
+
+ local = datetime.fromtimestamp(1.0, tz=timezone.utc).astimezone()
+ content = f"[{local.replace(tzinfo=None).isoformat()}] hello"
+ history, observed = _build_gateway_agent_history(
+ [{"role": "user", "content": content, "observed": True}],
+ inject_timestamps=True, channel_prompt="observed Telegram group context",
+ )
+
+ assert history == []
+ assert observed == render_user_content_with_timestamp("hello", 1.0)
+
+
[email protected]("fold", [0, 1])
[email protected]("wall_time", [
+ datetime(2026, 1, 15, 12), datetime(2026, 7, 15, 12),
+ datetime(2026, 3, 8, 2, 30), datetime(2026, 11, 1, 1, 30),
+])
+def test_modern_local_conversion_keeps_existing_fold_and_gap_behavior(wall_time, fold):
+ dt = wall_time.replace(fold=fold)
+
+ assert message_timestamps._localize(dt, None) == dt.astimezone().timestamp()
+
+
[email protected]("text", ["1969-06-01T12:00:00", "2026-07-15T12:00:00"])
+def test_explicit_timezone_parsing_preserves_wall_time(text):
+ expected = datetime.fromisoformat(text).replace(tzinfo=BERLIN).timestamp()
+
+ assert coerce_message_timestamp(text, tz=BERLIN) == expected
+
+
[email protected](sys.platform != "win32", reason="Windows' pre-epoch range limit")
+def test_unsupported_local_iso_is_uninterpretable_instead_of_raising():
+ assert coerce_message_timestamp("1969-06-01T12:00:00") is None
+
+
[email protected]("epoch", [float("nan"), float("inf"), -1.0])
[email protected](sys.platform != "win32", reason="Windows' pre-epoch range limit")
+def test_unrenderable_epoch_preserves_the_message_body(epoch):
+ assert format_message_timestamp(epoch) == ""
+ assert render_user_content_with_timestamp("hello", epoch) == "hello"
+
+
[email protected](sys.platform != "win32", reason="Windows' pre-epoch range limit")
+def test_unsupported_embedded_time_keeps_metadata_fallback():
+ content = "[Sun 1969-06-01 12:00:00] hello"
+
+ assert render_user_content_with_timestamp(content, 1_000_000_000.0) == (
+ render_user_content_with_timestamp("hello", 1_000_000_000.0)
+ )
+
+
[email protected]("enabled", [False, True])
[email protected](sys.platform != "win32", reason="Windows' pre-epoch range limit")
+def test_unsupported_embedded_time_does_not_abort_history(enabled):
+ from gateway.run import _build_gateway_agent_history
+
+ content = "[Sun 1969-06-01 12:00:00] hello"
+ history, _ = _build_gateway_agent_history(
+ [{"role": "user", "content": content}], inject_timestamps=enabled
+ )
+
+ assert history[0]["content"] == ("hello" if enabled else content)
+
+
@pytest.mark.platforms("windows")
def test_system_timezone_conversion_starts_from_aware_utc(monkeypatch):
# Record real datetime calls: output alone also passes with the unsafe