Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(postgres): clamp time '24:00:00' instead of crashing the sync (#63779)

Tom Owers61e501eb4baf
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 30f8d47a9c2f..8e289956bb62 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -7,7 +7,13 @@ import collections
import dataclasses
from collections.abc import Callable, Iterator
from contextlib import _GeneratorContextManager, contextmanager
-from datetime import UTC, date, datetime, timezone
+from datetime import (
+ UTC,
+ date,
+ datetime,
+ time as datetime_time,
+ timezone,
+)
from typing import TYPE_CHECKING, Any, Literal, LiteralString, Optional, cast
if TYPE_CHECKING:
@@ -20,7 +26,7 @@ import pyarrow as pa
import structlog
from psycopg import sql
from psycopg.adapt import Loader
-from psycopg.types.datetime import TimestampLoader, TimestamptzLoader
+from psycopg.types.datetime import TimeLoader, TimestampLoader, TimestamptzLoader, TimetzLoader
from structlog.types import FilteringBoundLogger
from posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_table_function
@@ -1137,6 +1143,59 @@ class SafeTimestamptzLoader(TimestamptzLoader):
return _clamp_out_of_range_timestamp(data, tzinfo=UTC)
+def _clamp_pg_hour_24(data) -> bytes | None:
+ """Clamp a Postgres '24:00:00' time/timetz value to the max Python time.
+
+ PostgreSQL accepts '24:00:00' as the maximum value for the `time` and
+ `timetz` types (end-of-day midnight), but Python's datetime.time caps the
+ hour at 23. The time portion of an hour-24 value is always exactly
+ '24:00:00', so we return an equivalent buffer with the time clamped to the
+ maximum representable value, preserving any timezone suffix. Returns None
+ for any value that is not an hour-24 time, so callers re-raise as usual.
+ """
+ s = bytes(data).decode("utf-8")
+ if not s.startswith("24:"):
+ return None
+ rest = s[len("24:00:00") :]
+ tz_suffix = ""
+ for i, ch in enumerate(rest):
+ if ch in "+-":
+ tz_suffix = rest[i:]
+ break
+ return ("23:59:59.999999" + tz_suffix).encode("utf-8")
+
+
+def _load_time_clamping_hour_24(super_load: Callable[[Any], datetime_time], data) -> datetime_time:
+ """Run psycopg's default time loader, clamping the '24:00:00' edge case.
+
+ Mirrors SafeDateLoader's clamp-to-max behaviour: a Postgres end-of-day
+ '24:00:00' (which Python's datetime.time cannot represent) is clamped to
+ time.max, while every other value — and any genuine parse error — is
+ delegated to psycopg's default loader.
+ """
+ try:
+ return super_load(data)
+ except psycopg.DataError:
+ clamped = _clamp_pg_hour_24(data)
+ if clamped is None:
+ raise
+ return super_load(clamped)
+
+
+class SafeTimeLoader(TimeLoader):
+ """Load PostgreSQL `time` values, clamping the '24:00:00' edge case."""
+
+ def load(self, data) -> datetime_time:
+ return _load_time_clamping_hour_24(super().load, data)
+
+
+class SafeTimetzLoader(TimetzLoader):
+ """Load PostgreSQL `timetz` values, clamping '24:00:00' while preserving the timezone offset."""
+
+ def load(self, data) -> datetime_time:
+ return _load_time_clamping_hour_24(super().load, data)
+
+
def _build_query(
schema: str,
table_name: str,
@@ -2263,6 +2322,8 @@ def postgres_source(
connection.adapters.register_loader("date", SafeDateLoader)
connection.adapters.register_loader("timestamp", SafeTimestampLoader)
connection.adapters.register_loader("timestamptz", SafeTimestamptzLoader)
+ connection.adapters.register_loader("time", SafeTimeLoader)
+ connection.adapters.register_loader("timetz", SafeTimetzLoader)
# Bump statement_timeout for the streaming connection. A server
# cursor FETCH inherits the session statement_timeout, and on
# wide/partitioned scans the source's default (often 30-60s)
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 448dd31ef46f..b8427a919f3a 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -1,6 +1,6 @@
from collections.abc import Iterable
from contextlib import contextmanager
-from datetime import UTC, date, datetime, timedelta
+from datetime import UTC, date, datetime, time, timedelta, timezone
from typing import Any, cast
import pytest
@@ -48,8 +48,10 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
PostgreSQLColumn,
RangeAsStringLoader,
SafeDateLoader,
+ SafeTimeLoader,
SafeTimestampLoader,
SafeTimestamptzLoader,
+ SafeTimetzLoader,
_build_count_query,
_build_query,
_connect_to_postgres,
@@ -166,6 +168,51 @@ class TestSafeTimestamptzLoader:
assert loader.load(b"200082-12-31 18:30:00+00").tzinfo is UTC
+class TestSafeTimeLoader:
+ @pytest.fixture
+ def loader(self):
+ return SafeTimeLoader(oid=1083)
+
+ @pytest.mark.parametrize(
+ "input_data,expected",
+ [
+ # Postgres allows 24:00:00 (end-of-day) but Python's time caps at 23 — clamp to max.
+ (b"24:00:00", time.max),
+ (b"24:00:00.000000", time.max),
+ # Normal values are parsed unchanged.
+ (b"00:00:00", time(0, 0, 0)),
+ (b"13:45:30", time(13, 45, 30)),
+ (b"13:45:30.123456", time(13, 45, 30, 123456)),
+ (b"23:59:59.999999", time(23, 59, 59, 999999)),
+ ],
+ )
+ def test_load_times(self, loader, input_data, expected):
+ assert loader.load(input_data) == expected
+
+ def test_non_hour_24_errors_still_propagate(self, loader):
+ with pytest.raises(psycopg.DataError):
+ loader.load(b"99:99:99")
+
+
+class TestSafeTimetzLoader:
+ @pytest.fixture
+ def loader(self):
+ return SafeTimetzLoader(oid=1266)
+
+ @pytest.mark.parametrize(
+ "input_data,expected",
+ [
+ (b"24:00:00+00", time.max.replace(tzinfo=UTC)),
+ (b"24:00:00.000000+00", time.max.replace(tzinfo=UTC)),
+ (b"24:00:00+05:30", time.max.replace(tzinfo=timezone(timedelta(hours=5, minutes=30)))),
+ (b"24:00:00-08", time.max.replace(tzinfo=timezone(timedelta(hours=-8)))),
+ (b"13:45:30+02", time(13, 45, 30, tzinfo=timezone(timedelta(hours=2)))),
+ ],
+ )
+ def test_load_timetz(self, loader, input_data, expected):
+ assert loader.load(input_data) == expected
+
+
class TestPostgresImplementationWiring:
def test_source_exposes_postgres_implementation_singleton(self):
source = PostgresSource()