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): fail fast when posthog can't impersonate a bigquery destination account (#115033)

Tom Owers13c24c485b9e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_bigquery_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_bigquery_writer.py
index 073a72cd2a10..4b9b2bf7af56 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_bigquery_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_bigquery_writer.py
@@ -6,13 +6,17 @@ from unittest.mock import MagicMock
import pyarrow as pa
import pyarrow.parquet as pq
-from google.api_core.exceptions import NotFound
+from google.api_core.exceptions import NotFound, ServiceUnavailable
+from google.auth.exceptions import RefreshError
from google.cloud import bigquery
from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ DestinationConfigurationError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.tests.fake_bigquery import (
FakeBigQueryClient,
MergeMultiMatchError,
@@ -25,6 +29,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
staging_table_name,
)
+_IMPERSONATION_DENIED_BODY = (
+ '{"error": {"code": 403, "message": "Permission \'iam.serviceAccounts.getAccessToken\' denied on resource '
+ '(or it may not exist).", "status": "PERMISSION_DENIED"}}'
+)
+
def _ctx(
schema_id: str = "schema",
@@ -189,6 +198,29 @@ class TestConfigValidation:
with pytest.raises(BigQueryDestinationConfigurationError):
BigQueryDestinationWriter(ctx)
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "denial",
+ [
+ RefreshError("Unable to acquire impersonated credentials", _IMPERSONATION_DENIED_BODY),
+ # The same refusal raised inside a gRPC auth plugin, which reaches the caller as a 503.
+ ServiceUnavailable(
+ f"Getting metadata from plugin failed with error: "
+ f"('Unable to acquire impersonated credentials', '{_IMPERSONATION_DENIED_BODY}')"
+ ),
+ ],
+ ids=["rest", "grpc"],
+ )
+ async def test_a_service_account_posthog_cannot_impersonate_is_a_configuration_error(
+ self, denial: Exception
+ ) -> None:
+ client = FakeBigQueryClient()
+ client.create_dataset = MagicMock(side_effect=denial) # type: ignore[method-assign]
+ writer = LocalBigQueryWriter(_ctx(), client)
+
+ with pytest.raises(DestinationConfigurationError, match="Token Creator"):
+ await writer.prepare_run(_ctx())
+
@pytest.mark.asyncio
class TestFullRefresh:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/bigquery.py
index c05454dfbfcf..a177c9402202 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/bigquery.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/bigquery.py
@@ -13,7 +13,8 @@ from __future__ import annotations
import io
import hashlib
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Iterator
+from contextlib import contextmanager
from typing import ClassVar
import pyarrow as pa
@@ -33,6 +34,9 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contr
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
+ DestinationConfigurationError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.merge_dedup import (
dedupe_merge_source,
)
@@ -57,6 +61,11 @@ _OWNERSHIP_LABEL_KEY = "posthog_sync_schema"
# complete table.
_PUBLISHED_RUN_LABEL_KEY = "posthog_sync_run"
+IMPERSONATION_DENIED_DETAIL = (
+ "PostHog can't act as your Google Cloud service account. Grant the PostHog service account the "
+ "Service Account Token Creator role on it, then run the sync again."
+)
+
class BigQueryDestinationConfigurationError(ValueError):
"""The destination's config cannot produce a valid BigQuery write."""
@@ -66,6 +75,17 @@ class UnrelatedTableExistsError(RuntimeError):
"""A sync would have overwritten, merged into or appended to a table it never created."""
+def _is_impersonation_denied(err: Exception) -> bool:
+ """Whether Google refused to mint a token for the service account PostHog impersonates.
+
+ The refusal comes lazily, on the first request that needs a token. Over REST it is a
+ `RefreshError`, and over gRPC the auth plugin's failure reaches the caller as a 503, so the
+ wording is all the two shapes share. Same match as the BigQuery source's validation.
+ """
+ message = str(err)
+ return "iam.serviceAccounts.getAccessToken" in message and "denied" in message
+
+
def staging_table_name(ctx: DestinationRunContext) -> str:
return f"{ctx.table_name}__ph_stage_{run_scope(ctx.run_uuid)}"
@@ -137,6 +157,16 @@ class BigQueryDestinationWriter:
self._project = self._project or self._client.project or ""
return self._client
+ @contextmanager
+ def _impersonation_denied_as_configuration_error(self) -> Iterator[None]:
+ # Without this, the 503 shape reads as transient and the run retries until it gives up.
+ try:
+ yield
+ except Exception as err:
+ if _is_impersonation_denied(err):
+ raise DestinationConfigurationError(self._ctx.destination_name, IMPERSONATION_DENIED_DETAIL) from err
+ raise
+
def _table_ref(self, table: str) -> str:
return f"{self._project}.{self._dataset}.{table}"
@@ -210,10 +240,17 @@ class BigQueryDestinationWriter:
client = self._get_client()
client.create_dataset(f"{self._project}.{self._dataset}", exists_ok=True)
- await sync_to_async(ensure_dataset, thread_sensitive=False)()
+ with self._impersonation_denied_as_configuration_error():
+ await sync_to_async(ensure_dataset, thread_sensitive=False)()
async def write_batch(
self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
+ ) -> BatchWriteOutcome:
+ with self._impersonation_denied_as_configuration_error():
+ return await self._write_batch(batches, ctx)
+
+ async def _write_batch(
+ self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
) -> BatchWriteOutcome:
if ctx.run.is_full_refresh and await sync_to_async(self._already_published, thread_sensitive=False)(ctx.run):
# This run's staging table is gone and the live table carries this run's publish
@@ -391,7 +428,8 @@ class BigQueryDestinationWriter:
self._mark_published(client, target_ref)
client.delete_table(self._table_ref(staging), not_found_ok=True)
- await sync_to_async(publish, thread_sensitive=False)()
+ with self._impersonation_denied_as_configuration_error():
+ await sync_to_async(publish, thread_sensitive=False)()
async def abort_run(self, ctx: DestinationRunContext) -> None:
# No `self._client is None` guard: `abort_destinations` builds a fresh writer for this