: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: Handle blanks in Google Sheets numeric columns (#63651)
Luke Beltone004d6517507
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py b/posthog/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.pyindex 3dbed53abd19..d09a58e17d4b 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py@@ -66,6 +66,39 @@ def test_table_from_py_list_inconsistent_other_types():)+def test_table_from_py_list_numeric_column_with_non_numeric_value_raises_named_error():+ with pytest.raises(TypeError) as exc_info:+ table_from_py_list([{"revenue": 1.5}, {"revenue": "N/A"}, {"revenue": ""}])++ message = str(exc_info.value)+ # Preserves the original phrase so source non-retryable matching still fires+ assert "must be real number, not str" in message+ # Names the column and shows the offending text and blank cells+ assert "revenue" in message+ assert "N/A" in message+ assert "<blank>" in message+++ "values,expected,type_check",+ [+ # Single float type -> float path+ ([1.5, None, 2.5, None], [1.5, None, 2.5, None], pa.types.is_floating),+ # Mixed numeric types -> decimal conversion path (len(unique_types_in_column) > 1)+ (+ [1.5, None, decimal.Decimal("2.5"), None],+ [decimal.Decimal("1.5"), None, decimal.Decimal("2.5"), None],+ pa.types.is_decimal,+ ),+ ],+)+def test_table_from_py_list_numeric_column_with_none_gaps(values, expected, type_check):+ table = table_from_py_list([{"column": value} for value in values])++ assert table.column("column").to_pylist() == expected+ assert type_check(table.schema.field("column").type)++def test_table_from_py_list_inconsistent_types_with_none():table = table_from_py_list([{"column": None}, {"column": "hello"}, {"column": 12}, {"column": None}])diff --git a/posthog/temporal/data_imports/pipelines/pipeline/utils.py b/posthog/temporal/data_imports/pipelines/pipeline/utils.pyindex 9c26628830eb..da2fbb37284e 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/utils.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/utils.py@@ -799,10 +799,14 @@ def _process_batch(table_data: list[dict], schema: Optional[pa.Schema] = None) -# Remove any NaN or infinite values from decimal columnsif issubclass(py_type, decimal.Decimal) or issubclass(py_type, float):- def _convert_to_decimal_or_none(x: decimal.Decimal | float | None) -> decimal.Decimal | None:+ def _convert_to_decimal_or_none(x: decimal.Decimal | float | str | None) -> decimal.Decimal | None:if x is None:return None+ if isinstance(x, str):+ # Non-numeric value in a column imported as a number; the caller adds column context.+ raise TypeError("must be real number, not str")+if (math.isnan(x)or (isinstance(x, decimal.Decimal) and x.is_infinite())@@ -815,10 +819,13 @@ def _process_batch(table_data: list[dict], schema: Optional[pa.Schema] = None) -return decimal.Decimal(str(x))- def _convert_to_float_or_none(x: float | None) -> float | None:+ def _convert_to_float_or_none(x: float | str | None) -> float | None:if x is None:return None+ if isinstance(x, str):+ raise TypeError("must be real number, not str")+if math.isnan(x) or np.isinf(x):return None@@ -828,7 +835,20 @@ def _process_batch(table_data: list[dict], schema: Optional[pa.Schema] = None) -if len(unique_types_in_column) > 1 or issubclass(py_type, decimal.Decimal):# Mixed types: convert all to decimals- all_values = [_convert_to_decimal_or_none(x) for x in all_values]+ try:+ all_values = [_convert_to_decimal_or_none(x) for x in all_values]+ except TypeError as e:+ # A column imported as a number contains a non-numeric value (text, or a+ # blank cell that arrives as ""). Keep the original "must be real number,+ # not str" phrase so source non-retryable matching still fires, but name the+ # column and show examples so the offending cells can be found in the source.+ offenders = [x for x in all_values if isinstance(x, str)]+ sample = [(x if x != "" else "<blank>") for x in offenders[:5]]+ raise TypeError(+ f"must be real number, not str: column '{field_name}' is imported as a "+ f"number but contains {len(offenders)} non-numeric value(s) such as "+ f"{sample}. Ensure every cell in this column is a plain number (or empty)."+ ) from eif arrow_schema and pa.types.is_decimal(arrow_schema.field(field_index).type):new_field_type = arrow_schema.field(field_index).typediff --git a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.pyindex 037a94e73f51..0347a594ec5a 100644--- a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py+++ b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py@@ -163,7 +163,9 @@ def google_sheets_source(def get_rows():worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id)- values = worksheet.get_all_records()+ # 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 = worksheet.get_all_records(default_blank=None)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/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py b/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.pyindex 77079df4539f..93f4362475b0 100644--- a/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py+++ b/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py@@ -1,3 +1,6 @@+from collections.abc import Iterable+from typing import Any, cast+import pytestfrom unittest import mock@@ -8,6 +11,7 @@ from posthog.temporal.data_imports.sources.google_sheets.google_sheets import (_PERMISSION_DENIED_MESSAGE,_get_worksheet,get_schemas,+ google_sheets_source,)from posthog.temporal.data_imports.sources.google_sheets.source import GoogleSheetsSource@@ -155,6 +159,32 @@ def test_reraises_permission_error_with_message(call_site):assert "Spreadsheet access denied" in str(exc_info.value)+def test_google_sheets_source_reads_blank_cells_as_null():+ 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},+ ]++ with (+ mock.patch(+ "posthog.temporal.data_imports.sources.google_sheets.google_sheets.get_schemas",+ return_value=[("sheet1", 123)],+ ),+ mock.patch(+ "posthog.temporal.data_imports.sources.google_sheets.google_sheets._get_worksheet",+ return_value=mock_worksheet,+ ),+ ):+ response = google_sheets_source(config, "sheet1", db_incremental_field_last_value=None)+ list(cast(Iterable[Any], response.items()))++ mock_worksheet.get_all_records.assert_called_once_with(default_blank=None)++def test_permission_error_is_non_retryable():"""The message we re-raise from gspread's bare PermissionError must be asubstring match for one of the source's non-retryable error keys, otherwise