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 rows instead of declaring a cursor (#79500)

Tom Owers83f6a6b191df
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 3d29c6d96a4e..951953beff51 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
@@ -18,7 +18,7 @@ from typing import Any, Literal, LiteralString, Optional, cast
import psycopg
import pyarrow as pa
import structlog
-from psycopg import sql
+from psycopg import pq, sql
from psycopg.adapt import Loader
from psycopg.pq import TransactionStatus
from structlog.types import FilteringBoundLogger
@@ -65,6 +65,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.redshift import (
RedshiftSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
from products.warehouse_sources.backend.types import IncrementalFieldType
__all__ = [
@@ -123,6 +124,13 @@ REDSHIFT_INTERNAL_COLUMN_LIKE = "padb_internal%"
# client-side read of the whole table.
REDSHIFT_SINGLE_NODE_FETCH_LIMIT = 1000
+# Rows libpq hands over per chunk while streaming. Only the delivery granularity — the server sends
+# the result set at its own pace either way — so this trades per-row Python overhead against the
+# transient list held between yields. Chunked delivery needs libpq 17; older builds fall back to
+# row-at-a-time, which streams just as correctly.
+REDSHIFT_STREAM_ROWS_PER_CHUNK = 1000
+_LIBPQ_CHUNKED_ROWS_MIN_VERSION = 170000
+
def _display_name(schema_name: str, table_name: str, *, qualify: bool) -> str:
"""Discovery key for a table: dotted `schema.table` in multi-schema mode, bare table otherwise."""
@@ -312,6 +320,67 @@ def _is_fetch_size_error(error: Exception) -> bool:
return "fetch size" in message and "exceeds the limit" in message
+def _is_cursor_size_error(error: Exception) -> bool:
+ """Is this Redshift refusing to materialize a cursor result set this large?
+
+ A cursor's result set is materialized whole on the leader node, and the cap is on that total,
+ not on the page a `FETCH` asks for. So no fetch size gets under it: the cap makes the server
+ cursor permanently unusable for the table on this cluster, whatever we do to the fetch.
+ """
+ message = str(error).lower()
+ return "cursor data" in message or ("cursor result set" in message and "exceeds the limit" in message)
+
+
+def _rollback_if_aborted(connection: psycopg.Connection) -> None:
+ """Clear an aborted transaction so the next attempt isn't killed by `InFailedSqlTransaction`.
+
+ Redshift has no savepoints to scope a failure, so the whole transaction goes. This also frees
+ the cursor name for a re-DECLARE, since an aborted transaction turns `CLOSE` into a no-op.
+ """
+ if connection.info.transaction_status == TransactionStatus.INERROR:
+ connection.rollback()
+
+
+def _libpq_rows_per_chunk() -> int:
+ """Rows per libpq chunk while streaming, or 1 where chunked delivery isn't available.
+
+ Chunked row mode arrived in libpq 17. On an older build `stream()` still streams correctly,
+ one row at a time — only the per-row overhead differs, never the memory profile.
+ """
+ return REDSHIFT_STREAM_ROWS_PER_CHUNK if pq.version() >= _LIBPQ_CHUNKED_ROWS_MIN_VERSION else 1
+
+
+def _stream_rows_as_arrow_batches(
+ cursor: psycopg.Cursor,
+ query: sql.Composed,
+ chunk_size: int,
+ arrow_schema: pa.Schema,
+) -> Iterator[pa.Table]:
+ """Yield one Arrow table per `chunk_size` rows, reading rows straight off the wire.
+
+ `stream()` puts libpq in single-row (or chunked-row) mode: no cursor is declared, so the
+ per-node cap on cursor data never applies, and no result set is buffered into the worker
+ either. Those were the two ways a large table could not be read.
+ """
+ column_names: list[str] = []
+ pending: list[Any] = []
+
+ def to_arrow(rows: list[Any]) -> pa.Table:
+ return table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
+
+ for row in cursor.stream(query, size=_libpq_rows_per_chunk()):
+ if not column_names:
+ # Only described once the first result arrives, so it can't be read before the loop.
+ column_names = [column.name for column in cursor.description or []]
+ pending.append(row)
+ if len(pending) >= chunk_size:
+ yield to_arrow(pending)
+ pending = []
+
+ if pending:
+ yield to_arrow(pending)
+
+
def _fetch_arrow_batches(
cursor: psycopg.Cursor,
chunk_size: int,
@@ -359,23 +428,38 @@ def _stream_arrow_batches(
) -> 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. The fetch cap is a
- property of the cluster, not the table, so on a single-node cluster it rejects the *first* fetch
- of every sync — the retry at `REDSHIFT_SINGLE_NODE_FETCH_LIMIT` is what keeps those clusters on
- the server cursor at all. Anything else that makes the cursor unusable 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 both recoveries are off the table: re-running the
- query would re-emit rows the pipeline has already consumed, so later errors propagate.
+ Two ways to read, tried in order. Streaming (`stream()`) is preferred: libpq delivers rows as
+ the server produces them, so nothing is declared on the cluster and nothing is buffered in the
+ worker. The server-side cursor (`DECLARE`/`FETCH`) is the fallback, mirroring the sibling
+ Postgres driver.
+
+ Redshift constrains cursors in ways Postgres doesn't, which is why streaming leads. A cursor's
+ result set is materialized whole on the leader node under a per-node-type cap, so a table above
+ that cap can never be read through a cursor at any fetch size. Single-node clusters separately
+ reject a `FETCH FORWARD` above 1000 rows; that one is a property of the cluster rather than the
+ table, so the retry at `REDSHIFT_SINGLE_NODE_FETCH_LIMIT` recovers it.
+
+ Neither path buffers the whole result set, so there is no third attempt: an unnamed cursor would
+ pull the entire table into the worker and OOM the pod, taking every co-tenant extraction on it
+ down too. A table that neither path can read fails the sync instead.
+
+ Once a batch has been yielded every recovery is off the table: re-running the query would
+ re-emit rows the pipeline has already consumed, so later errors propagate.
"""
yielded = False
+
+ try:
+ with connection.cursor() as stream_cursor:
+ for batch in _stream_rows_as_arrow_batches(stream_cursor, query, chunk_size, arrow_schema):
+ yielded = True
+ yield batch
+ return
+ except Exception as e:
+ if yielded:
+ raise
+ _rollback_if_aborted(connection)
+ logger.warning(f"Row streaming unusable ({e}); falling back to a server-side cursor", exc_info=e)
+
fetch_sizes = [chunk_size]
if chunk_size > REDSHIFT_SINGLE_NODE_FETCH_LIMIT:
fetch_sizes.append(REDSHIFT_SINGLE_NODE_FETCH_LIMIT)
@@ -393,31 +477,29 @@ def _stream_arrow_batches(
except Exception as e:
if yielded:
raise
-
- # A failed DECLARE/FETCH leaves the transaction aborted, and Redshift has no savepoints
- # to scope it. Roll back so the next attempt isn't killed by `InFailedSqlTransaction` —
- # and because that is also what frees `cursor_name` for a re-DECLARE, since an aborted
- # transaction turns the block's `CLOSE` into a no-op.
- if connection.info.transaction_status == TransactionStatus.INERROR:
- connection.rollback()
+ _rollback_if_aborted(connection)
is_last_attempt = attempt == len(fetch_sizes) - 1
if not is_last_attempt and _is_fetch_size_error(e):
- logger.debug(
+ logger.warning(
f"Server cursor rejected a {fetch_size}-row FETCH ({e}); "
f"retrying at {REDSHIFT_SINGLE_NODE_FETCH_LIMIT} rows per fetch"
)
continue
- logger.debug(
- f"Server-side cursor unusable ({e}); falling back to a client-side read of the full result set",
- exc_info=e,
- )
- break
-
- with connection.cursor() as client_cursor:
- client_cursor.execute(query)
- yield from _fetch_arrow_batches(client_cursor, chunk_size, arrow_schema)
+ if _is_cursor_size_error(e):
+ # Classified, permanent for this table on this cluster: no fetch size gets under the
+ # cap, and streaming already failed. Retrying just repeats a materialization that
+ # takes over a minute to fail.
+ raise NonRetryableException(
+ "This table is too large to read from this Redshift cluster. The cluster caps how "
+ "much data a cursor can hold, and row streaming is unavailable, so PostHog cannot "
+ "page through the result set. Sync fewer columns, add a row filter, or move to a "
+ "multi-node cluster."
+ ) from e
+
+ logger.warning(f"Server-side cursor unusable ({e})", exc_info=e)
+ raise
class RedshiftColumn(Column):
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 d7b1a51c9f6f..623e0913f6d9 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
@@ -25,13 +25,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.r
_build_query,
_explain_query,
_fetch_arrow_batches,
+ _libpq_rows_per_chunk,
_stream_arrow_batches,
+ _stream_rows_as_arrow_batches,
filter_redshift_incremental_fields,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.source import (
_REDSHIFT_IMPLEMENTATION,
RedshiftSource,
)
+from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
from products.warehouse_sources.backend.types import IncrementalFieldType
# ---------------------------------------------------------------------------
@@ -548,13 +551,29 @@ def _stream_cursor(batches: list[list[tuple]]) -> MagicMock:
return cursor
+def _rows_cursor(rows: list[tuple] | Exception) -> MagicMock:
+ """An unnamed cursor whose `stream()` yields `rows`, or raises when given an exception."""
+ column = MagicMock()
+ column.name = "id"
+
+ cursor = MagicMock()
+ cursor.description = [column]
+ if isinstance(rows, Exception):
+ cursor.stream.side_effect = rows
+ else:
+ cursor.stream.return_value = iter(rows)
+ cursor.__enter__.return_value = cursor
+ cursor.__exit__.return_value = False
+ return cursor
+
+
def _stream_connection(
server_cursor: MagicMock,
- client_cursor: MagicMock,
+ stream_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.cursor.side_effect = lambda name=None: server_cursor if name is not None else stream_cursor
connection.info.transaction_status = transaction_status
return connection
@@ -581,37 +600,46 @@ class TestFetchArrowBatches:
assert [c.args[0] for c in cursor.fetchmany.call_args_list] == [2, 2]
+class TestStreamRowsAsArrowBatches:
+ def test_accumulates_streamed_rows_into_chunk_sized_batches(self):
+ # Streaming yields row by row; the Delta writer still has to see chunk_size-sized batches.
+ cursor = _rows_cursor([(1,), (2,), (3,), (4,), (5,)])
+
+ tables = list(_stream_rows_as_arrow_batches(cursor, _STREAM_QUERY, 2, _STREAM_SCHEMA))
+
+ assert _ids(tables) == [[1, 2], [3, 4], [5]]
+
+ def test_asks_libpq_for_chunked_delivery(self):
+ cursor = _rows_cursor([(1,)])
+
+ list(_stream_rows_as_arrow_batches(cursor, _STREAM_QUERY, 1, _STREAM_SCHEMA))
+
+ assert cursor.stream.call_args.kwargs["size"] == _libpq_rows_per_chunk()
+
+ def test_yields_nothing_for_an_empty_result(self):
+ cursor = _rows_cursor([])
+
+ assert list(_stream_rows_as_arrow_batches(cursor, _STREAM_QUERY, 2, _STREAM_SCHEMA)) == []
+
+
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)
+ def test_streams_without_declaring_a_cursor(self, logger):
+ # Streaming declares nothing on the cluster, so the per-node cap on cursor data - which no
+ # fetch size can get under - never applies to the table at all.
+ stream_cursor = _rows_cursor([(1,), (2,), (3,)])
+ server_cursor = _stream_cursor([])
+ connection = _stream_connection(server_cursor, stream_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()
+ assert connection.cursor.call_args_list == [call()]
+ server_cursor.execute.assert_not_called()
- @pytest.mark.parametrize(
- "failure_point,error",
- [
- # Cumulative cursor result sets are capped per node type. It says "exceeds the limit"
- # too, but shrinking the fetch can't fix it, so it must not trigger the retry below.
- ("declare", psycopg.errors.FeatureNotSupported("cursor result set size exceeds the limit")),
- ("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)
+ def test_falls_back_to_a_server_cursor_when_streaming_fails(self, logger):
+ stream_cursor = _rows_cursor(psycopg.errors.FeatureNotSupported("single row mode not supported"))
+ server_cursor = _stream_cursor([[(1,), (2,)]])
+ connection = _stream_connection(server_cursor, stream_cursor, TransactionStatus.INERROR)
tables = list(_stream_arrow_batches(connection, _STREAM_QUERY, 2, _STREAM_SCHEMA, "cur", logger))
@@ -619,23 +647,21 @@ class TestStreamArrowBatches:
# Without the rollback the fallback dies on `InFailedSqlTransaction` instead of syncing.
connection.rollback.assert_called_once()
- def test_retries_at_the_single_node_limit_instead_of_falling_back(self, logger):
- # A single-node cluster rejects the first FETCH of every sync. Falling back here reads the
- # whole table into the worker, which is what OOM-killed the pod in production.
+ def test_retries_the_cursor_at_the_single_node_limit(self, logger):
+ # A single-node cluster rejects the first FETCH of every sync, and that one a smaller fetch
+ # does fix - so it must retry rather than give up on the cursor.
+ stream_cursor = _rows_cursor(psycopg.errors.FeatureNotSupported("single row mode not supported"))
server_cursor = _stream_cursor([[(1,), (2,)]])
server_cursor.fetchmany.side_effect = [
psycopg.errors.InternalError_("Fetch size 20000 exceeds the limit of 1000 for a single node configuration"),
[(1,), (2,)],
[],
]
- client_cursor = _stream_cursor([[(9,)]])
- connection = _stream_connection(server_cursor, client_cursor, TransactionStatus.INERROR)
+ connection = _stream_connection(server_cursor, stream_cursor, TransactionStatus.INERROR)
tables = list(_stream_arrow_batches(connection, _STREAM_QUERY, 20_000, _STREAM_SCHEMA, "cur", logger))
assert _ids(tables) == [[1, 2]]
- client_cursor.execute.assert_not_called()
- assert connection.cursor.call_args_list == [call(name="cur"), call(name="cur")]
# The retry has to actually shrink the fetch, or Redshift rejects it identically.
assert [c.args[0] for c in server_cursor.fetchmany.call_args_list] == [
20_000,
@@ -643,29 +669,47 @@ class TestStreamArrowBatches:
REDSHIFT_SINGLE_NODE_FETCH_LIMIT,
]
- def test_does_not_retry_when_the_chunk_already_fits_the_single_node_limit(self, logger):
- # Re-DECLARE-ing at the size that was just rejected would loop the same failure.
+ def test_fails_the_sync_when_the_result_set_exceeds_the_cursor_limit(self, logger):
+ # The production failure: streaming is unavailable and the table is over the cluster's cursor
+ # cap. Reading it client-side instead OOM-killed the pod, taking co-tenant extractions with it.
+ stream_cursor = _rows_cursor(psycopg.errors.FeatureNotSupported("single row mode not supported"))
server_cursor = _stream_cursor([])
server_cursor.fetchmany.side_effect = psycopg.errors.InternalError_(
- "Fetch size 1000 exceeds the limit of 1000 for a single node configuration"
+ "exceeded the maximum size allowed for the total set of cursor data: 8000MB."
)
- client_cursor = _stream_cursor([[(1,)]])
- connection = _stream_connection(server_cursor, client_cursor, TransactionStatus.INERROR)
+ connection = _stream_connection(server_cursor, stream_cursor, TransactionStatus.INERROR)
- tables = list(
- _stream_arrow_batches(
- connection, _STREAM_QUERY, REDSHIFT_SINGLE_NODE_FETCH_LIMIT, _STREAM_SCHEMA, "cur", logger
+ with pytest.raises(NonRetryableException) as failure:
+ list(
+ _stream_arrow_batches(
+ connection, _STREAM_QUERY, REDSHIFT_SINGLE_NODE_FETCH_LIMIT, _STREAM_SCHEMA, "cur", logger
+ )
)
- )
- assert _ids(tables) == [[1]]
- assert connection.cursor.call_args_list == [call(name="cur"), call()]
+ assert "too large to read" in str(failure.value)
+ # Only the stream cursor and the one server cursor: no third, unnamed read of the whole table.
+ assert connection.cursor.call_args_list == [call(), call(name="cur")]
- def test_does_not_fall_back_once_a_batch_has_been_yielded(self, logger):
+ def test_propagates_an_unclassified_cursor_failure(self, logger):
+ # Unclassified means possibly transient, so it must stay retryable rather than fail the
+ # schema outright the way the cursor-cap case does.
+ stream_cursor = _rows_cursor(psycopg.errors.FeatureNotSupported("single row mode not supported"))
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)
+ server_cursor.fetchmany.side_effect = psycopg.OperationalError("connection lost")
+ connection = _stream_connection(server_cursor, stream_cursor, TransactionStatus.INERROR)
+
+ with pytest.raises(psycopg.OperationalError):
+ list(_stream_arrow_batches(connection, _STREAM_QUERY, 2, _STREAM_SCHEMA, "cur", logger))
+
+ def test_does_not_fall_back_once_a_batch_has_been_yielded(self, logger):
+ def rows():
+ yield (1,)
+ raise psycopg.OperationalError("connection lost")
+
+ stream_cursor = _rows_cursor([])
+ stream_cursor.stream.return_value = rows()
+ server_cursor = _stream_cursor([[(9,)]])
+ connection = _stream_connection(server_cursor, stream_cursor)
stream = _stream_arrow_batches(connection, _STREAM_QUERY, 1, _STREAM_SCHEMA, "cur", logger)
@@ -673,7 +717,7 @@ class TestStreamArrowBatches:
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()
+ server_cursor.execute.assert_not_called()
class TestHasDuplicatePrimaryKeys: