: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): name unnamed Google Sheets columns instead of failing (#78197)
Tom Owers9396ed5fbd0b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/naming_convention.py b/products/warehouse_sources/backend/temporal/data_imports/naming_convention.pyindex c9824641d411..bda5f1bd6af8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/naming_convention.py+++ b/products/warehouse_sources/backend/temporal/data_imports/naming_convention.py@@ -53,7 +53,11 @@ class NamingConvention:raise ValueError("`name` is None")identifier = identifier.strip()if not identifier:- raise ValueError(identifier)+ # DLT raises this with the (empty) identifier as the only argument, which leaves+ # `str(exc)` empty. An empty message reaches the user as Temporal's placeholder+ # "Application error", so say what happened instead. The normalized output for every+ # other identifier is unchanged, which is what has to stay compatible.+ raise ValueError("`name` is empty or contains only whitespace")return _normalize_identifier(identifier, max_length)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.pyindex b58abff91952..4f57ec88ed84 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@@ -1,7 +1,8 @@import timeimport random+from collections import Counterfrom collections.abc import Callable-from typing import Any, Optional, TypeVar+from typing import Any, Optional, TypeVar, castfrom django.conf import settings@@ -10,6 +11,7 @@ import requestsfrom cachetools import Cache, TTLCache, cachedfrom google.auth.transport.requests import AuthorizedSessionfrom google.oauth2 import service_account+from gspread.utils import numericise_allfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list@@ -101,7 +103,7 @@ def _assert_unique_normalized_column_names(headers: list[str]) -> None:same column. gspread only rejects *exact* duplicate headers, so these near-duplicates slip past itand fail much later with an opaque "duplicate column name" deep in table creation, after the synchas 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."""+ offending headers instead. Exact duplicates are left to `_resolve_column_names`."""seen: dict[str, str] = {}for header in headers:if not header or not header.strip():@@ -112,11 +114,57 @@ def _assert_unique_normalized_column_names(headers: list[str]) -> None: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."+ f"them (it ignores case and punctuation, and drops characters outside a-z and 0-9, so "+ f"headers written entirely in another script all end up with the same name). Give one of "+ f"them a name that differs in its letters or digits, then resync.")seen[normalized] = header+def _resolve_column_names(headers: list[str]) -> list[str]:+ """Turn a worksheet's header row into a usable column name per position.++ Header cells are routinely blank: the Sheets API pads every row out to the width of the widest+ row, so a single stray value typed to the right of the header row invents columns with nothing+ in their header cell. gspread keys its records straight off the raw cells, which turns one blank+ header into a column literally named "" (rejected later by the naming convention with an empty+ error message) and two or more into its "contains duplicates" error. Name the unnamed columns+ after their position instead, so the sync completes with the data intact. Duplicated *named*+ headers still fail: there the user has two real names, and only they can decide which is which."""+ named = [header for header in headers if header and header.strip()]+ duplicates = sorted({header for header, count in Counter(named).items() if count > 1})+ if duplicates:+ # Keep gspread's wording — the source registers its user-facing message against this text.+ raise Exception(f"the header row in the worksheet contains duplicates: {duplicates}")++ taken = set(named)+ resolved: list[str] = []++ for position, header in enumerate(headers, start=1):+ if header and header.strip():+ resolved.append(header)+ continue++ name = f"column_{position}"+ while name in taken:+ name = f"_{name}"+ taken.add(name)+ resolved.append(name)++ return resolved+++def _records_from_grid(grid: list[list[str]]) -> list[dict[str, Any]]:+ if not grid or grid == [[]]:+ return []++ column_names = _resolve_column_names(list(grid[0]))++ # default_blank defaults to "", which turns empty cells into strings and breaks numeric+ # columns that legitimately have gaps. None lets blank cells import as null instead.+ return [dict(zip(column_names, numericise_all(row, default_blank=None))) for row in grid[1:]]++def _is_retryable_api_error(e: gspread.exceptions.APIError) -> bool:"""Decide whether a gspread APIError is a transient error worth retrying.@@ -147,7 +195,7 @@ def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:by quota limits dont all retry at the same time.This wraps every gspread call that hits the API — worksheet acquisition *and* the- cell-reading calls (`get_all_values`/`get_all_records`). The reads issue their own+ cell-reading calls (`get_all_values`/`get`). The reads issue their ownrequests, so a transient 5xx there must be retried too rather than failing the sync."""attempts = 1@@ -289,9 +337,9 @@ def google_sheets_source(primary_keys = ["id"]# Note: this source intentionally remains a SimpleSource rather than a ResumableSource.- # gspread's get_all_records() performs a single Sheets API call that returns every row at- # once, with no pagination cursor, continuation token, or range handle exposed to the- # caller. The loop below yields exactly one batch, so there is no intermediate checkpoint+ # The grid read below performs a single Sheets API call that returns every row at once,+ # with no pagination cursor, continuation token, or range handle exposed to the caller.+ # The loop below yields exactly one batch, so there is no intermediate checkpoint# where some rows have been emitted and others are still pending — the two states are# "nothing yielded yet" and "fully done". A ResumableSource would have no cursor to# persist and would still have to re-download the entire sheet on restart, so it adds no@@ -301,9 +349,11 @@ def google_sheets_source(def get_rows():worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id, api_version)- # default_blank defaults to "", which turns empty cells into strings and breaks numeric- # columns that legitimately have gaps. None lets blank cells import as null instead.- values = _retry_on_transient_api_error(lambda: worksheet.get_all_records(default_blank=None))+ # Read the raw grid and build the records ourselves rather than calling+ # `get_all_records`, which can't cope with a blank header cell. `pad_values=True` mirrors+ # what `get_all_records` asks for, so every row is the same width as the widest one.+ grid = cast(list[list[str]], _retry_on_transient_api_error(lambda: worksheet.get(pad_values=True)))+ values = _records_from_grid(grid)if should_use_incremental_field and db_incremental_field_last_value is not None:values = [value for value in values if value.get("id", 0) > db_incremental_field_last_value]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.pyindex ab1a3ee72d04..a6f8300043e0 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@@ -51,7 +51,7 @@ 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.",+ "the header row in the worksheet contains duplicates": "Import failed: two or more columns in the worksheet share the same header. Give each one a distinct name and resync.",# 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.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.pyindex 978523c590a9..cd11bc0515f5 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@@ -376,18 +376,17 @@ def test_retry_on_transient_api_error_bubbles_network_error_after_max_retries(erdef test_google_sheets_source_retries_transient_error_on_data_reads():- """A transient 5xx on the cell-reading calls (`get_all_values`/`get_all_records`)- must be retried, not surfaced on the first occurrence. These reads issue their own- Sheets API requests separate from worksheet acquisition, so they need the same- backoff — otherwise a "[503]: The service is currently unavailable." blip fails the- sync."""+ """A transient 5xx on the cell-reading calls (`get_all_values`/`get`) must be retried,+ not surfaced on the first occurrence. These reads issue their own Sheets API requests+ separate from worksheet acquisition, so they need the same backoff — otherwise a+ "[503]: The service is currently unavailable." blip fails the sync."""config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")mock_worksheet = mock.MagicMock()# First header read hits a transient 503, then succeeds on retry.mock_worksheet.get_all_values.side_effect = [_api_error(503), [["id"]]]- # The data read also hits a transient 503 once before returning rows.- mock_worksheet.get_all_records.side_effect = [_api_error(503), [{"id": 1}]]+ # The data read also hits a transient 503 once before returning the grid.+ mock_worksheet.get.side_effect = [_api_error(503), [["id"], ["1"]]]with (mock.patch(@@ -406,18 +405,15 @@ def test_google_sheets_source_retries_transient_error_on_data_reads():list(cast(Iterable[Any], response.items()))assert mock_worksheet.get_all_values.call_count == 2- assert mock_worksheet.get_all_records.call_count == 2+ assert mock_worksheet.get.call_count == 2-def test_google_sheets_source_reads_blank_cells_as_null():+def _read_sheet(header_row: list[str], data_rows: list[list[str]]) -> list[Any]:config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")mock_worksheet = mock.MagicMock()- mock_worksheet.get_all_values.return_value = [["id", "NumericColumnWithBlanks"]]- mock_worksheet.get_all_records.return_value = [- {"id": 1, "NumericColumnWithBlanks": 1.5},- {"id": 2, "NumericColumnWithBlanks": None},- ]+ mock_worksheet.get_all_values.return_value = [header_row]+ mock_worksheet.get.return_value = [header_row, *data_rows]with (mock.patch(@@ -432,9 +428,51 @@ def test_google_sheets_source_reads_blank_cells_as_null():response = google_sheets_source(config, "sheet1", db_incremental_field_last_value=None, api_version=GOOGLE_SHEETS_API_VERSION_V4)- list(cast(Iterable[Any], response.items()))+ return list(cast(Iterable[Any], response.items()))+++def test_google_sheets_source_reads_blank_cells_as_null():+ """Blank cells must import as null, not as "" — an empty string in an otherwise numeric column+ turns it into a text column. The source numericises the grid itself, so this covers that wiring."""+ tables = _read_sheet(["id", "NumericColumnWithBlanks"], [["1", "1.5"], ["2", ""]])++ assert tables[0].to_pylist() == [+ {"id": 1, "NumericColumnWithBlanks": 1.5},+ {"id": 2, "NumericColumnWithBlanks": None},+ ]- mock_worksheet.get_all_records.assert_called_once_with(default_blank=None)++ "header_row,expected_columns",+ [+ pytest.param(["id", "", "name"], ["id", "column_2", "name"], id="blank_header_between_named"),+ pytest.param(["id", "name", " "], ["id", "name", "column_3"], id="whitespace_only_header"),+ # Google pads every row out to the width of the widest one, so a stray value to the right of+ # the header row can invent several unnamed columns at once.+ pytest.param(["id", "", ""], ["id", "column_2", "column_3"], id="several_blank_headers"),+ # A generated name must not steal a name a real header already uses.+ pytest.param(["", "column_1"], ["_column_1", "column_1"], id="generated_name_avoids_real_header"),+ ],+)+def test_google_sheets_source_names_columns_with_blank_headers(header_row, expected_columns):+ """A header cell with nothing in it used to produce a column named "", which the naming+ convention rejected with an empty error message — the sync failed permanently and the user was+ told only "Application error". Every column must come out with a usable name instead."""+ tables = _read_sheet(header_row, [["1"] * len(header_row)])++ # Sorted because the pipeline decides the column order in the arrow table, not the source.+ assert sorted(tables[0].column_names) == sorted(expected_columns)+ assert tables[0].num_rows == 1+++def test_google_sheets_source_rejects_duplicate_named_headers():+ """Two columns under the same name would silently collapse into one, so the sync must fail with+ a message the framework knows is permanent. This check used to be gspread's, and is now ours."""+ with pytest.raises(Exception) as exc_info:+ _read_sheet(["id", "name", "name"], [["1", "a", "b"]])++ non_retryable_errors = GoogleSheetsSource().get_non_retryable_errors()+ assert any(key in str(exc_info.value) for key in non_retryable_errors)@pytest.mark.parametrize(@@ -509,6 +547,9 @@ def test_reraises_spreadsheet_not_found_with_non_retryable_message(call_site):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"),+ # Normalization drops everything outside a-z and 0-9, so headers written entirely in another+ # script all reduce to the same name however different they look.+ pytest.param(["Дата", "Клиент"], id="distinct_non_latin_headers"),],)def test_assert_unique_normalized_column_names_raises_on_normalized_collision(headers):@@ -696,7 +737,7 @@ def test_source_for_pipeline_threads_resolved_api_version_to_worksheet(pinned_veworksheet = mock.MagicMock()worksheet.get_all_values.return_value = [["id"]]- worksheet.get_all_records.return_value = [{"id": 1}]+ worksheet.get.return_value = [["id"], ["1"]]inputs = mock.MagicMock()inputs.schema_name = "sheet1"diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_naming_convention.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_naming_convention.pyindex 0fd1f2cd468e..fad9ec5946a3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_naming_convention.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_naming_convention.py@@ -94,7 +94,9 @@ class TestNamingConvention:@pytest.mark.parametrize("value", ["", " ", " ", "\t\n"])def test_empty_after_strip_raises(self, value):- with pytest.raises(ValueError):+ # The message has to say something: an exception with an empty str() reaches the user as+ # Temporal's "Application error" placeholder, which tells them nothing at all.+ with pytest.raises(ValueError, match="empty"):NamingConvention.normalize_identifier(value)@pytest.mark.parametrize("source,expected", HAND_VERIFIED_CASES)