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(postgres): stop flooding error tracking from best-effort partition sizing (#63751)

Tom Owers8d19faf2ead9
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 8e289956bb62..04d9dc901ba9 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -183,21 +183,6 @@ def _is_connection_dropped_error(error: BaseException) -> bool:
return False
-def _is_recovery_conflict_error(error: BaseException) -> bool:
- """True if `error` is a Postgres standby recovery conflict.
-
- A read replica cancels an in-flight query when WAL replay needs to remove row
- versions the query might still read ("canceling statement due to conflict with
- recovery", SQLSTATE 40001 -> psycopg SerializationFailure). It's transient and
- expected on replicas — the row-streaming reader already retries it in-process and
- `get_non_retryable_errors` deliberately keeps the raw message retryable — so
- best-effort probes should degrade quietly rather than alert on a handled condition.
- """
- return isinstance(error, psycopg.errors.SerializationFailure) and "conflict with recovery" in " ".join(
- str(arg) for arg in error.args
- )
-
-
def _connect_with_dropped_retry(
connect: Callable[[], psycopg.Connection],
logger: FilteringBoundLogger,
@@ -1633,21 +1618,21 @@ def _get_partition_settings(
logger.debug(f"_get_partition_settings: table does not exist, returning None: {e}")
return None
except Exception as e:
- # Partition sizing is best-effort: on failure we return None and the sync proceeds
- # unpartitioned. Two handled conditions must not flood error tracking:
- # - A read replica can cancel this sizing query with a recovery conflict
- # (`SerializationFailure` "conflict with recovery"); it's transient and expected on
- # replicas, and the row-streaming reader retries it in-process.
- # - An earlier best-effort query in this same transaction (chunk sizing, row count,
- # partition detection) can hit that transient condition and leave the transaction in
- # `INERROR`, so this query then fails with `InFailedSqlTransaction` purely as a
- # downstream symptom.
- # Both resurface (and are classified through the normal retryable/non-retryable path) via
- # the real extraction query, so degrade quietly. Genuinely unexpected failures are still
- # captured.
- if not _is_recovery_conflict_error(e) and not isinstance(e, psycopg.errors.InFailedSqlTransaction):
- capture_exception(e)
- logger.debug(f"_get_partition_settings: returning None due to error: {e}")
+ # Partition sizing is a best-effort optimization: returning None just falls back to
+ # default partition settings and the sync proceeds. This query shares its FROM with the
+ # real extraction query, so any genuine problem (missing table, permissions, upstream
+ # extension state, read-replica recovery conflict, or an earlier best-effort query in this
+ # same transaction having left it `InFailedSqlTransaction`) resurfaces there and is
+ # classified through the normal retryable/non-retryable path. Capturing it here too only
+ # floods error tracking with handled duplicates of user/upstream conditions we already
+ # tolerate, so log at debug and fall back — mirroring `_get_rows_to_sync`.
+ logger.debug(f"_get_partition_settings: returning None due to error: {e}", exc_info=e)
+
+ if "temporary file size exceeds temp_file_limit" in str(e):
+ raise TemporaryFileSizeExceedsLimitException(
+ f"Error: {e}. Please ensure your incremental field has an appropriate index created"
+ )
+
return None
result = cursor.fetchone()
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index b8427a919f3a..96fbc6bc22ad 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -70,7 +70,6 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
_is_options_startup_param_unsupported,
_is_partitioned_table,
_is_read_replica,
- _is_recovery_conflict_error,
_is_unsupported_function_error,
_normalize_function_names,
_rls_active_from_conn,
@@ -2275,17 +2274,20 @@ class TestGetPartitionSettings:
assert result is None
capture_mock.assert_not_called()
- def test_unexpected_error_is_still_captured(self):
- # A genuinely unexpected failure on the sizing query must still surface to error tracking.
+ @pytest.mark.django_db
+ def test_failing_sizing_query_falls_back_to_none_without_capturing(self):
logger = structlog.get_logger()
- cursor = mock.MagicMock()
- cursor.execute.side_effect = Exception("some unexpected failure")
- with patch("posthog.temporal.data_imports.sources.postgres.postgres.capture_exception") as capture_mock:
- result = _get_partition_settings(cast(Any, cursor), "public", "t", logger, is_partitioned=False)
+ # The sizing query runs against a table that doesn't exist — stands in for an
+ # upstream/source-side failure (e.g. a misbehaving extension index on the source DB)
+ # that is already tolerated by falling back to default partition settings.
+ with django_connection.cursor() as dj_cursor:
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.capture_exception") as mock_capture:
+ result = _get_partition_settings(cast(Any, dj_cursor), "public", "does_not_exist_ps_table", logger)
+ # Best-effort sizing falls back to None and never reports the handled failure.
assert result is None
- capture_mock.assert_called_once()
+ mock_capture.assert_not_called()
@pytest.mark.parametrize(
"exc",
@@ -2312,22 +2314,18 @@ class TestGetPartitionSettings:
assert result is None
capture_mock.assert_not_called()
+ def test_temp_file_limit_error_still_raises(self):
+ logger = structlog.get_logger()
-class TestIsRecoveryConflictError:
- @pytest.mark.parametrize(
- "error,expected",
- [
- (psycopg.errors.SerializationFailure("canceling statement due to conflict with recovery"), True),
- (psycopg.errors.SerializationFailure("could not serialize access due to conflict with recovery"), True),
- # A non-recovery serialization failure (true 40001 write conflict) is not ours to swallow.
- (psycopg.errors.SerializationFailure("could not serialize access due to concurrent update"), False),
- # Right message, wrong type -> not a recovery conflict we recognise here.
- (psycopg.errors.QueryCanceled("canceling statement due to conflict with recovery"), False),
- (Exception("canceling statement due to conflict with recovery"), False),
- ],
- )
- def test_recognises_recovery_conflict(self, error, expected):
- assert _is_recovery_conflict_error(error) is expected
+ cursor = mock.MagicMock()
+ cursor.execute.side_effect = Exception("temporary file size exceeds temp_file_limit (1048576kB)")
+
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.capture_exception") as mock_capture:
+ with pytest.raises(TemporaryFileSizeExceedsLimitException):
+ _get_partition_settings(cast(Any, cursor), "public", "users", logger)
+
+ # The temp-file signal is actionable, so it propagates rather than being swallowed.
+ mock_capture.assert_not_called()
class TestPostgreSQLColumnToArrowField: