: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(data-warehouse): stop postgres date loader corrupting non-standard date text (#70089)
Tom Owers7ed6caeadf7b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex 74d813e24983..67e37d855b70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -1558,16 +1558,22 @@ class SafeDateLoader(Loader):"""Load PostgreSQL dates, handling edge cases beyond Python's date range.PostgreSQL can store dates beyond Python's datetime.date limits (year 1 to- year 9999). This includes 'infinity', '-infinity', and dates in years > 9999.- When encountering such dates, we clamp to Python's date limits rather than- raising an error.+ year 9999). This includes 'infinity', '-infinity', and dates in years > 9999,+ which we clamp to Python's date limits rather than raising an error.++ Some Postgres-compatible engines (duckdb/duckgres) render a `date` in text+ mode with a trailing time component ("2022-04-01 00:00:00" or ISO "…T…") — we+ strip it before parsing. 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")+ s = bytes(data).decode("utf-8").strip()if s in ("infinity", "-infinity"):return date.max if s == "infinity" else date.min@@ -1576,24 +1582,20 @@ class SafeDateLoader(Loader):if s.startswith("-") or "bc" in s.lower():return date.min- try:- parts = s.split("-")- if len(parts) == 3:- year = int(parts[0])- month = int(parts[1])- day = int(parts[2])+ # Keep only the date portion — duckdb/duckgres may append a time or ISO "T".+ date_part = s.replace("T", " ").split(" ", 1)[0]- if year > 9999:- return date.max- if year < 1:- return date.min+ try:+ year, month, day = (int(part) for part in date_part.split("-"))+ except ValueError as e:+ raise ValueError(f"Unparseable PostgreSQL date value: {s!r}") from e- return date(year, month, day)- except (ValueError, IndexError):- pass+ if year > 9999:+ return date.max+ if year < 1:+ return date.min- # Fallback: clamp to max for unparseable dates- return date.max+ return date(year, month, day)def _clamp_out_of_range_timestamp(data, *, tzinfo: timezone | None) -> datetime:@@ -3148,10 +3150,16 @@ def postgres_source(# cursor FETCH inherits the session statement_timeout, and on# wide/partitioned scans the source's default (often 30-60s)# kills the fetch before rows come back.+ #+ # Also pin DateStyle to ISO so text-mode date/timestamp values always+ # arrive as YYYY-MM-DD regardless of the server's configured DateStyle.+ # A non-ISO source (e.g. German/SQL/Postgres styles) would otherwise send+ # "04/01/2022" or "15.01.2024", which the Safe*Loaders can't parse.try:# Use psycopg.Cursor directly to bypass cursor_factory (which may be# ServerCursor and requires a `name` arg, breaking an unnamed cursor()).with psycopg.Cursor(connection) as setup_cursor:+ setup_cursor.execute(sql.SQL("SET DateStyle TO 'ISO, MDY'"))setup_cursor.execute(sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(SYNC_STATEMENT_TIMEOUT_MS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex 32fe70bbbc94..d03aced2d187 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -143,12 +143,25 @@ class TestSafeDateLoader:(b"-0044-03-15", date.min),(b"0000-01-01", date.min),(b"0044-03-15 BC", date.min),+ # duckdb/duckgres render `date` in text mode with a trailing time component; the+ # date portion must survive rather than falling through to a fabricated 9999-12-31.+ (b"2022-04-01 00:00:00", date(2022, 4, 1)),+ (b"2022-04-01T00:00:00", date(2022, 4, 1)),+ (b"2022-04-01 00:00:00+00", date(2022, 4, 1)),+ (b" 2024-01-15 ", date(2024, 1, 15)),(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)+class TestSafeTimestampLoader:@pytest.fixture