: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): list google sheets worksheets once during schema discovery (#114181)
posthog[bot]f3c6ec13211a
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex 0b5ca68ea664..aef3f4abfb9f 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -2380,11 +2380,25 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([actions.setIsLoading(true)+ const sourceType = values.selectedConnector.name+ const startedAt = performance.now()+ const captureSchemasLoaded = (success: boolean, schemaCount: number | null): void => {+ posthog.capture('source wizard schemas loaded', {+ sourceType,+ success,+ schema_count: schemaCount,+ duration_ms: Math.round(performance.now() - startedAt),+ })+ }+try {- const schemas = await api.externalDataSources.database_schema(- values.selectedConnector.name,- getDatabaseSchemaPayload(values.source)- )+ const schemas = await api.externalDataSources+ .database_schema(sourceType, getDatabaseSchemaPayload(values.source))+ .catch((e) => {+ captureSchemasLoaded(false, null)+ throw e+ })+ captureSchemasLoaded(true, schemas.length)// Backend `cdc_available` only reflects the team flag — clear it when the// user didn't toggle CDC on for this source in step 1.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 1d731fe1fafe..8f439ce502f4 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@@ -2,7 +2,7 @@ import reimport timeimport randomfrom collections import Counter-from collections.abc import Callable+from collections.abc import Callable, Collectionfrom typing import Any, Optional, TypeVar, castimport gspread@@ -75,9 +75,20 @@ def google_sheets_client() -> gspread.Client:cache: Cache[Any, Any] = TTLCache(maxsize=500, ttl=120) # 120 seconds-max_attempts = 10-jitter_in_seconds = 10-sleep_per_attempt_in_seconds = 30+++@frozen+class _RetryBudget:+ max_attempts: int+ sleep_per_attempt_in_seconds: float+ jitter_in_seconds: float+++# Syncs run in Temporal activities, so they can wait out a per-minute quota (429) window.+_SYNC_RETRY_BUDGET = _RetryBudget(max_attempts=10, sleep_per_attempt_in_seconds=30, jitter_in_seconds=10)+# Schema discovery runs inside a web request while the user waits on the source wizard. A long+# backoff only holds the request open, so fail fast and let the user try again.+_DISCOVERY_RETRY_BUDGET = _RetryBudget(max_attempts=3, sleep_per_attempt_in_seconds=2, jitter_in_seconds=1)# Transient Google Sheets API failures worth retrying: 429 (per-minute quota exhausted), the# 5xx server-side errors Google returns intermittently (e.g. "[500]: Internal error encountered."),@@ -222,7 +233,7 @@ def _is_retryable_api_error(e: gspread.exceptions.APIError) -> bool:return False-def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:+def _retry_on_transient_api_error(execute: Callable[[], T], budget: _RetryBudget = _SYNC_RETRY_BUDGET) -> T:"""Run `execute` with linear backoff, retrying transient Google Sheets APIerrors. Google Sheets has a 300 request quota per minute, and also returnstransient 5xx server errors (see `_RETRYABLE_API_ERROR_CODES`). We retry both@@ -269,16 +280,25 @@ def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:is_retryable = _is_transient_refresh_error(e)else:is_retryable = True- if not is_retryable or attempts >= max_attempts:+ if not is_retryable or attempts >= budget.max_attempts:raise- jitter = random.uniform(-jitter_in_seconds, jitter_in_seconds)- sleep_with_jitter = sleep_per_attempt_in_seconds + jitter+ jitter = random.uniform(-budget.jitter_in_seconds, budget.jitter_in_seconds)+ sleep_with_jitter = budget.sleep_per_attempt_in_seconds + jittertime.sleep(sleep_with_jitter * attempts)attempts = attempts + 1+def _open_spreadsheet(client: gspread.Client, spreadsheet_url: str) -> gspread.Spreadsheet:+ try:+ return 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 e++@cached(cache)def _get_worksheet(spreadsheet_url: str, worksheet_id: int, api_version: str = GOOGLE_SHEETS_API_VERSION_V4@@ -286,14 +306,7 @@ def _get_worksheet(# `api_version` participates in the memoization key so a future version whose client differs# can't collide with a cached handle built for another version.def execute() -> gspread.Worksheet:- client = google_sheets_client()- try:- spreadsheet = 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 e- return spreadsheet.get_worksheet_by_id(worksheet_id)+ return _open_spreadsheet(google_sheets_client(), spreadsheet_url).get_worksheet_by_id(worksheet_id)return _retry_on_transient_api_error(execute)@@ -314,30 +327,54 @@ def get_schemas(config: GoogleSheetsSourceConfig) -> list[tuple[str, int]]:def get_worksheets(config: GoogleSheetsSourceConfig) -> list[DiscoveredWorksheet]:+ return [_discovered_worksheet(worksheet) for worksheet in _list_worksheets(config, _SYNC_RETRY_BUDGET)]+++def _list_worksheets(config: GoogleSheetsSourceConfig, budget: _RetryBudget) -> list[gspread.Worksheet]:+ client = google_sheets_client()# `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- except gspread.exceptions.SpreadsheetNotFound as e:- raise gspread.exceptions.SpreadsheetNotFound(_SPREADSHEET_NOT_FOUND_MESSAGE) from e- return spreadsheet.worksheets()-- worksheets = _retry_on_transient_api_error(execute)-- return [- DiscoveredWorksheet(- name=NamingConvention.normalize_identifier(worksheet.title),- title=worksheet.title,- worksheet_id=worksheet.id,+ def execute() -> list[gspread.Worksheet]:+ return _open_spreadsheet(client, config.spreadsheet_url).worksheets()++ return _retry_on_transient_api_error(execute, budget)+++def _discovered_worksheet(worksheet: gspread.Worksheet) -> DiscoveredWorksheet:+ return DiscoveredWorksheet(+ name=NamingConvention.normalize_identifier(worksheet.title),+ title=worksheet.title,+ worksheet_id=worksheet.id,+ )+++@frozen+class DiscoveredWorksheetSchema:+ worksheet: DiscoveredWorksheet+ incremental_fields: list[IncrementalField]+++def discover_worksheet_schemas(+ config: GoogleSheetsSourceConfig, names: Collection[str] | None = None+) -> list[DiscoveredWorksheetSchema]:+ """List the worksheets once and read each header row through the listed handles.++ The handles share one client and one token, so each worksheet costs one header read and+ no further spreadsheet lookups."""+ schemas: list[DiscoveredWorksheetSchema] = []+ for handle in _list_worksheets(config, _DISCOVERY_RETRY_BUDGET):+ worksheet = _discovered_worksheet(handle)+ if names is not None and worksheet.name not in names:+ continue+ schemas.append(+ DiscoveredWorksheetSchema(+ worksheet=worksheet,+ incremental_fields=_incremental_fields_from_header(handle, _DISCOVERY_RETRY_BUDGET),+ ))- for worksheet in worksheets- ]+ return schemasdef _resolve_worksheet_id(@@ -359,14 +396,9 @@ def _resolve_worksheet_id(return selected_worksheet[0]-def get_schema_incremental_fields(- config: GoogleSheetsSourceConfig, worksheet_name: str, api_version: str = GOOGLE_SHEETS_API_VERSION_V4-) -> list[IncrementalField]:- worksheet_id = _resolve_worksheet_id(config, worksheet_name, None, api_version)- worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id, api_version)-+def _incremental_fields_from_header(worksheet: gspread.Worksheet, budget: _RetryBudget) -> list[IncrementalField]:try:- rows = _retry_on_transient_api_error(lambda: worksheet.get_all_values("1:2")) # Get the first two rows+ rows = _retry_on_transient_api_error(lambda: worksheet.get_all_values("1:2"), budget) # Get the first two rowsexcept 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@@ -409,7 +441,7 @@ def google_sheets_source(try:headers = _retry_on_transient_api_error(lambda: worksheet.get_all_values("1:1")) # Get the first rowexcept gspread.exceptions.APIError as e:- # Same deterministic 400 handled in `get_schema_incremental_fields` above (e.g. empty+ # Same deterministic 400 handled in `_incremental_fields_from_header` above (e.g. empty# sheets, or sheets resized to have no columns) — treat it as a worksheet with no header# row rather than failing the sync.if e.code == 400 and "Unable to parse range" in str(e):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 9e111514e27b..9248e7382da6 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@@ -26,8 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets import (GOOGLE_SHEETS_API_VERSION_V4,- get_schema_incremental_fields as get_google_sheets_schema_incremental_fields,- get_worksheets as get_google_sheets_worksheets,+ discover_worksheet_schemas,google_sheets_client,google_sheets_source,)@@ -112,19 +111,10 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # Listing worksheets is version-agnostic (gspread's `worksheets()`), but the per-worksheet- # header read goes through `_get_worksheet`, whose memoization key includes the version —- # so discovery must resolve the pin rather than let it default.- resolved_version = self.resolve_api_version(api_version)- worksheets = get_google_sheets_worksheets(config)-- if names is not None:- names_set = set(names)- worksheets = [worksheet for worksheet in worksheets if worksheet.name in names_set]-schemas: list[SourceSchema] = []- for worksheet in worksheets:- incremental_fields = get_google_sheets_schema_incremental_fields(config, worksheet.name, resolved_version)+ for discovered in discover_worksheet_schemas(config, names=names):+ worksheet = discovered.worksheet+ incremental_fields = discovered.incremental_fieldsschemas.append(SourceSchema(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 f6c5c545d147..2b194def49e3 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@@ -15,11 +15,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets import (_REQUEST_TIMEOUT_SECONDS,GOOGLE_SHEETS_API_VERSION_V4,- DiscoveredWorksheet,_assert_unique_normalized_column_names,_get_worksheet,_retry_on_transient_api_error,- get_schema_incremental_fields,+ discover_worksheet_schemas,get_schemas,google_sheets_client,google_sheets_source,@@ -516,28 +515,37 @@ def test_assert_unique_normalized_column_names_raises_on_normalized_collision(heassert any(key in str(exc_info.value) for key in non_retryable_errors)-def test_get_schema_incremental_fields_skips_unparseable_range():+def _sheets_client_listing(*worksheets: mock.MagicMock) -> mock.MagicMock:+ client = mock.MagicMock()+ client.open_by_url.return_value.worksheets.return_value = list(worksheets)+ return client+++def _worksheet_handle(title: str, worksheet_id: int) -> mock.MagicMock:+ handle = mock.MagicMock()+ handle.title = title+ handle.id = worksheet_id+ return handle+++def test_discover_worksheet_schemas_skips_unparseable_range():"""Google rejects the unbounded "1:2" row range with a 400 'Unable to parse range' for someworksheets (e.g. empty sheets). That deterministic error must not break schema discovery — theworksheet should just report no incremental fields so the rest of the spreadsheet still syncs."""config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")- mock_worksheet = mock.MagicMock()- mock_worksheet.get_all_values.side_effect = _api_error(+ handle = _worksheet_handle("csm_followups", 123)+ handle.get_all_values.side_effect = _api_error(400, "Unable to parse range: 'csm_followups'!1:2", "INVALID_ARGUMENT")- with (- mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.get_schemas",- return_value=[("csm_followups", 123)],- ),- mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets._get_worksheet",- return_value=mock_worksheet,- ),+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.google_sheets_client",+ return_value=_sheets_client_listing(handle),):- assert get_schema_incremental_fields(config, "csm_followups") == []+ [schema] = discover_worksheet_schemas(config)++ assert schema.incremental_fields == []def test_google_sheets_source_skips_unparseable_header_range():@@ -602,30 +610,29 @@ def test_google_sheets_source_skips_unparseable_invalid_range_on_data_read():assert tables[0].num_rows == 0-def test_get_schema_incremental_fields_reraises_other_api_errors():+def test_discover_worksheet_schemas_reraises_other_api_errors_after_a_short_retry_budget():"""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."""+ retried and must still propagate rather than schema discovery silently reporting no incremental+ fields. Discovery runs inside a web request, so it uses a short retry budget, not the sync one."""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")+ handle = _worksheet_handle("sheet1", 123)+ handle.get_all_values.side_effect = _api_error(500, "Internal error encountered.", "INTERNAL")with (- mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.time"),mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.get_schemas",- return_value=[("sheet1", 123)],- ),+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.time"+ ) as mock_time,mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets._get_worksheet",- return_value=mock_worksheet,+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.google_sheets_client",+ return_value=_sheets_client_listing(handle),),pytest.raises(gspread.exceptions.APIError),):- get_schema_incremental_fields(config, "sheet1")+ discover_worksheet_schemas(config)- assert mock_worksheet.get_all_values.call_count == 10+ assert handle.get_all_values.call_count == 3+ assert sum(call.args[0] for call in mock_time.sleep.call_args_list) < 10def test_google_sheets_client_sets_request_timeout():@@ -827,20 +834,26 @@ def test_google_sheets_source_resolves_the_stored_worksheet_id_before_the_name(assert mock_get_worksheet.call_args.args[1] == expected_worksheet_id-def test_discovered_schemas_carry_the_worksheet_title_and_id():- with (- mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.get_google_sheets_worksheets",- return_value=[DiscoveredWorksheet(name="budget_2025", title="Budget 2025", worksheet_id=7)],- ),- mock.patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.get_google_sheets_schema_incremental_fields",- return_value=[],- ),- ):- config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")- [schema] = GoogleSheetsSource().get_schemas(config, team_id=1)+def test_discovered_schemas_list_worksheets_once_and_carry_title_and_id():+ budget = _worksheet_handle("Budget 2025", 7)+ budget.get_all_values.return_value = [["id"], [1]]+ notes = _worksheet_handle("Notes", 8)+ notes.get_all_values.return_value = [["text"], ["hello"]]+ client = _sheets_client_listing(budget, notes)- assert schema.name == "budget_2025"- assert schema.label == "Budget 2025"- assert schema.schema_metadata == {SCHEMA_RESOURCE_ID_METADATA_KEY: "7"}+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.google_sheets_client",+ return_value=client,+ ) as mock_client_factory:+ config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")+ schemas = GoogleSheetsSource().get_schemas(config, team_id=1)++ assert mock_client_factory.call_count == 1+ assert client.open_by_url.call_count == 1+ assert client.open_by_url.return_value.worksheets.call_count == 1+ assert budget.get_all_values.call_count == 1+ assert notes.get_all_values.call_count == 1+ assert [(s.name, s.label, s.schema_metadata, s.supports_incremental) for s in schemas] == [+ ("budget_2025", "Budget 2025", {SCHEMA_RESOURCE_ID_METADATA_KEY: "7"}, True),+ ("notes", "Notes", {SCHEMA_RESOURCE_ID_METADATA_KEY: "8"}, False),+ ]