: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): set v3 loader statement_timeout after connect, not via startup options (#68960)
estefania51926bbfd6e9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex 4ca07c41fb0c..773e4adbdf04 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -260,21 +260,29 @@ class BatchConsumer:def _lease_ttl_seconds(self) -> int:return self._config.lease_ttl_seconds or self._config.recovery_grace_seconds or RECOVERY_GRACE_SECONDS- def _statement_timeout_options(self, client_timeout_seconds: float | None) -> str | None:- """libpq options for the server-side statement_timeout backstop; None when- the client ceiling is disabled (same "0 disables" contract)."""+ def _statement_timeout_ms(self, client_timeout_seconds: float | None) -> int | None:+ """Server-side statement_timeout backstop in milliseconds; None when the+ client ceiling is disabled (same "0 disables" contract)."""if not client_timeout_seconds:return None- timeout_ms = int((client_timeout_seconds + self._config.statement_timeout_margin_seconds) * 1000)- return f"-c statement_timeout={timeout_ms}"+ return int((client_timeout_seconds + self._config.statement_timeout_margin_seconds) * 1000)- async def _connect(self, *, statement_timeout_options: str | None = None) -> psycopg.AsyncConnection[Any]:- return await psycopg.AsyncConnection.connect(+ async def _connect(self, *, statement_timeout_seconds: float | None = None) -> psycopg.AsyncConnection[Any]:+ conn = await psycopg.AsyncConnection.connect(self._config.database_url,autocommit=True,connect_timeout=self._config.connect_timeout_seconds,- options=statement_timeout_options,)+ # Session-scoped SET, not a libpq startup option: PgBouncer rejects+ # statement_timeout inside the `options` startup parameter.+ timeout_ms = self._statement_timeout_ms(statement_timeout_seconds)+ if timeout_ms is not None:+ try:+ await conn.execute(f"SET statement_timeout = {timeout_ms}")+ except psycopg.Error:+ await conn.close()+ raise+ return connasync def _drop_conn(self, attr: str) -> None:"""Close and forget a connection after a timed-out operation.@@ -298,9 +306,7 @@ class BatchConsumer:async with self._poll_conn_lock:if self._poll_conn is None or self._poll_conn.closed or self._poll_conn.broken:logger.warning(self._event("queue_db_poll_connection_reconnecting"))- self._poll_conn = await self._connect(- statement_timeout_options=self._statement_timeout_options(self._config.poll_timeout_seconds)- )+ self._poll_conn = await self._connect(statement_timeout_seconds=self._config.poll_timeout_seconds)return self._poll_connasync def _ensure_recovery_conn(self) -> psycopg.AsyncConnection[Any]:@@ -310,9 +316,7 @@ class BatchConsumer:async with self._recovery_conn_lock:if self._recovery_conn is None or self._recovery_conn.closed or self._recovery_conn.broken:logger.warning(self._event("queue_db_recovery_connection_reconnecting"))- self._recovery_conn = await self._connect(- statement_timeout_options=self._statement_timeout_options(self._config.sweep_timeout_seconds)- )+ self._recovery_conn = await self._connect(statement_timeout_seconds=self._config.sweep_timeout_seconds)return self._recovery_connasync def _wait_or_shutdown(self, timeout: float) -> None:@@ -324,12 +328,8 @@ class BatchConsumer:async def run(self) -> None:self._install_signal_handlers()- self._poll_conn = await self._connect(- statement_timeout_options=self._statement_timeout_options(self._config.poll_timeout_seconds)- )- self._recovery_conn = await self._connect(- statement_timeout_options=self._statement_timeout_options(self._config.sweep_timeout_seconds)- )+ self._poll_conn = await self._connect(statement_timeout_seconds=self._config.poll_timeout_seconds)+ self._recovery_conn = await self._connect(statement_timeout_seconds=self._config.sweep_timeout_seconds)logger.info(self._event("batch_consumer_started"),diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex bdbaee461af7..1381d7b6ff34 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -631,31 +631,33 @@ class TestStatementTimeoutBackstop:@pytest.mark.parametrize("client_timeout,expected",[- (180.0, "-c statement_timeout=210000"), # 180s + 30s margin, in ms+ (180.0, 210000), # 180s + 30s margin, in ms(None, None), # disabled client ceiling disables the backstop too(0, None),],)- def test_option_string_tracks_client_timeout(self, client_timeout, expected):+ def test_timeout_ms_tracks_client_timeout(self, client_timeout, expected):consumer = _make_consumer(statement_timeout_margin_seconds=30.0)- assert consumer._statement_timeout_options(client_timeout) == expected+ assert consumer._statement_timeout_ms(client_timeout) == expected@pytest.mark.asyncioasync def test_poll_reconnect_applies_statement_timeout(self):# A reconnect that drops the backstop lets an abandoned query keep# burning queue-DB CPU — the exact failure the timeout guards against.+ # The timeout must arrive as a SET statement after connect, never as a+ # libpq startup option: PgBouncer rejects the latter and the whole+ # loader crash-loops at startup.consumer = _make_consumer(poll_timeout_seconds=180.0, statement_timeout_margin_seconds=30.0)consumer._poll_conn = _make_healthy_conn(closed=True) # force the reconnect branch- captured: dict[str, Any] = {}-- async def fake_connect(*, statement_timeout_options: str | None = None) -> AsyncMock:- captured["options"] = statement_timeout_options- return _make_healthy_conn()+ fresh = _make_healthy_conn()- with patch.object(consumer, "_connect", side_effect=fake_connect):+ with patch.object(+ psycopg.AsyncConnection, "connect", new_callable=AsyncMock, return_value=fresh+ ) as mock_connect:await consumer._ensure_poll_conn()- assert captured["options"] == "-c statement_timeout=210000"+ assert "options" not in mock_connect.call_args.kwargs+ fresh.execute.assert_awaited_once_with("SET statement_timeout = 210000")class TestPollBackoff: