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(google_sheets): retry transient API errors during schema discovery (#63682)

Tom Owers0432d00b2419
diff --git a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
index 0347a594ec5a..7db3dd7c6b14 100644
--- a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
+++ b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
@@ -1,6 +1,7 @@
import time
import random
-from typing import Any, Optional
+from collections.abc import Callable
+from typing import Any, Optional, TypeVar
from django.conf import settings
@@ -56,22 +57,15 @@ _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."
+T = TypeVar("T")
-@cached(cache)
-def _get_worksheet(spreadsheet_url: str, worksheet_id: int) -> gspread.Worksheet:
- """Attempt to get a worksheet with linear backoff. Google Sheets has a 300
- request quota per minute, and also returns transient 5xx server errors. We
- retry both (see `_RETRYABLE_API_ERROR_CODES`) and add a +- 10s jitter to the
- sleep per attempt so that multiple jobs blocked by quota limits dont all retry
- at the same time"""
- def execute():
- client = google_sheets_client()
- try:
- spreadsheet = client.open_by_url(spreadsheet_url)
- except PermissionError as e:
- raise PermissionError(_PERMISSION_DENIED_MESSAGE) from e
- return spreadsheet.get_worksheet_by_id(worksheet_id)
+def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:
+ """Run `execute` with linear backoff, retrying transient Google Sheets API
+ errors. Google Sheets has a 300 request quota per minute, and also returns
+ transient 5xx server errors (see `_RETRYABLE_API_ERROR_CODES`). We retry both
+ and add a +- 10s jitter to the sleep per attempt so that multiple jobs blocked
+ by quota limits dont all retry at the same time."""
attempts = 1
@@ -89,15 +83,34 @@ def _get_worksheet(spreadsheet_url: str, worksheet_id: int) -> gspread.Worksheet
attempts = attempts + 1
+@cached(cache)
+def _get_worksheet(spreadsheet_url: str, worksheet_id: int) -> gspread.Worksheet:
+ def execute():
+ client = google_sheets_client()
+ try:
+ spreadsheet = client.open_by_url(spreadsheet_url)
+ except PermissionError as e:
+ raise PermissionError(_PERMISSION_DENIED_MESSAGE) from e
+ return spreadsheet.get_worksheet_by_id(worksheet_id)
+
+ return _retry_on_transient_api_error(execute)
+
+
def get_schemas(config: GoogleSheetsSourceConfig) -> list[tuple[str, int]]:
"""Returns a tuple of worksheets in the form of (title, id)"""
- client = google_sheets_client()
- try:
- spreadsheet = client.open_by_url(config.spreadsheet_url)
- except PermissionError as e:
- raise PermissionError(_PERMISSION_DENIED_MESSAGE) from e
- worksheets = spreadsheet.worksheets()
+ # `open_by_url` and `worksheets()` hit the Sheets API and so are subject to the same
+ # transient quota (429) and 5xx server errors as `_get_worksheet` — retry them with backoff
+ # rather than letting a transient blip fail the whole sync during schema discovery.
+ def execute():
+ client = google_sheets_client()
+ try:
+ spreadsheet = client.open_by_url(config.spreadsheet_url)
+ except PermissionError as e:
+ raise PermissionError(_PERMISSION_DENIED_MESSAGE) from e
+ return spreadsheet.worksheets()
+
+ worksheets = _retry_on_transient_api_error(execute)
return [(NamingConvention.normalize_identifier(worksheet.title), worksheet.id) for worksheet in worksheets]
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.py
index 93f4362475b0..41d32d5bb3f9 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
@@ -83,6 +83,59 @@ def test_get_worksheet_retries_transient_api_errors(status_code):
assert mock_get_worksheet_by_id.call_count == 10
[email protected]("status_code", [429, 500, 502, 503, 504])
+def test_get_schemas_retries_transient_api_errors(status_code):
+ """Schema discovery (`open_by_url`/`worksheets`) hits the Sheets API just like
+ `_get_worksheet`, so a transient quota 429 or 5xx server error (e.g.
+ "[500]: Internal error encountered.") must be retried with backoff rather than
+ failing the whole sync on the first occurrence."""
+ with (
+ mock.patch(
+ "posthog.temporal.data_imports.sources.google_sheets.google_sheets.google_sheets_client"
+ ) as mock_google_sheets_client,
+ mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"),
+ ):
+ mock_response = mock.MagicMock()
+ mock_response.json.return_value = {
+ "error": {"code": status_code, "message": "Internal error encountered.", "status": "INTERNAL"}
+ }
+
+ instance = mock_google_sheets_client.return_value
+ instance.open_by_url.side_effect = gspread.exceptions.APIError(mock_response)
+
+ config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")
+
+ with pytest.raises(gspread.exceptions.APIError):
+ get_schemas(config)
+
+ assert instance.open_by_url.call_count == 10
+
+
+def test_get_schemas_does_not_retry_non_transient_api_error():
+ """A non-transient API error (e.g. 400) raised during schema discovery should be
+ raised immediately without burning through the retry budget."""
+ with (
+ mock.patch(
+ "posthog.temporal.data_imports.sources.google_sheets.google_sheets.google_sheets_client"
+ ) as mock_google_sheets_client,
+ mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"),
+ ):
+ mock_response = mock.MagicMock()
+ mock_response.json.return_value = {
+ "error": {"code": 400, "message": "Bad request", "status": "INVALID_ARGUMENT"}
+ }
+
+ instance = mock_google_sheets_client.return_value
+ instance.open_by_url.side_effect = gspread.exceptions.APIError(mock_response)
+
+ config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")
+
+ with pytest.raises(gspread.exceptions.APIError):
+ get_schemas(config)
+
+ assert instance.open_by_url.call_count == 1
+
+
def test_get_worksheet_does_not_retry_non_transient_api_error():
"""A non-transient API error (e.g. 400) should be raised immediately without
burning through the retry budget."""