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 dates instead of crashing the sync (#79231)

Tom Owers00dc09d10d30
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 50054d3aabd0..27586739bfcd 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
@@ -13,6 +13,7 @@ from __future__ import annotations
import collections
from collections.abc import Iterator
from contextlib import contextmanager
+from datetime import date
from typing import Any, Literal, LiteralString, Optional, cast
import psycopg
@@ -72,6 +73,7 @@ __all__ = [
"JsonAsStringLoader",
"RedshiftColumn",
"RedshiftImplementation",
+ "SafeDateLoader",
"filter_redshift_incremental_fields",
]
@@ -197,6 +199,45 @@ class JsonAsStringLoader(Loader):
return bytes(data).decode("utf-8")
+class SafeDateLoader(Loader):
+ """Load Redshift dates, handling edge cases beyond Python's date range.
+
+ Redshift's `date` range (4713 BC to 294276 AD) is far wider than Python's `datetime.date`
+ (year 1 to year 9999). psycopg's default loader raises `DataError` on anything outside that
+ range — including a bare `0000-01-01` — which aborts the whole table sync. We clamp
+ out-of-range values to `date.min`/`date.max` instead, mirroring the equivalent Postgres fix.
+
+ A value we genuinely cannot parse raises rather than being clamped: silently mapping it onto
+ date.max fabricates a real-looking 9999-12-31 and corrupts the whole column, which is far
+ worse than a loud sync failure.
+ """
+
+ def load(self, data) -> date | None:
+ if data is None:
+ return None
+
+ s = bytes(data).decode("utf-8").strip()
+
+ if s in ("infinity", "-infinity"):
+ return date.max if s == "infinity" else date.min
+
+ # Handle negative years (BC dates)
+ if s.startswith("-") or "bc" in s.lower():
+ return date.min
+
+ try:
+ year, month, day = (int(part) for part in s.split("-"))
+ except ValueError as e:
+ raise ValueError(f"Unparseable Redshift date value: {s!r}") from e
+
+ if year > 9999:
+ return date.max
+ if year < 1:
+ return date.min
+
+ return date(year, month, day)
+
+
def _redshift_select_clause(
enabled_columns: Optional[list[str]],
primary_keys: Optional[list[str]],
@@ -597,6 +638,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
password=config.password,
**_REDSHIFT_CONNECT_OPTS,
) as conn:
+ conn.adapters.register_loader("date", SafeDateLoader)
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 54b3f8043359..c801d99d8f14 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,3 +1,5 @@
+from datetime import date
+
import pytest
from unittest.mock import MagicMock, call, patch
@@ -22,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.r
REDSHIFT_SINGLE_NODE_FETCH_LIMIT,
RedshiftColumn,
RedshiftImplementation,
+ SafeDateLoader,
_build_query,
_explain_query,
_fetch_arrow_batches,
@@ -261,6 +264,39 @@ class TestRedshiftColumnToArrowField:
assert "UTC" in str(field.type)
+class TestSafeDateLoader:
+ @pytest.fixture
+ def loader(self):
+ return SafeDateLoader(oid=1082)
+
+ @pytest.mark.parametrize(
+ "input_data,expected",
+ [
+ (b"2024-01-15", date(2024, 1, 15)),
+ (b"0001-01-01", date(1, 1, 1)),
+ (b"9999-12-31", date(9999, 12, 31)),
+ # Reproduces the reported incident: psycopg's default `DateLoader` raises
+ # `DataError: can't parse date '0000-01-01': year 0 is out of range`, aborting the sync.
+ (b"0000-01-01", date.min),
+ (b"10000-01-01", date.max),
+ (b"infinity", date.max),
+ (b"-infinity", date.min),
+ (b"-0001-01-01", date.min),
+ (b"0044-03-15 BC", date.min),
+ (None, None),
+ ],
+ )
+ def test_load_dates(self, loader, input_data, expected):
+ assert loader.load(input_data) == expected
+
+ @pytest.mark.parametrize("input_data", [b"04/01/2022", b"not-a-date", b"20220401"])
+ def test_unparseable_dates_raise_instead_of_clamping(self, loader, input_data):
+ # A silent clamp to date.max corrupts the whole column with a real-looking date;
+ # an unparseable value must surface as a loud sync failure instead.
+ with pytest.raises(ValueError):
+ loader.load(input_data)
+
+
# ---------------------------------------------------------------------------
# Per-cursor metadata queries — exercise impl methods directly
# ---------------------------------------------------------------------------
@@ -1309,6 +1345,25 @@ 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
+ # connection every `connect()` call produces.
+ mocker.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.open_ssh_tunnel",
+ ).return_value.__enter__.return_value = ("localhost", 5439)
+ mock_conn = MagicMock()
+ mock_conn.__enter__.return_value = mock_conn
+ mocker.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.psycopg.connect",
+ return_value=mock_conn,
+ )
+
+ impl = RedshiftImplementation()
+ with impl.connect(_make_config()):
+ pass
+
+ mock_conn.adapters.register_loader.assert_any_call("date", SafeDateLoader)
+
class TestGetConnectionMetadata:
# Source creation looks this method up by name (duck-typed) and silently persists {} when