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(bigquery): skip duplicate-key probe quietly when BigQuery memory is exceeded (#63752)

Tom Owersaf5898681d46
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
index d74a72836ab4..302d46f33fa1 100644
--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
@@ -22,7 +22,7 @@ from typing import Any
import pyarrow as pa
import structlog
-from google.api_core.exceptions import Forbidden, NotFound
+from google.api_core.exceptions import BadRequest, Forbidden, NotFound
from google.auth.transport.requests import AuthorizedSession
from google.cloud import bigquery, bigquery_storage
from google.cloud.bigquery.job import QueryJobConfig
@@ -386,6 +386,19 @@ def _get_primary_keys_for_table(table: bigquery.Table, client: bigquery.Client)
return primary_keys
+def _is_bigquery_resource_exceeded(error: BadRequest) -> bool:
+ """True for BigQuery's `resourcesExceeded` query failures.
+
+ BigQuery raises this when a query can't run within a node's memory (for
+ example a large GROUP BY or sort over a big table). It's a property of the
+ customer's data volume, not something we can fix, so best-effort diagnostic
+ queries should degrade gracefully instead of treating it as an actionable
+ crash.
+ """
+ reasons = {err.get("reason") for err in (getattr(error, "errors", None) or [])}
+ return "resourcesExceeded" in reasons or "Resources exceeded during query execution" in str(error)
+
+
def _has_duplicate_primary_keys(table: bigquery.Table, client: bigquery.Client, primary_keys: list[str] | None) -> bool:
if not primary_keys or len(primary_keys) == 0:
return False
@@ -403,6 +416,20 @@ def _has_duplicate_primary_keys(table: bigquery.Table, client: bigquery.Client,
for _ in job.result():
return True
+ except BadRequest as e:
+ if _is_bigquery_resource_exceeded(e):
+ # The duplicate-key probe runs a full GROUP BY over the table; on very large
+ # tables BigQuery can't sort it within a node's memory and raises
+ # `resourcesExceeded`. That's a data-volume limit we can't fix, and this check
+ # is best-effort, so skip it quietly rather than capturing non-actionable noise
+ # on every sync.
+ structlog.get_logger().warning(
+ "Skipping duplicate primary key check for BigQuery table %s.%s: query exceeded BigQuery memory limits",
+ table.dataset_id,
+ table.table_id,
+ )
+ return False
+ capture_exception(e)
except Exception as e:
capture_exception(e)
diff --git a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
index 0246856d636c..29f88b363a01 100644
--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -3,7 +3,7 @@ from freezegun import freeze_time
from unittest import mock
from dateutil import parser
-from google.api_core.exceptions import Forbidden, NotFound, PermissionDenied
+from google.api_core.exceptions import BadRequest, Forbidden, NotFound, PermissionDenied
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
from posthog.temporal.data_imports.sources.bigquery.bigquery import (
@@ -12,6 +12,7 @@ from posthog.temporal.data_imports.sources.bigquery.bigquery import (
BigQueryTokenRefreshError,
_bq_select_clause,
_get_query,
+ _has_duplicate_primary_keys,
_resolve_dataset_id,
_resolve_dataset_project_id,
_resolve_project_id,
@@ -520,3 +521,55 @@ def test_non_retryable_errors_match_permission_denied(observed_error):
def test_non_retryable_errors_does_not_match_transient(other_error):
non_retryable_errors = BigQuerySource().get_non_retryable_errors()
assert not any(key in other_error for key in non_retryable_errors)
+
+
+def _run_has_duplicate_primary_keys(side_effect):
+ table = mock.MagicMock()
+ table.dataset_id = "dataset"
+ table.table_id = "table"
+ table.project = "project"
+
+ client = mock.MagicMock()
+ job = mock.MagicMock()
+ job.result.side_effect = side_effect
+ client.query.return_value = job
+
+ with mock.patch("posthog.temporal.data_imports.sources.bigquery.bigquery.capture_exception") as mock_capture:
+ result = _has_duplicate_primary_keys(table, client, ["id"])
+ return result, mock_capture
+
+
+ "exception",
+ [
+ BadRequest(
+ "Resources exceeded during query execution: The query could not be executed in the allotted memory."
+ ),
+ BadRequest("query failed", errors=[{"reason": "resourcesExceeded", "message": "out of memory"}]),
+ ],
+)
+def test_has_duplicate_primary_keys_skips_resource_exceeded_quietly(exception):
+ """A `resourcesExceeded` BigQuery error during the best-effort duplicate-key probe must NOT
+ be captured to error tracking — it's a non-actionable data-volume limit that otherwise fires
+ on every sync of a large table."""
+ result, mock_capture = _run_has_duplicate_primary_keys(exception)
+
+ assert result is False
+ mock_capture.assert_not_called()
+
+
+def test_has_duplicate_primary_keys_captures_unexpected_bad_request():
+ """A non-resource BadRequest (e.g. a genuinely malformed probe query) is still captured so we
+ don't lose visibility into real bugs."""
+ result, mock_capture = _run_has_duplicate_primary_keys(BadRequest("Syntax error in query"))
+
+ assert result is False
+ mock_capture.assert_called_once()
+
+
+def test_has_duplicate_primary_keys_captures_unexpected_errors():
+ """Genuinely unexpected errors are still captured so we don't lose visibility."""
+ result, mock_capture = _run_has_duplicate_primary_keys(RuntimeError("boom"))
+
+ assert result is False
+ mock_capture.assert_called_once()