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 on sheet data reads (#63745)

Tom Owers2490b4407ae7
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 e886c804904b..19b1de7e5a5e 100644
--- a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
+++ b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
@@ -65,7 +65,11 @@ def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:
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."""
+ 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
+ requests, so a transient 5xx there must be retried too rather than failing the sync."""
attempts = 1
@@ -85,7 +89,7 @@ def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:
@cached(cache)
def _get_worksheet(spreadsheet_url: str, worksheet_id: int) -> gspread.Worksheet:
- def execute():
+ def execute() -> gspread.Worksheet:
client = google_sheets_client()
try:
spreadsheet = client.open_by_url(spreadsheet_url)
@@ -126,7 +130,7 @@ def get_schema_incremental_fields(config: GoogleSheetsSourceConfig, worksheet_na
worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id)
try:
- rows = worksheet.get_all_values("1:2") # Get the first two rows
+ rows = _retry_on_transient_api_error(lambda: worksheet.get_all_values("1:2")) # Get the first two rows
except gspread.exceptions.APIError as e:
# Google rejects the unbounded "1:2" row range with a 400 "Unable to parse range" for
# some worksheets (e.g. empty sheets, or sheets resized to have no columns). This is
@@ -170,7 +174,7 @@ def google_sheets_source(
worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id)
- headers = worksheet.get_all_values("1:1") # Get the first row
+ headers = _retry_on_transient_api_error(lambda: worksheet.get_all_values("1:1")) # Get the first row
primary_keys = None
if len(headers) > 0 and "id" in headers[0]:
primary_keys = ["id"]
@@ -190,7 +194,7 @@ def google_sheets_source(
# 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)
+ values = _retry_on_transient_api_error(lambda: 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.py
index ccf8ba39c1fb..ad92be08114b 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
@@ -10,6 +10,7 @@ from posthog.temporal.data_imports.sources.generated_configs import GoogleSheets
from posthog.temporal.data_imports.sources.google_sheets.google_sheets import (
_PERMISSION_DENIED_MESSAGE,
_get_worksheet,
+ _retry_on_transient_api_error,
get_schema_incremental_fields,
get_schemas,
google_sheets_source,
@@ -17,10 +18,12 @@ from posthog.temporal.data_imports.sources.google_sheets.google_sheets import (
from posthog.temporal.data_imports.sources.google_sheets.source import GoogleSheetsSource
-def _api_error(code: int, message: str, status: str) -> gspread.exceptions.APIError:
- response = mock.MagicMock()
- response.json.return_value = {"error": {"code": code, "message": message, "status": status}}
- return gspread.exceptions.APIError(response)
+def _api_error(
+ status_code: int, message: str = "transient", status: str = "UNAVAILABLE"
+) -> gspread.exceptions.APIError:
+ mock_response = mock.MagicMock()
+ mock_response.json.return_value = {"error": {"code": status_code, "message": message, "status": status}}
+ return gspread.exceptions.APIError(mock_response)
def test_get_worksheet_backoff():
@@ -219,6 +222,61 @@ def test_reraises_permission_error_with_message(call_site):
assert "Spreadsheet access denied" in str(exc_info.value)
[email protected]("status_code", [429, 500, 502, 503, 504])
+def test_retry_on_transient_api_error_retries_then_exhausts(status_code):
+ """The shared retry helper must retry transient API errors (quota 429s and 5xx
+ server errors like "[503]: The service is currently unavailable.") with backoff."""
+ with mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"):
+ fn = mock.MagicMock(side_effect=_api_error(status_code))
+
+ with pytest.raises(gspread.exceptions.APIError):
+ _retry_on_transient_api_error(fn)
+
+ assert fn.call_count == 10
+
+
+def test_retry_on_transient_api_error_does_not_retry_non_transient():
+ with mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"):
+ fn = mock.MagicMock(side_effect=_api_error(400, status="INVALID_ARGUMENT"))
+
+ with pytest.raises(gspread.exceptions.APIError):
+ _retry_on_transient_api_error(fn)
+
+ assert fn.call_count == 1
+
+
+def 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."""
+ 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}]]
+
+ 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,
+ ),
+ mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"),
+ ):
+ response = google_sheets_source(config, "sheet1", db_incremental_field_last_value=None)
+ list(cast(Iterable[Any], response.items()))
+
+ assert mock_worksheet.get_all_values.call_count == 2
+ assert mock_worksheet.get_all_records.call_count == 2
+
+
def test_google_sheets_source_reads_blank_cells_as_null():
config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")
@@ -298,14 +356,16 @@ def test_get_schema_incremental_fields_skips_unparseable_range():
def test_get_schema_incremental_fields_reraises_other_api_errors():
- """Only the deterministic 'Unable to parse range' 400 is swallowed. Other API errors (e.g.
- transient 5xx) must still propagate so Temporal can retry them."""
+ """Only the deterministic 'Unable to parse range' 400 is swallowed. Transient 5xx errors are
+ retried with backoff and, once retries are exhausted, must still propagate so Temporal can retry
+ the activity rather than schema discovery silently reporting no incremental fields."""
config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")
mock_worksheet = mock.MagicMock()
mock_worksheet.get_all_values.side_effect = _api_error(500, "Internal error encountered.", "INTERNAL")
with (
+ mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"),
mock.patch(
"posthog.temporal.data_imports.sources.google_sheets.google_sheets.get_schemas",
return_value=[("sheet1", 123)],
@@ -317,3 +377,5 @@ def test_get_schema_incremental_fields_reraises_other_api_errors():
pytest.raises(gspread.exceptions.APIError),
):
get_schema_incremental_fields(config, "sheet1")
+
+ assert mock_worksheet.get_all_values.call_count == 10