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(data-warehouse): find renamed google sheets worksheets on the sync method tab (#116527)

Kyle Swankbc0828a9e62c
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index f5acddfd4bac..97dffee054a0 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -38,6 +38,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
SCHEMA_RESOURCE_ID_METADATA_KEY,
ExternalDataSchema,
auto_enable_new_schemas,
+ discovered_schema_finder,
get_all_schemas_for_source_id,
get_schemas_for_direct_reconciliation,
mark_schema_running_unless_halted,
@@ -108,6 +109,7 @@ __all__ = [
"acreate_datawarehousetable",
"asave_datawarehousetable",
"auto_enable_new_schemas",
+ "discovered_schema_finder",
"create_datawarehousetable",
"get_all_schemas_for_source_id",
"get_schemas_for_direct_reconciliation",
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 7b0f001884f1..581c8d5cd8d9 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -2248,6 +2248,31 @@ def _resource_id(metadata: object) -> str | None:
return None
+def discovered_schema_finder(
+ discovered: Iterable["SourceSchema"],
+) -> Callable[[str, object], "SourceSchema | None"]:
+ """Return a lookup that finds the discovered schema for a stored one: by its stable resource id
+ first, then by name.
+
+ A renamed resource keeps its id but not its name, so a match by name alone misses it. Build one
+ lookup per discovery, so that matching many stored schemas costs one dict read each."""
+ by_resource_id: dict[str, SourceSchema] = {}
+ by_name: dict[str, SourceSchema] = {}
+ for discovered_schema in discovered:
+ resource_id = _resource_id(discovered_schema.schema_metadata)
+ if resource_id is not None:
+ by_resource_id.setdefault(resource_id, discovered_schema)
+ by_name.setdefault(discovered_schema.name, discovered_schema)
+
+ def find(stored_name: str, stored_metadata: object) -> "SourceSchema | None":
+ stored_resource_id = _resource_id(stored_metadata)
+ if stored_resource_id is not None and stored_resource_id in by_resource_id:
+ return by_resource_id[stored_resource_id]
+ return by_name.get(stored_name)
+
+ return find
+
+
def _renamed_schema_names(
old_schemas: list["ExternalDataSchema"],
new_schema_names: list[str],
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index 7628e21b2769..0d980c726de4 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -46,11 +46,13 @@ from products.warehouse_sources.backend.facade.models import (
CDC_SNAPSHOT_LANE_KEY,
MAX_FULL_REFRESH_INTERVAL_DAYS,
SCHEDULED_FULL_REFRESH_SYNC_TYPES,
+ SCHEMA_RESOURCE_ID_METADATA_KEY,
ExternalDataJob,
ExternalDataSchema,
ExternalDataSchemaDestination,
ExternalDataSource,
UnsupportedSyncTypeError,
+ discovered_schema_finder,
mark_schema_running_unless_halted,
resolve_destinations,
resolve_sync_type,
@@ -2350,10 +2352,27 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
data={"message": credentials_error or "Invalid credentials"},
)
+ stored_resource_id = (
+ (instance.schema_metadata or {}).get(SCHEMA_RESOURCE_ID_METADATA_KEY)
+ if new_source.uses_stable_schema_resource_ids
+ else None
+ )
try:
schemas = new_source.get_schemas(
config, self.team_id, names=[instance.name], api_version=effective_api_version
)
+ # A stored resource id can outlive the stored name after an upstream rename. Discover every
+ # schema only when the name lookup misses that id, so an unrenamed schema keeps the cheap
+ # filtered discovery.
+ if stored_resource_id is not None:
+ found = discovered_schema_finder(schemas)(instance.name, instance.schema_metadata)
+ found_resource_id = (
+ (found.schema_metadata or {}).get(SCHEMA_RESOURCE_ID_METADATA_KEY) if found else None
+ )
+ if str(found_resource_id) != str(stored_resource_id):
+ schemas = new_source.get_schemas(
+ config, self.team_id, names=None, api_version=effective_api_version
+ )
except Exception as e:
# `validate_credentials` above just probed the same connection successfully, so a
# failure here that the source itself classifies is an expected customer or upstream
@@ -2384,7 +2403,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# Not every source honors the `names` filter (e.g. Slack returns all schemas regardless), so
# `schemas` may contain unrelated tables in any order. Pick the one that matches this schema
# instead of trusting `schemas[0]`, whose metadata could belong to a different table.
- schema = next((s for s in schemas if s.name == instance.name), None)
+ schema = discovered_schema_finder(schemas)(instance.name, instance.schema_metadata)
if schema is None:
return Response(
status=status.HTTP_400_BAD_REQUEST, data={"message": f"Schema with name {instance.name} not found"}
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
index 4db0da53c366..c2ead35a76c3 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
@@ -21,10 +21,10 @@ from products.access_control.backend.facade.user_access_control import access_le
from products.data_warehouse.backend.facade.api import get_direct_query_engine, get_namespaced_resource_adapter
from products.warehouse_sources.backend.facade.models import (
MAX_FULL_REFRESH_INTERVAL_DAYS,
- SCHEMA_RESOURCE_ID_METADATA_KEY,
ExternalDataSchema,
ExternalDataSource,
auto_enable_new_schemas,
+ discovered_schema_finder,
sync_old_schemas_with_new_schemas,
)
from products.warehouse_sources.backend.facade.source_management import (
@@ -521,20 +521,11 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
# Not every source honors the `names` filter, so match by name instead of order. Sheets are
# discovered without that filter because a renamed worksheet is matched by its stable id.
- discovered_by_name = {discovered_schema.name: discovered_schema for discovered_schema in discovered}
- discovered_by_resource_id = {
- str(resource_id): discovered_schema
- for discovered_schema in discovered
- if (resource_id := (discovered_schema.schema_metadata or {}).get(SCHEMA_RESOURCE_ID_METADATA_KEY))
- is not None
- }
+ find_discovered_schema = discovered_schema_finder(discovered)
defaulted_schema_ids: set[str] = set()
for schema_update in needing_defaults:
schema = source_schemas_by_id[schema_update["id"]]
- stored_resource_id = (schema.schema_metadata or {}).get(SCHEMA_RESOURCE_ID_METADATA_KEY)
- discovered_schema = (
- discovered_by_resource_id.get(str(stored_resource_id)) if stored_resource_id is not None else None
- ) or discovered_by_name.get(schema.name)
+ discovered_schema = find_discovered_schema(schema.name, schema.schema_metadata)
if discovered_schema is None:
failures[str(schema.id)] = (
schema.name,
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
index a10942320c31..3af60874356b 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
@@ -50,7 +50,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
WebhookSyncResult,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source import GoogleSheetsSource
from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.source import RedshiftSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.source import SharePointSource
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSource
from products.warehouse_sources.backend.tests.api.utils import create_external_data_source_ok
@@ -500,9 +502,99 @@ class TestExternalDataSchema(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["xmin_available"] is expected_xmin_available
- def test_incremental_fields_matches_schema_by_name(self):
+ @parameterized.expand(
+ [
+ (
+ # Mimics sources (e.g. Slack) that ignore `names` and return every schema. The first
+ # element is an unrelated table; the endpoint must pick the one matching instance.name.
+ "name_match_when_names_filter_ignored",
+ StripeSource,
+ {"stripe_secret_key": "test_key"},
+ None,
+ False,
+ [["C123"]],
+ [
+ SourceSchema(name="$channels", supports_incremental=False, supports_append=False),
+ SourceSchema(
+ name="C123", supports_incremental=False, supports_append=False, supports_webhooks=True
+ ),
+ ],
+ ),
+ (
+ "resource_id_match_after_rename",
+ GoogleSheetsSource,
+ {"spreadsheet_url": "https://docs.google.com/spreadsheets/d/example/edit"},
+ {"schema_metadata": {"source_resource_id": "123"}},
+ True,
+ [["C123"], None],
+ [
+ SourceSchema(
+ name="other_sheet",
+ supports_incremental=False,
+ supports_append=False,
+ schema_metadata={"source_resource_id": "456"},
+ ),
+ SourceSchema(
+ name="new_title",
+ supports_incremental=False,
+ supports_append=False,
+ supports_webhooks=True,
+ schema_metadata={"source_resource_id": "123"},
+ ),
+ ],
+ ),
+ (
+ "name_filter_kept_when_name_still_matches_resource_id",
+ GoogleSheetsSource,
+ {"spreadsheet_url": "https://docs.google.com/spreadsheets/d/example/edit"},
+ {"schema_metadata": {"source_resource_id": "123"}},
+ True,
+ [["C123"]],
+ [
+ SourceSchema(
+ name="other_sheet",
+ supports_incremental=False,
+ supports_append=False,
+ schema_metadata={"source_resource_id": "456"},
+ ),
+ SourceSchema(
+ name="C123",
+ supports_incremental=False,
+ supports_append=False,
+ supports_webhooks=True,
+ schema_metadata={"source_resource_id": "123"},
+ ),
+ ],
+ ),
+ (
+ # A SharePoint endpoint table has no resource id, so discovery keeps the name filter
+ # and skips the file crawl.
+ "name_filter_kept_without_stored_resource_id",
+ SharePointSource,
+ {"tenant_id": "tenant", "client_id": "client", "client_secret": "secret"},
+ None,
+ True,
+ [["C123"]],
+ [
+ SourceSchema(
+ name="C123", supports_incremental=False, supports_append=False, supports_webhooks=True
+ ),
+ ],
+ ),
+ ]
+ )
+ def test_incremental_fields_matches_discovered_schema(
+ self,
+ _name,
+ source_class,
+ job_inputs,
+ sync_type_config,
+ honors_names_filter,
+ expected_names_per_call,
+ discovered_schemas,
+ ):
source = ExternalDataSource.objects.create(
- team=self.team, source_type=ExternalDataSourceType.STRIPE, job_inputs={"stripe_secret_key": "test_key"}
+ team=self.team, source_type=source_class().source_type, job_inputs=job_inputs
)
schema = ExternalDataSchema.objects.create(
name="C123",
@@ -511,25 +603,25 @@ class TestExternalDataSchema(APIBaseTest):
should_sync=True,
status=ExternalDataSchema.Status.COMPLETED,
sync_type=ExternalDataSchema.SyncType.WEBHOOK,
+ sync_type_config=sync_type_config or {},
)
- # Mimics sources (e.g. Slack) that ignore `names` and return every schema. The first
- # element is an unrelated table; the endpoint must pick the one matching instance.name.
- all_schemas = [
- SourceSchema(name="$channels", supports_incremental=False, supports_append=False, supports_webhooks=False),
- SourceSchema(name="C123", supports_incremental=False, supports_append=False, supports_webhooks=True),
- ]
+ def get_schemas(*args, names=None, **kwargs):
+ if names is None or not honors_names_filter:
+ return discovered_schemas
+ return [s for s in discovered_schemas if s.name in names]
with (
- mock.patch.object(StripeSource, "validate_credentials", return_value=(True, None)),
- mock.patch.object(StripeSource, "get_schemas", return_value=all_schemas),
+ mock.patch.object(source_class, "validate_credentials", return_value=(True, None)),
+ mock.patch.object(source_class, "get_schemas", side_effect=get_schemas) as mock_get_schemas,
):
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/incremental_fields",
)
- assert response.status_code == status.HTTP_200_OK
+ assert response.status_code == status.HTTP_200_OK, response.json()
assert response.json()["supports_webhooks"] is True
+ assert [call.kwargs["names"] for call in mock_get_schemas.call_args_list] == expected_names_per_call
@parameterized.expand(
[