: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): skip server-side cursor reads for duckdb-wire sources (#78302)
Tom Owers1f4979e4dec9
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 17b49c4c5b50..743442e23733 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@@ -3032,6 +3032,12 @@ def postgres_source(logger.debug("Checking if source is a read replica...")using_read_replica = _is_read_replica(cursor)logger.debug(f"using_read_replica = {using_read_replica}")+ # DuckDB/duckgres-backed Postgres-wire engines don't implement+ # `DECLARE CURSOR` (or the `pg_catalog.pg_cursors` check psycopg's+ # ServerCursor runs before it), so `get_rows` must skip the+ # server-side cursor read path against them.+ is_duckdb = _is_duckdb_connection(cursor)+ logger.debug(f"is_duckdb = {is_duckdb}")logger.debug("Getting primary keys...")primary_keys = _get_primary_keys(cursor, schema, table_name, logger)if primary_keys:@@ -3278,7 +3284,7 @@ def postgres_source(# the Arrow schema (as the leading field, matching the SELECT) for a clean zip.arrow_schema = arrow_schema.insert(0, pa.field(XMIN_PROJECTED_COLUMN, pa.int64(), nullable=False))with _tunnel_with_handshake_translation(tunnel) as (host, port):- cursor_factory = psycopg.ServerCursor if not using_read_replica else None+ cursor_factory = psycopg.ServerCursor if not using_read_replica and not is_duckdb else Nonedef get_connection():try:@@ -3536,6 +3542,13 @@ def postgres_source(# propagates, so a partially read window/partition is never re-yielded.return _connect_with_dropped_retry(get_connection, logger)+ if is_duckdb:+ # No server-side cursor support (see `is_duckdb` above), so read with the same+ # LIMIT/OFFSET fallback a read replica uses on a recovery conflict — a plain client+ # cursor, no DECLARE required.+ yield from offset_chunking(0, chunk_size)+ return+if use_per_partition_chunking and incremental_field is not None and incremental_field_type is not None:def _build_per_partition_query(child_schema: str, child_name: str) -> sql.Composed: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 966d11d7ec8c..331cec4e7234 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@@ -1512,6 +1512,7 @@ class TestSetupStatementTimeoutUnsupported:patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(is_setup=False)),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=False),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=False),patch(f"{module}._get_table_chunk_size", return_value=100),@@ -2437,6 +2438,7 @@ class TestServerCursorStatementTimeout:patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(raise_on_fetch=False)),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=False),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=False),patch(f"{module}._get_table_chunk_size", return_value=100),@@ -2559,6 +2561,7 @@ class TestServerCursorCloseStatementTimeout:patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(named=False)),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=False),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=False),patch(f"{module}._get_table_chunk_size", return_value=100),@@ -2596,6 +2599,110 @@ class TestServerCursorCloseStatementTimeout:assert connection.closed+class TestGetRowsSkipsServerCursorForDuckDB:+ """DuckDB/duckgres-backed Postgres-wire engines don't implement `DECLARE CURSOR`, nor the+ `pg_catalog.pg_cursors` check psycopg's ServerCursor runs before it — opening a named cursor+ against one raises a `Catalog Error: Table with name pg_cursors does not exist!`. `get_rows`+ must route these connections through the plain-cursor offset-chunking path instead.+ """++ class _Cursor:+ def __init__(self, rows: list[tuple[Any, ...]]):+ self._rows = rows+ self._fetched = False+ col = mock.Mock()+ col.name = "id"+ self.description = [col]++ def execute(self, *args, **kwargs):+ return None++ def fetchall(self):+ if self._fetched:+ return []+ self._fetched = True+ return self._rows++ def fetchmany(self, _n: int):+ raise AssertionError("a server-side cursor FETCH must not run against a duckdb connection")++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ class _Connection:+ def __init__(self, rows: list[tuple[Any, ...]]):+ self._rows = rows+ self.autocommit = False+ self.closed = False+ self.broken = False+ self.adapters = mock.Mock()++ def cursor(self, *args, **kwargs):+ if "name" in kwargs:+ raise AssertionError("get_rows must not open a named/server-side cursor against a duckdb connection")+ return TestGetRowsSkipsServerCursorForDuckDB._Cursor(self._rows)++ def commit(self):+ return None++ def close(self):+ self.closed = True++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ def test_duckdb_connection_reads_via_offset_chunking(self):+ @contextmanager+ def fake_tunnel():+ yield ("localhost", 5432)++ fake_table = mock.Mock()+ fake_table.to_arrow_schema.return_value = pa.schema([pa.field("id", pa.int64())])+ fake_table.type = "table"+ fake_table.columns = []+ fake_table.__contains__ = mock.Mock(return_value=False)++ connection = self._Connection(rows=[(1,)])++ module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"+ with (+ patch(f"{module}.psycopg.connect", return_value=connection),+ patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(rows=[(1,)])),+ patch(f"{module}._get_table", return_value=fake_table),+ patch(f"{module}._is_read_replica", return_value=False),+ patch(f"{module}._is_duckdb_connection", return_value=True),+ patch(f"{module}._get_primary_keys", return_value=["id"]),+ patch(f"{module}._is_partitioned_table", return_value=False),+ patch(f"{module}._get_table_chunk_size", return_value=100),+ patch(f"{module}._get_rows_to_sync", return_value=10),+ patch(f"{module}._role_subject_to_rls", return_value=False),+ patch(f"{module}._get_partition_settings", return_value=None),+ ):+ response = postgres_source(+ tunnel=lambda: fake_tunnel(),+ user="u",+ password="p",+ database="db",+ sslmode="prefer",+ schema="public",+ table_names=["companies"],+ should_use_incremental_field=False,+ logger=structlog.get_logger(),+ db_incremental_field_last_value=None,+ team_id=1,+ )+ tables = list(cast(Iterable[Any], response.items()))++ assert len(tables) == 1+ assert tables[0].to_pylist() == [{"id": 1}]++class TestOffsetChunkingConnectRecoveryConflict:"""A recovery conflict raised by the connect itself in the offset-chunking fallback — a hotstandby cancelling the new connection's startup with "conflict with recovery" — must be retried@@ -2711,6 +2818,7 @@ class TestOffsetChunkingConnectRecoveryConflict:patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._OffsetCursor()),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=True),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=False),patch(f"{module}._get_table_chunk_size", return_value=1000),@@ -2779,6 +2887,7 @@ class TestOffsetChunkingConnectTimeout:),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=True),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=False),patch(f"{module}._get_table_chunk_size", return_value=1000),@@ -2892,6 +3001,7 @@ class TestOffsetChunkingRecoveryConflictTimeout:patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._OffsetCursor()),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=True),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=False),patch(f"{module}._get_table_chunk_size", return_value=1000),@@ -7223,6 +7333,7 @@ class TestGetRowsInitialReadDropRetry:patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(batches=[], drop_on_execute=False)),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=False),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=False),patch(f"{module}._get_table_chunk_size", return_value=100),@@ -7370,6 +7481,7 @@ class TestGetRowsInitialReadLockTimeoutRetry:patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(batches=[], state={"declare_locks_left": 0})),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=False),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=False),patch(f"{module}._get_table_chunk_size", return_value=100),@@ -7531,6 +7643,7 @@ class TestPartitionIterationConnectRetry:),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=False),+ patch(f"{module}._is_duckdb_connection", return_value=False),patch(f"{module}._get_primary_keys", return_value=["id"]),patch(f"{module}._is_partitioned_table", return_value=True),patch(f"{module}.list_child_partitions", return_value=[child]),