: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(google_sheets): treat deleted-spreadsheet 404 as non-retryable (#66696)
Tom Owers336dd11a0e85
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 a561b12ad105..4309b85e50b8 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@@ -67,6 +67,17 @@ _RETRYABLE_API_ERROR_CODES = {429, 500, 502, 503, 504}# stable, descriptive message so downstream matching can identify it._PERMISSION_DENIED_MESSAGE = "Spreadsheet access denied. Please share the spreadsheet with the PostHog service account."+# gspread converts the Sheets API 404 into `SpreadsheetNotFound` — see gspread/client.py+# `open_by_key`: `raise SpreadsheetNotFound(ex.response) from ex`. Its `str()` is just the bare+# response repr (`<Response [404]>`); the "Requested entity was not found" text lives only on the+# chained APIError cause. The non-retryable matcher does a substring match over `str(e)`, so it has+# nothing to match on and a deleted/moved/unshared sheet gets retried indefinitely. Re-raise with a+# stable, descriptive message (mirroring `_PERMISSION_DENIED_MESSAGE` above) so it stops retrying.+_SPREADSHEET_NOT_FOUND_MESSAGE = (+ "Spreadsheet not found. The Google Sheet could not be found — it may have been deleted or "+ "moved, or is no longer shared with the PostHog service account."+)+T = TypeVar("T")@@ -127,6 +138,8 @@ def _get_worksheet(spreadsheet_url: str, worksheet_id: int) -> gspread.Worksheetspreadsheet = client.open_by_url(spreadsheet_url)except PermissionError as e:raise PermissionError(_PERMISSION_DENIED_MESSAGE) from e+ except gspread.exceptions.SpreadsheetNotFound as e:+ raise gspread.exceptions.SpreadsheetNotFound(_SPREADSHEET_NOT_FOUND_MESSAGE) from ereturn spreadsheet.get_worksheet_by_id(worksheet_id)return _retry_on_transient_api_error(execute)@@ -144,6 +157,8 @@ def get_schemas(config: GoogleSheetsSourceConfig) -> list[tuple[str, int]]:spreadsheet = client.open_by_url(config.spreadsheet_url)except PermissionError as e:raise PermissionError(_PERMISSION_DENIED_MESSAGE) from e+ except gspread.exceptions.SpreadsheetNotFound as e:+ raise gspread.exceptions.SpreadsheetNotFound(_SPREADSHEET_NOT_FOUND_MESSAGE) from ereturn spreadsheet.worksheets()worksheets = _retry_on_transient_api_error(execute)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 46bbd7792307..151306fbce52 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@@ -40,12 +40,13 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):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.","can't be found": None,- "SpreadsheetNotFound": 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",- # gspread raises APIError "[404]: Requested entity was not found." when the- # spreadsheet has been deleted or is otherwise unreachable. Retrying cannot recover.- "Requested entity was not found": "Import failed: the Google Sheet could not be found. It may have been deleted or moved. Please check the spreadsheet URL and that it is shared with our service account.",+ # gspread surfaces the Sheets API 404 (deleted/moved sheet, or access removed) as a+ # `SpreadsheetNotFound`, which `google_sheets.py` re-raises with this stable message —+ # `str(SpreadsheetNotFound)` is otherwise just `<Response [404]>`, with nothing to match.+ # Retrying cannot recover.+ "Spreadsheet not found": "Import failed: the Google Sheet could not be found. It may have been deleted or moved. Please check the spreadsheet URL and that it is shared with our service account.",}def get_schemas(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 6edd6d06198a..222ffba4ad17 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@@ -390,18 +390,37 @@ def test_permission_error_is_non_retryable():assert any(key in error_msg for key in non_retryable_errors)-def test_not_found_api_error_is_non_retryable():- """gspread raises a 404 APIError when the spreadsheet has been deleted/moved — it- must match a non-retryable pattern so we stop retrying a permanent failure."""- mock_response = mock.MagicMock()- mock_response.json.return_value = {- "error": {"code": 404, "message": "Requested entity was not found.", "status": "NOT_FOUND"}- }- error_msg = str(gspread.exceptions.APIError(mock_response))+ "call_site",+ [+ pytest.param(+ lambda: get_schemas(+ GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")+ ),+ id="get_schemas",+ ),+ # Use a unique url/id to avoid the module-level TTLCache returning a prior result+ pytest.param(lambda: _get_worksheet("not-found-url", 998), id="_get_worksheet"),+ ],+)+def test_reraises_spreadsheet_not_found_with_non_retryable_message(call_site):+ """gspread converts the Sheets API 404 (deleted/moved/unshared sheet) into+ `SpreadsheetNotFound`, whose `str()` is only `<Response [404]>` — so the non-retryable matcher+ (substring over `str(e)`) never fires and a permanent failure is retried forever. We must+ re-raise it with a stable message that matches one of the source's non-retryable keys."""+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.google_sheets_client"+ ) as mock_google_sheets_client:+ instance = mock_google_sheets_client.return_value+ instance.open_by_url.side_effect = gspread.exceptions.SpreadsheetNotFound(mock.MagicMock())++ with pytest.raises(gspread.exceptions.SpreadsheetNotFound) as exc_info:+ call_site()+ error_msg = str(exc_info.value)non_retryable_errors = GoogleSheetsSource().get_non_retryable_errors()assert any(key in error_msg for key in non_retryable_errors), (- f"Google Sheets 404 error {error_msg!r} did not match any non-retryable pattern"+ f"Re-raised SpreadsheetNotFound {error_msg!r} did not match any non-retryable pattern")