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): surface opaque OAuth token refresh TypeError as non-retryable (#63788)

Tom Owers7874cf9875bb
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
index f5206a15974b..8bc07879ab18 100644
--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
@@ -51,7 +51,9 @@ from posthog.temporal.data_imports.sources.generated_configs import BigQuerySour
from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings
__all__ = [
+ "BIGQUERY_TOKEN_RESPONSE_ERROR",
"BigQueryImplementation",
+ "BigQueryTokenRefreshError",
"bigquery_client",
"bigquery_storage_read_client",
"build_destination_table_prefix",
@@ -65,6 +67,24 @@ __all__ = [
# tracked gRPC transport's logs/metrics.
BIGQUERY_STORAGE_HOST = "bigquerystorage.googleapis.com"
+# Stable, source-specific marker for a failed service-account OAuth token refresh.
+# Used both when raising below and when matching in `BigQuerySource.get_non_retryable_errors`,
+# so it must stay free of volatile data (urls, ids, timestamps).
+BIGQUERY_TOKEN_RESPONSE_ERROR = "BigQuery OAuth token endpoint returned an unexpected response"
+
+
+class BigQueryTokenRefreshError(Exception):
+ """Raised when the service-account OAuth token endpoint returns a non-JSON-object 200.
+
+ google-auth's `jwt_grant` reads `response_data["access_token"]` while guarding only
+ against `KeyError`. When the token endpoint replies 200 with a body that isn't a JSON
+ object — an intercepting proxy, or a misconfigured `token_uri` in the service-account
+ key file — `response_data` is a `str` and the lookup raises an opaque
+ `TypeError: string indices must be integers` instead of a `RefreshError`. We re-raise it
+ as this clear, non-retryable error so the sync stops hammering an endpoint that can't
+ authenticate us, and the user gets an actionable message.
+ """
+
def build_destination_table_prefix(schema_id: str | None) -> str:
return f"__posthog_import_{schema_id.replace('-', '_') if schema_id else ''}"
@@ -531,11 +551,13 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
) -> dict[str, list[tuple[str, str, bool]]]:
schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
- query = conn.query(
- f"SELECT table_name, column_name, data_type, is_nullable FROM `{_resolve_dataset_id(config)}.INFORMATION_SCHEMA.COLUMNS` ORDER BY table_name ASC",
- project=_resolve_query_project(config),
- )
try:
+ # Submitting the job triggers the lazy service-account token refresh, so an
+ # auth failure surfaces here rather than at `result()`.
+ query = conn.query(
+ f"SELECT table_name, column_name, data_type, is_nullable FROM `{_resolve_dataset_id(config)}.INFORMATION_SCHEMA.COLUMNS` ORDER BY table_name ASC",
+ project=_resolve_query_project(config),
+ )
rows = query.result()
except Forbidden:
structlog.get_logger().warning(
@@ -543,6 +565,15 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
config.dataset_id,
)
return {}
+ except TypeError as e:
+ # See `BigQueryTokenRefreshError`: google-auth raises an opaque
+ # `TypeError: string indices must be integers` when the OAuth token endpoint
+ # returns a non-JSON-object 200. Anything else is a genuine bug — let it propagate.
+ if "string indices must be integers" not in str(e):
+ raise
+ raise BigQueryTokenRefreshError(
+ f"{BIGQUERY_TOKEN_RESPONSE_ERROR}. Please re-upload your service account key file and verify its token_uri."
+ ) from e
for row in rows:
schema_list[row.table_name].append((row.column_name, row.data_type, row.is_nullable == "YES"))
diff --git a/posthog/temporal/data_imports/sources/bigquery/source.py b/posthog/temporal/data_imports/sources/bigquery/source.py
index cb4530e54275..f8ef13afda57 100644
--- a/posthog/temporal/data_imports/sources/bigquery/source.py
+++ b/posthog/temporal/data_imports/sources/bigquery/source.py
@@ -12,6 +12,7 @@ from posthog.schema import (
)
from posthog.temporal.data_imports.sources.bigquery.bigquery import (
+ BIGQUERY_TOKEN_RESPONSE_ERROR,
BigQueryImplementation,
build_destination_table_prefix,
validate_bigquery_credentials,
@@ -56,6 +57,11 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
# type. Delta Lake can't widen an existing column in place, so retrying won't help —
# the table must be reset and fully re-synced to adopt the new type.
"Source column type changed": "A column's type changed in your source database (for example an integer column was widened to bigint) and no longer fits the type we stored. We can't widen an existing column in place — please reset and fully re-sync this table to adopt the new type.",
+ # Raised from `BigQueryImplementation.get_columns` when the service-account OAuth
+ # token endpoint returns a non-JSON-object 200 (bad `token_uri`, or an intercepting
+ # proxy). Authentication can't succeed until the key file is fixed, so retrying just
+ # hammers the endpoint and spams error tracking.
+ BIGQUERY_TOKEN_RESPONSE_ERROR: "We couldn't authenticate with BigQuery — Google's OAuth token endpoint returned an unexpected response. Please re-upload your service account key file and verify its token_uri.",
}
def validate_credentials(
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 5a8820713b6e..3888dec58945 100644
--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -7,7 +7,9 @@ from google.api_core.exceptions import Forbidden, NotFound
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
from posthog.temporal.data_imports.sources.bigquery.bigquery import (
+ BIGQUERY_TOKEN_RESPONSE_ERROR,
BigQueryImplementation,
+ BigQueryTokenRefreshError,
_bq_select_clause,
_get_query,
_resolve_dataset_id,
@@ -84,6 +86,33 @@ def test_bigquery_get_columns_filters_existing_destination_tables():
assert list(columns.keys()) == ["table"]
+ "error_message,expected_type,is_token_refresh",
+ [
+ # A bad OAuth token endpoint makes google-auth raise this opaque `TypeError` during the
+ # lazy token refresh — `get_columns` must surface a clear, non-retryable error instead.
+ ("string indices must be integers, not 'str'", BigQueryTokenRefreshError, True),
+ # Any other `TypeError` indicates a genuine bug and must propagate unchanged.
+ ("unrelated bug", TypeError, False),
+ ],
+)
+def test_bigquery_get_columns_typeerror_handling(error_message, expected_type, is_token_refresh):
+ """Token-refresh `TypeError`s are wrapped as `BigQueryTokenRefreshError`; others propagate."""
+ fake_client = mock.MagicMock()
+ fake_client.query.side_effect = TypeError(error_message)
+
+ with pytest.raises(expected_type) as exc_info:
+ BigQueryImplementation().get_columns(fake_client, _make_config(), names=None)
+
+ assert isinstance(exc_info.value, BigQueryTokenRefreshError) == is_token_refresh
+ if is_token_refresh:
+ # The raised message must carry the stable marker registered as non-retryable.
+ assert BIGQUERY_TOKEN_RESPONSE_ERROR in str(exc_info.value)
+ assert BIGQUERY_TOKEN_RESPONSE_ERROR in BigQuerySource().get_non_retryable_errors()
+ else:
+ assert error_message in str(exc_info.value)
+
+
@pytest.mark.parametrize(
"dataset_project,temporary_dataset,expected_dataset_project_id,expected_destination_dataset_id",
[