: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(postgres): handle out-of-range timestamps during import (#63787)
Tom Owerse0c69229dc6e
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex 704ae91d6fa9..f6ba5253a7e7 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -7,7 +7,7 @@ import collectionsimport dataclassesfrom collections.abc import Callable, Iteratorfrom contextlib import _GeneratorContextManager, contextmanager-from datetime import UTC, date, datetime+from datetime import UTC, date, datetime, timezonefrom typing import TYPE_CHECKING, Any, Literal, LiteralString, Optional, castif TYPE_CHECKING:@@ -20,6 +20,7 @@ import pyarrow as paimport structlogfrom psycopg import sqlfrom psycopg.adapt import Loader+from psycopg.types.datetime import TimestampLoader, TimestamptzLoaderfrom structlog.types import FilteringBoundLoggerfrom posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_table_function@@ -1016,6 +1017,57 @@ class SafeDateLoader(Loader):return date.max+def _clamp_out_of_range_timestamp(data, *, tzinfo: timezone | None) -> datetime:+ """Map a Postgres timestamp value outside Python's datetime range onto datetime.min/max.++ PostgreSQL timestamps span years 4713 BC to 294276 AD and include 'infinity'/'-infinity',+ far wider than Python's datetime (year 1 to 9999). We pick the boundary by sign so values+ 'before year 1' (BC dates, '-infinity', negative years) clamp low and everything else+ clamps high. `tzinfo` keeps the result aware/naive to match the column's Arrow type.+ """+ s = bytes(data).decode("utf-8", "replace").strip().lower()+ if s == "-infinity" or s.startswith("-") or "bc" in s:+ return datetime.min.replace(tzinfo=tzinfo)+ return datetime.max.replace(tzinfo=tzinfo)+++class SafeTimestampLoader(TimestampLoader):+ """Load PostgreSQL timestamps, handling values beyond Python's datetime range.++ psycopg's default loader raises `DataError` on timestamps outside Python's datetime+ range (years > 9999, 'infinity'/'-infinity'), which aborts the whole table sync. We+ defer to the default loader for in-range values and clamp the rest, mirroring+ `SafeDateLoader`. `timestamp` columns map to a naive Arrow type, so the clamp stays naive.+ """++ # psycopg short-circuits SQL NULL before the loader, so `data` is never None in practice;+ # the guard mirrors SafeDateLoader's defensive parity, hence the widened return + override ignore.+ def load(self, data) -> datetime | None: # type: ignore[override]+ if data is None:+ return None+ try:+ return super().load(data)+ except psycopg.DataError:+ return _clamp_out_of_range_timestamp(data, tzinfo=None)+++class SafeTimestamptzLoader(TimestamptzLoader):+ """`timestamptz` counterpart of `SafeTimestampLoader` (see its docstring).++ `timestamptz` columns map to a UTC-aware Arrow type, so the clamp is made tz-aware to+ avoid mixing naive and aware datetimes in the same Arrow column.+ """++ # See SafeTimestampLoader.load for why the override is widened/ignored.+ def load(self, data) -> datetime | None: # type: ignore[override]+ if data is None:+ return None+ try:+ return super().load(data)+ except psycopg.DataError:+ return _clamp_out_of_range_timestamp(data, tzinfo=UTC)++def _build_query(schema: str,table_name: str,@@ -2116,6 +2168,8 @@ def postgres_source(connection.adapters.register_loader("tstzrange", RangeAsStringLoader)connection.adapters.register_loader("daterange", RangeAsStringLoader)connection.adapters.register_loader("date", SafeDateLoader)+ connection.adapters.register_loader("timestamp", SafeTimestampLoader)+ connection.adapters.register_loader("timestamptz", SafeTimestamptzLoader)# 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.pyindex 546e087924fa..c3a7b669c32d 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -47,6 +47,8 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (PostgreSQLColumn,RangeAsStringLoader,SafeDateLoader,+ SafeTimestampLoader,+ SafeTimestamptzLoader,_build_count_query,_build_query,_connect_with_dropped_retry,@@ -108,6 +110,58 @@ class TestSafeDateLoader:assert loader.load(input_data) == expected+class TestSafeTimestampLoader:+ @pytest.fixture+ def loader(self):+ return SafeTimestampLoader(oid=1114)++ @pytest.mark.parametrize(+ "input_data,expected",+ [+ (b"2024-01-15 10:30:00", datetime(2024, 1, 15, 10, 30, 0)),+ (b"2024-01-15 10:30:00.123456", datetime(2024, 1, 15, 10, 30, 0, 123456)),+ (b"0001-01-01 00:00:00", datetime(1, 1, 1, 0, 0, 0)),+ (b"9999-12-31 23:59:59", datetime(9999, 12, 31, 23, 59, 59)),+ (b"200082-12-31 18:30:00", datetime.max),+ (b"20424-11-14 10:30:00", datetime.max),+ (b"10000-01-01 00:00:00", datetime.max),+ (b"infinity", datetime.max),+ (b"-infinity", datetime.min),+ (b"0044-03-15 00:00:00 BC", datetime.min),+ (None, None),+ ],+ )+ def test_load_timestamps(self, loader, input_data, expected):+ assert loader.load(input_data) == expected++ def test_clamped_values_are_naive(self, loader):+ assert loader.load(b"200082-12-31 18:30:00").tzinfo is None+++class TestSafeTimestamptzLoader:+ @pytest.fixture+ def loader(self):+ return SafeTimestamptzLoader(oid=1184)++ @pytest.mark.parametrize(+ "input_data,expected",+ [+ (b"2024-01-15 10:30:00+00", datetime(2024, 1, 15, 10, 30, 0, tzinfo=UTC)),+ (b"200082-12-31 18:30:00+00", datetime.max.replace(tzinfo=UTC)),+ (b"infinity", datetime.max.replace(tzinfo=UTC)),+ (b"-infinity", datetime.min.replace(tzinfo=UTC)),+ (None, None),+ ],+ )+ def test_load_timestamptz(self, loader, input_data, expected):+ assert loader.load(input_data) == expected++ def test_clamped_values_are_utc_aware(self, loader):+ # timestamptz columns map to a UTC-aware Arrow type, so clamps must stay aware+ # to avoid mixing naive and aware datetimes in the same column.+ assert loader.load(b"200082-12-31 18:30:00+00").tzinfo is UTC++class TestPostgresImplementationWiring:def test_source_exposes_postgres_implementation_singleton(self):source = PostgresSource()