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(data-warehouse): stream Redshift reads via a server-side cursor (#78156)

Tom Owersa6fc7afcf098
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 f199537a1446..81d0b380b655 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
@@ -293,6 +293,74 @@ def _explain_query(cursor: psycopg.Cursor, query: sql.Composed, logger: Filterin
pass
+def _fetch_arrow_batches(
+ cursor: psycopg.Cursor,
+ chunk_size: int,
+ arrow_schema: pa.Schema,
+) -> Iterator[pa.Table]:
+ """Yield one Arrow table per `chunk_size` rows drawn from an already-executed `cursor`."""
+ column_names = [column.name for column in cursor.description or []]
+
+ while True:
+ rows = cursor.fetchmany(chunk_size)
+ if not rows:
+ break
+
+ yield table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
+
+
+def _stream_arrow_batches(
+ connection: psycopg.Connection,
+ query: sql.Composed,
+ chunk_size: int,
+ arrow_schema: pa.Schema,
+ cursor_name: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[pa.Table]:
+ """Stream `query` as Arrow tables, holding only `chunk_size` rows in the worker at a time.
+
+ Reads through a server-side cursor (`DECLARE`/`FETCH`), mirroring the sibling Postgres driver.
+ An unnamed psycopg cursor is client-side: `execute()` buffers the *entire* result set into the
+ worker before `fetchmany` returns its first batch, so `chunk_size` bounds nothing and any table
+ larger than the pod's memory kills it during extraction — before a single row is ever written.
+ Redshift instead materializes a cursor's result set on the leader node (spilling to disk when it
+ doesn't fit), which is what keeps the worker's footprint proportional to `chunk_size`.
+
+ Redshift constrains cursors in ways Postgres doesn't: cumulative result sets are capped per node
+ type, and single-node clusters reject a `FETCH FORWARD` above 1000 rows. Both surface before any
+ batch reaches the caller, so a failure there falls back to the client-side read instead of
+ failing the sync — no better than having no server cursor at all, but no worse either. Once a
+ batch has been yielded the fallback is off the table: re-running the query would re-emit rows the
+ pipeline has already consumed, so later errors propagate.
+ """
+ yielded = False
+ try:
+ # `close()` is a no-op while the transaction is aborted (psycopg checks the status first),
+ # so this never masks the original failure with a CLOSE error.
+ with connection.cursor(name=cursor_name) as server_cursor:
+ server_cursor.execute(query)
+ for batch in _fetch_arrow_batches(server_cursor, chunk_size, arrow_schema):
+ yielded = True
+ yield batch
+ return
+ except Exception as e:
+ if yielded:
+ raise
+ logger.debug(
+ f"Server-side cursor unusable ({e}); falling back to a client-side read of the full result set",
+ exc_info=e,
+ )
+
+ # A failed DECLARE/FETCH leaves the transaction aborted, and Redshift has no savepoints to scope
+ # it — roll back so the client-side retry below isn't killed by `InFailedSqlTransaction`.
+ if connection.info.transaction_status == TransactionStatus.INERROR:
+ connection.rollback()
+
+ with connection.cursor() as client_cursor:
+ client_cursor.execute(query)
+ yield from _fetch_arrow_batches(client_cursor, chunk_size, arrow_schema)
+
+
class RedshiftColumn(Column):
"""Implementation of the `Column` protocol for a Redshift source."""
@@ -963,46 +1031,28 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
inner_query_args: Any,
logger: FilteringBoundLogger,
) -> int | None:
- """Sample the 95th percentile of `pg_column_size(t)` across the filtered query.
-
- `inner_query` is a `psycopg.sql.Composed` whose literals are
- already bound — no separate `inner_query_args` is interpolated
- here, mirroring how the rest of the Redshift driver builds
- queries.
+ """Derive the average row size from `svv_table_info`'s reported size and row count.
- Best-effort only: Redshift rejects the `pg_column_size(t)` whole-row reference, so this
- currently returns None on every table and the caller falls back to the default chunk size.
- Failures are swallowed rather than reported — see the except block below.
- """
- try:
- query = sql.SQL("""
- SELECT percentile_cont(0.95) within group (order by subquery.row_size) FROM (
- SELECT pg_column_size(t) as row_size FROM ({}) as t
- ) as subquery
- """).format(inner_query)
-
- _explain_query(cursor, query, logger)
- logger.debug(f"Running query: {query.as_string()}")
- cursor.execute(query)
- row = cursor.fetchone()
+ Redshift has no portable whole-row size expression — `pg_column_size(t)` (like Postgres'
+ `octet_length(t::text)`) needs a composite whole-row reference that Redshift rejects with
+ `UndefinedColumn: column "t" does not exist in t`, so sampling the rows directly fails on
+ every table and the caller silently fell back to `DEFAULT_CHUNK_SIZE` for all of them. The
+ table's own catalog stats give the same figure without a sample scan.
- if row is None or row[0] is None:
- logger.debug("fetch_average_row_size: no results returning None")
- return None
+ `size` is the *compressed* on-disk footprint, so this under-estimates the decompressed
+ working set and the chunk it yields stays larger than the true row size warrants. The caller
+ caps the result at `DEFAULT_CHUNK_SIZE` either way, so an under-estimate is safe: it can
+ only shrink a table's chunk from what it was, never grow it.
- return int(row[0] or 1)
- except psycopg.errors.QueryCanceled:
- raise
- except Exception as e:
- # Best-effort sampling: any failure falls back to the default chunk size, so it must not
- # be reported to error tracking. Redshift has no portable whole-row size — `pg_column_size(t)`
- # (like Postgres' `octet_length(t::text)`) relies on a composite whole-row reference that
- # Redshift rejects with `UndefinedColumn: column "t" does not exist in t`, so this fails on
- # every table. Mirrors the sibling Postgres `_get_table_chunk_size` and `_explain_query` here,
- # both of which treat this as expected, non-actionable noise.
- logger.debug(f"fetch_average_row_size: Error: {e}", exc_info=e)
+ Best-effort, like every other stats probe on this driver: None falls back to the default.
+ """
+ stats = self.fetch_table_stats(cursor, schema, table_name, logger)
+ if stats is None or stats.row_count <= 0:
+ logger.debug("fetch_average_row_size: no usable table stats, returning None")
return None
+ return max(1, stats.table_size_bytes // stats.row_count)
+
# ------------------------------------------------------------------
# Pipeline build — the dlt `SourceResponse` for a single table
# ------------------------------------------------------------------
@@ -1131,31 +1181,31 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
arrow_schema = table.to_arrow_schema()
with self.connect(config) as streaming_connection:
streaming_connection.adapters.register_loader("json", JsonAsStringLoader)
- with streaming_connection.cursor() as cursor:
- query = _build_query(
- schema,
- table_name,
- should_use_incremental_field,
- table.type,
- incremental_field,
- incremental_field_type,
- db_incremental_field_last_value,
- enabled_columns=enabled_columns,
- primary_keys=primary_keys,
- row_filters=row_filters,
- )
- logger.debug(f"Redshift query: {query.as_string()}")
-
- cursor.execute(query)
-
- column_names = [column.name for column in cursor.description or []]
-
- while True:
- rows = cursor.fetchmany(chunk_size)
- if not rows:
- break
-
- yield table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
+ query = _build_query(
+ schema,
+ table_name,
+ should_use_incremental_field,
+ table.type,
+ incremental_field,
+ incremental_field_type,
+ db_incremental_field_last_value,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ row_filters=row_filters,
+ )
+ logger.debug(f"Redshift query: {query.as_string()}")
+
+ # Left in the connection's default (autocommit off) transaction: Redshift only
+ # allows a cursor inside an explicit transaction block, and only one open per
+ # session — this connection is dedicated to the stream, so neither binds.
+ yield from _stream_arrow_batches(
+ streaming_connection,
+ query,
+ chunk_size,
+ arrow_schema,
+ f"posthog_{inputs.team_id}_{schema}.{table_name}",
+ logger,
+ )
return SourceResponse(
name=location.response_name,
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 99f993bd4b87..95b201a4d448 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,7 +1,8 @@
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
import psycopg
+import pyarrow as pa
from psycopg import sql
from psycopg.pq import TransactionStatus
@@ -22,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.r
RedshiftImplementation,
_build_query,
_explain_query,
+ _stream_arrow_batches,
filter_redshift_incremental_fields,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.source import (
@@ -499,36 +501,117 @@ class TestFetchAverageRowSize:
def _inner(self):
return sql.SQL("SELECT 1").format()
- def test_returns_none_when_no_row(self, impl, cursor, logger):
- cursor.fetchone.return_value = None
- assert impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger) is None
+ @pytest.mark.parametrize(
+ "table_info_row,expected",
+ [
+ ((2, 100), 2 * 1024 * 1024 // 100),
+ # Rows far smaller than a byte still have to report at least 1: a 0 would make the
+ # caller discard the measurement and fall back to the full default chunk.
+ ((1, 10_000_000), 1),
+ (None, None),
+ ((0, 100), None),
+ ((10, 0), None),
+ ],
+ )
+ def test_derives_row_size_from_table_stats(self, impl, cursor, logger, table_info_row, expected):
+ cursor.fetchone.return_value = table_info_row
+ assert impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger) == expected
- def test_returns_none_when_row_value_is_none(self, impl, cursor, logger):
- cursor.fetchone.return_value = (None,)
- assert impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger) is None
+ def test_returns_none_on_exception(self, impl, cursor, logger):
+ cursor.execute.side_effect = RuntimeError("boom")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.capture_exception"
+ ):
+ assert impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger) is None
- def test_returns_row_size_bytes(self, impl, cursor, logger):
- cursor.fetchone.return_value = (256.4,)
- result = impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger)
- assert result == 256
- def test_returns_none_on_exception(self, impl, cursor, logger):
- cursor.execute.side_effect = [None, RuntimeError("boom")]
- assert impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger) is None
+# ---------------------------------------------------------------------------
+# Streaming reads
+# ---------------------------------------------------------------------------
- def test_does_not_report_whole_row_reference_failure(self, impl, cursor, logger):
- # Redshift rejects the `pg_column_size(t)` whole-row reference with this exact error on every
- # table. It's a best-effort probe that falls back to the default chunk size, so it must not be
- # reported to error tracking (the source of the noise this fix addresses).
- cursor.execute.side_effect = [None, psycopg.errors.UndefinedColumn('column "t" does not exist in t')]
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.capture_exception"
- ) as mock_capture:
- result = impl.fetch_average_row_size(cursor, "public", "t", self._inner(), None, logger)
+_STREAM_SCHEMA = pa.schema([pa.field("id", pa.int64())])
+_STREAM_QUERY = sql.SQL("SELECT id FROM public.t").format()
- assert result is None
- mock_capture.assert_not_called()
+
+def _stream_cursor(batches: list[list[tuple]]) -> MagicMock:
+ column = MagicMock()
+ column.name = "id"
+
+ cursor = MagicMock()
+ cursor.description = [column]
+ cursor.fetchmany.side_effect = [*batches, []]
+ cursor.__enter__.return_value = cursor
+ cursor.__exit__.return_value = False
+ return cursor
+
+
+def _stream_connection(
+ server_cursor: MagicMock,
+ client_cursor: MagicMock,
+ transaction_status: TransactionStatus = TransactionStatus.INTRANS,
+) -> MagicMock:
+ connection = MagicMock()
+ connection.cursor.side_effect = lambda name=None: server_cursor if name is not None else client_cursor
+ connection.info.transaction_status = transaction_status
+ return connection
+
+
+def _ids(tables) -> list[list[int]]:
+ return [table.column("id").to_pylist() for table in tables]
+
+
+class TestStreamArrowBatches:
+ def test_streams_through_a_server_side_cursor(self, logger):
+ server_cursor = _stream_cursor([[(1,), (2,)], [(3,)]])
+ client_cursor = _stream_cursor([])
+ connection = _stream_connection(server_cursor, client_cursor)
+
+ tables = list(_stream_arrow_batches(connection, _STREAM_QUERY, 2, _STREAM_SCHEMA, "cur", logger))
+
+ assert _ids(tables) == [[1, 2], [3]]
+ # The whole point of the fix: an unnamed cursor is client-side, so `execute` would buffer the
+ # entire table into the worker and OOM it on anything large.
+ assert connection.cursor.call_args_list == [call(name="cur")]
+ client_cursor.execute.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "failure_point,error",
+ [
+ # Cumulative cursor result sets are capped per node type.
+ ("declare", psycopg.errors.FeatureNotSupported("cursor result set too large")),
+ # Single-node clusters reject a FETCH FORWARD above 1000 rows.
+ ("fetch", psycopg.errors.InvalidCursorName("cursor does not exist")),
+ ],
+ )
+ def test_falls_back_to_a_client_cursor_when_the_server_cursor_fails(self, logger, failure_point, error):
+ server_cursor = _stream_cursor([])
+ if failure_point == "declare":
+ server_cursor.execute.side_effect = error
+ else:
+ server_cursor.fetchmany.side_effect = error
+ client_cursor = _stream_cursor([[(1,), (2,)]])
+ connection = _stream_connection(server_cursor, client_cursor, TransactionStatus.INERROR)
+
+ tables = list(_stream_arrow_batches(connection, _STREAM_QUERY, 2, _STREAM_SCHEMA, "cur", logger))
+
+ assert _ids(tables) == [[1, 2]]
+ # Without the rollback the fallback dies on `InFailedSqlTransaction` instead of syncing.
+ connection.rollback.assert_called_once()
+
+ def test_does_not_fall_back_once_a_batch_has_been_yielded(self, logger):
+ server_cursor = _stream_cursor([])
+ server_cursor.fetchmany.side_effect = [[(1,)], psycopg.OperationalError("connection lost")]
+ client_cursor = _stream_cursor([[(9,)]])
+ connection = _stream_connection(server_cursor, client_cursor)
+
+ stream = _stream_arrow_batches(connection, _STREAM_QUERY, 1, _STREAM_SCHEMA, "cur", logger)
+
+ assert next(stream).column("id").to_pylist() == [1]
+ with pytest.raises(psycopg.OperationalError):
+ next(stream)
+ # Re-running the query here would re-emit rows the pipeline already merged.
+ client_cursor.execute.assert_not_called()
class TestHasDuplicatePrimaryKeys: