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 early on colliding Google Sheets headers (#71982)

Tom Owers1e7b3563b79c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
index f59f4f2bc328..06572dae4f3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
@@ -82,6 +82,30 @@ _SPREADSHEET_NOT_FOUND_MESSAGE = (
T = TypeVar("T")
+def _assert_unique_normalized_column_names(headers: list[str]) -> None:
+ """Fail early when two header cells collapse to the same column name.
+
+ Sheet headers become table column names via `NamingConvention`, which is case-insensitive and
+ collapses spaces/punctuation — so headers that look distinct ("Task ID" vs "task_id") map to the
+ same column. gspread only rejects *exact* duplicate headers, so these near-duplicates slip past it
+ and fail much later with an opaque "duplicate column name" deep in table creation, after the sync
+ has already started. Detect the collision up front and raise an actionable message naming the
+ offending headers instead. Exact duplicates are left to gspread's own check."""
+ seen: dict[str, str] = {}
+ for header in headers:
+ if not header or not header.strip():
+ continue
+ normalized = NamingConvention.normalize_identifier(header)
+ previous = seen.get(normalized)
+ if previous is not None and previous != header:
+ raise Exception(
+ f'Column headers "{previous}" and "{header}" collapse to the same column name '
+ f'"{normalized}" when synced. Column headers must stay unique after PostHog normalizes '
+ f"them (it ignores case, spaces, and punctuation). Rename one of them and resync."
+ )
+ seen[normalized] = header
+
+
def _is_retryable_api_error(e: gspread.exceptions.APIError) -> bool:
"""Decide whether a gspread APIError is a transient error worth retrying.
@@ -240,6 +264,8 @@ def google_sheets_source(
worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id)
headers = _retry_on_transient_api_error(lambda: worksheet.get_all_values("1:1")) # Get the first row
+ if len(headers) > 0:
+ _assert_unique_normalized_column_names(headers[0])
primary_keys = None
if len(headers) > 0 and "id" in headers[0]:
primary_keys = ["id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py
index ef195c4c4e20..afde9a523cb9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py
@@ -42,6 +42,10 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
"the header row in the worksheet contains duplicates": "Import failed: There exists duplicate column headers. Please make sure all column headers have values and aren't duplicated.",
+ # Raised by `_assert_unique_normalized_column_names`: two headers that look distinct
+ # collapse to the same normalized column name. Deterministic — retrying can't recover, and
+ # the message already names the offending headers, so keep it as-is.
+ "collapse to the same column name": None,
"can't be found": None,
"must be real number, not str": "Import failed: a numeric column contains a non-numeric value. Ensure every cell in numeric columns is stored as a plain number.",
"Spreadsheet access denied": "Import failed: PostHog does not have access to this spreadsheet. Please share it with our service account as described at https://posthog.com/docs/cdp/sources/google-sheets",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
index 6547334fb08a..87fa4a078d49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets import (
_PERMISSION_DENIED_MESSAGE,
_REQUEST_TIMEOUT_SECONDS,
+ _assert_unique_normalized_column_names,
_get_worksheet,
_retry_on_transient_api_error,
get_schema_incremental_fields,
@@ -481,6 +482,39 @@ def test_reraises_spreadsheet_not_found_with_non_retryable_message(call_site):
)
+ "headers",
+ [
+ pytest.param(["Task ID", "task_id"], id="case_and_punctuation"),
+ pytest.param(["task_id", "task-id"], id="punctuation_only"),
+ pytest.param(["Name", "name"], id="case_only"),
+ pytest.param(["id", "customer name", "Customer Name"], id="collision_among_distinct"),
+ ],
+)
+def test_assert_unique_normalized_column_names_raises_on_normalized_collision(headers):
+ """Headers that differ only by case/punctuation collapse to one column name and would otherwise
+ fail with an opaque error deep in table creation. The raised message must also match one of the
+ source's non-retryable keys, or the deterministic failure gets retried forever."""
+ with pytest.raises(Exception) as exc_info:
+ _assert_unique_normalized_column_names(headers)
+
+ non_retryable_errors = GoogleSheetsSource().get_non_retryable_errors()
+ assert any(key in str(exc_info.value) for key in non_retryable_errors)
+
+
+ "headers",
+ [
+ pytest.param(["id", "name", "email"], id="distinct"),
+ pytest.param(["id", "", "name"], id="blank_cells_ignored"),
+ # Exact duplicates are left to gspread's own "contains duplicates" check.
+ pytest.param(["id", "id"], id="exact_duplicate"),
+ ],
+)
+def test_assert_unique_normalized_column_names_allows_valid_headers(headers):
+ _assert_unique_normalized_column_names(headers)
+
+
def test_get_schema_incremental_fields_skips_unparseable_range():
"""Google rejects the unbounded "1:2" row range with a 400 'Unable to parse range' for some
worksheets (e.g. empty sheets). That deterministic error must not break schema discovery — the