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(redshift): clamp out-of-range timestamps instead of failing the sync (#103046)

Tom Owersa0c802c162b5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
index ad2d45d20e1b..1c5d9fef8130 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
@@ -15,7 +15,7 @@ import time
import collections
from collections.abc import Callable, Iterator
from contextlib import contextmanager
-from datetime import date
+from datetime import UTC, date, datetime, timezone
from typing import Any, Literal, LiteralString, Optional, TypeVar, cast
import psycopg
@@ -24,6 +24,7 @@ import structlog
from psycopg import pq, sql
from psycopg.adapt import Loader
from psycopg.pq import TransactionStatus
+from psycopg.types.datetime import TimestampLoader, TimestamptzLoader
from structlog.types import FilteringBoundLogger
from posthog.dataclasses import frozen
@@ -91,6 +92,8 @@ __all__ = [
"RedshiftColumn",
"RedshiftImplementation",
"SafeDateLoader",
+ "SafeTimestampLoader",
+ "SafeTimestamptzLoader",
"filter_redshift_incremental_fields",
]
@@ -378,6 +381,57 @@ class SafeDateLoader(Loader):
return date(year, month, day)
+def _clamp_out_of_range_timestamp(data, *, tzinfo: timezone | None) -> datetime:
+ """Map a Redshift timestamp value outside Python's datetime range onto datetime.min/max.
+
+ Redshift's timestamp range spans 4713 BC to 294276 AD, 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, mirroring
+ `SafeDateLoader`. `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 Redshift timestamps, handling values beyond Python's datetime range.
+
+ psycopg's default loader raises `DataError` on timestamps outside Python's datetime
+ range (BC dates, '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 _redshift_select_clause(
enabled_columns: Optional[list[str]],
primary_keys: Optional[list[str]],
@@ -955,6 +1009,8 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
}
with psycopg.connect(**connect_kwargs) as conn:
conn.adapters.register_loader("date", SafeDateLoader)
+ conn.adapters.register_loader("timestamp", SafeTimestampLoader)
+ conn.adapters.register_loader("timestamptz", SafeTimestamptzLoader)
yield conn
# ------------------------------------------------------------------
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
index 37674b832549..e3950d2fbe9b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -1,6 +1,6 @@
from collections.abc import Callable, Iterator
from contextlib import contextmanager
-from datetime import date
+from datetime import UTC, date, datetime
from typing import Any
import pytest
@@ -38,6 +38,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.r
RedshiftColumn,
RedshiftImplementation,
SafeDateLoader,
+ SafeTimestampLoader,
+ SafeTimestamptzLoader,
_build_query,
_explain_query,
_fetch_arrow_batches,
@@ -323,6 +325,41 @@ class TestSafeDateLoader:
loader.load(input_data)
+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"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"10000-01-01 00:00:00", datetime.max),
+ (b"infinity", datetime.max),
+ (b"-infinity", datetime.min),
+ # Reproduces the reported incident: psycopg's default `TimestampLoader` raises
+ # `DataError: timestamp too small (before year 1)`, aborting the sync.
+ (b"0001-02-11 00:00:00 BC", datetime.min),
+ (None, None),
+ ],
+ )
+ def test_load_timestamps(self, loader, input_data, expected):
+ assert loader.load(input_data) == expected
+
+
+class TestSafeTimestamptzLoader:
+ @pytest.fixture
+ def loader(self):
+ return SafeTimestamptzLoader(oid=1184)
+
+ def test_clamps_out_of_range_value_with_utc_tzinfo(self, loader):
+ # `timestamptz` columns map to a UTC-aware Arrow type; mixing in a naive clamp would
+ # raise when the batch tries to combine aware and naive datetimes in one column.
+ assert loader.load(b"0001-02-11 00:00:00 BC") == datetime.min.replace(tzinfo=UTC)
+
+
# ---------------------------------------------------------------------------
# Per-cursor metadata queries — exercise impl methods directly
# ---------------------------------------------------------------------------
@@ -1880,8 +1917,8 @@ class TestConnect:
assert kwargs["keepalives_count"] == 3
assert kwargs["tcp_user_timeout"] == 60000
- def test_connect_registers_safe_date_loader(self, mocker):
- # Wiring guard: SafeDateLoader only protects a sync if it's actually registered on the
+ def test_connect_registers_safe_date_and_timestamp_loaders(self, mocker):
+ # Wiring guard: these loaders only protect a sync if they're actually registered on the
# connection every `connect()` call produces.
mocker.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.open_ssh_tunnel",
@@ -1898,6 +1935,8 @@ class TestConnect:
pass
mock_conn.adapters.register_loader.assert_any_call("date", SafeDateLoader)
+ mock_conn.adapters.register_loader.assert_any_call("timestamp", SafeTimestampLoader)
+ mock_conn.adapters.register_loader.assert_any_call("timestamptz", SafeTimestamptzLoader)
class TestGetConnectionMetadata: