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): keep google sheets schemas across worksheet renames (#110688)

Tom Owers23108cc07621
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index 1b6a7bc14075..94a96f1d8c1d 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
CDC_SNAPSHOT_LANE_KEY,
MAX_FULL_REFRESH_INTERVAL_DAYS,
SCHEDULED_FULL_REFRESH_SYNC_TYPES,
+ SCHEMA_RESOURCE_ID_METADATA_KEY,
ExternalDataSchema,
auto_enable_new_schemas,
get_all_schemas_for_source_id,
@@ -96,6 +97,7 @@ __all__ = [
"MANAGED_WAREHOUSE_SOURCE_PREFIX",
"MAX_FULL_REFRESH_INTERVAL_DAYS",
"PendingSourceCredential",
+ "SCHEMA_RESOURCE_ID_METADATA_KEY",
"SCHEDULED_FULL_REFRESH_SYNC_TYPES",
"SERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING",
"WarehouseColumnAnnotation",
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index c526d2f0ba81..d6c3e4c02113 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1747,6 +1747,74 @@ def get_schemas_for_direct_reconciliation(
return DirectSchemaReconciliation(active_schemas=active, stale_schemas=stale)
+# A discovered schema can carry a stable identifier for its upstream resource under this key in its
+# `schema_metadata`. A source sets it when the resource keeps its identity through an upstream rename (a
+# Google Sheets worksheet keeps its sheet id when its title changes). Reconciliation then keeps the
+# stored schema, its table and its sync settings across the rename instead of disabling the schema and
+# offering the new name as a separate one.
+SCHEMA_RESOURCE_ID_METADATA_KEY = "source_resource_id"
+
+
+def _resource_id(metadata: object) -> str | None:
+ if isinstance(metadata, dict) and metadata.get(SCHEMA_RESOURCE_ID_METADATA_KEY) is not None:
+ return str(metadata[SCHEMA_RESOURCE_ID_METADATA_KEY])
+ return None
+
+
+def _renamed_schema_names(
+ old_schemas: list["ExternalDataSchema"],
+ new_schema_names: list[str],
+ schema_metadata_by_name: dict[str, dict],
+) -> dict[str, str]:
+ """Map each discovered name that is a renamed stored schema to that schema's stored name."""
+ stored_names = {schema.name for schema in old_schemas}
+ stored_name_by_resource_id: dict[str, str] = {}
+ for schema in old_schemas:
+ resource_id = _resource_id(schema.schema_metadata)
+ if resource_id is not None:
+ stored_name_by_resource_id[resource_id] = schema.name
+
+ renames: dict[str, str] = {}
+ for new_name in new_schema_names:
+ if new_name in stored_names:
+ continue
+ resource_id = _resource_id(schema_metadata_by_name.get(new_name))
+ stored_name = stored_name_by_resource_id.get(resource_id) if resource_id is not None else None
+ if stored_name is None:
+ continue
+ resource_at_stored_name = _resource_id(schema_metadata_by_name.get(stored_name))
+ if stored_name not in new_schema_names or resource_at_stored_name != resource_id:
+ renames[new_name] = stored_name
+ return renames
+
+
+def _apply_schema_renames[T](values: dict[str, T], renames: dict[str, str]) -> dict[str, T]:
+ rename_destinations = set(renames.values())
+ remapped = {
+ name: value for name, value in values.items() if name not in rename_destinations and name not in renames
+ }
+ remapped.update({renames[name]: values[name] for name in renames})
+ return remapped
+
+
+def _store_discovered_resource_ids(
+ old_schemas: list["ExternalDataSchema"], schema_metadata_by_name: dict[str, dict]
+) -> None:
+ for schema in old_schemas:
+ discovered_id = _resource_id(schema_metadata_by_name.get(schema.name))
+ if discovered_id is None or _resource_id(schema.schema_metadata) == discovered_id:
+ continue
+
+ def store_resource_id(config: dict[str, Any], discovered_id: str = discovered_id) -> None:
+ metadata = config.get("schema_metadata")
+ metadata = metadata if isinstance(metadata, dict) else {}
+ config["schema_metadata"] = {**metadata, SCHEMA_RESOURCE_ID_METADATA_KEY: discovered_id}
+
+ schema.sync_type_config = update_sync_type_config_keys(
+ schema_id=schema.id, team_id=schema.team_id, mutate=store_resource_id
+ )
+
+
def _update_labels(old_schemas: list["ExternalDataSchema"], new_schemas: dict[str, str | None]) -> None:
for schema in old_schemas:
new_label = new_schemas.get(schema.name)
@@ -1804,6 +1872,17 @@ def sync_old_schemas_with_new_schemas(
old_schemas = get_all_schemas_for_source_id(source_id=source_id, team_id=team_id)
old_schemas_names = [schema.name for schema in old_schemas]
+ if schema_metadata_by_name:
+ # Discovery reports a renamed resource under its new name. Name it as the stored schema from
+ # here on, so the matching below keeps that row and refreshes its label to the new name.
+ renames = _renamed_schema_names(old_schemas, list(new_schemas), schema_metadata_by_name)
+ if renames:
+ new_schemas = _apply_schema_renames(new_schemas, renames)
+ if descriptions:
+ descriptions = _apply_schema_renames(descriptions, renames)
+ schema_metadata_by_name = _apply_schema_renames(schema_metadata_by_name, renames)
+ _store_discovered_resource_ids(old_schemas, schema_metadata_by_name)
+
if descriptions:
for old_schema in old_schemas:
new_description = descriptions.get(old_schema.name)
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 9acfec288316..4db0da53c366 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,6 +21,7 @@ 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,
@@ -299,7 +300,7 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
strict_name_match=namespaced_adapter is not None and namespaced_adapter.uses_strict_schema_name_match,
schema_metadata_by_name=namespaced_adapter.schema_metadata_by_name(schemas)
if namespaced_adapter is not None
- else None,
+ else {name_substitutions.get(s.name, s.name): s.schema_metadata for s in schemas if s.schema_metadata},
)
# Mutable local: engine reconciliation below may extend the deleted set.
schemas_deleted = sync_result.deleted
@@ -500,7 +501,10 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
source_impl = base.SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
config = source_impl.parse_config(source.job_inputs)
discovered = source_impl.get_schemas(
- config, self.team_id, names=names, api_version=source_impl.resolve_api_version(source.api_version)
+ config,
+ self.team_id,
+ names=None if source_impl.uses_stable_schema_resource_ids else names,
+ api_version=source_impl.resolve_api_version(source.api_version),
)
except Exception as e:
# Discovery connects to the customer's source, so an expected user/upstream failure
@@ -515,12 +519,22 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
failures[str(schema.id)] = (schema.name, reason)
return failures, set()
- # Not every source honors the `names` filter, so match by name instead of order.
+ # 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
+ }
defaulted_schema_ids: set[str] = set()
for schema_update in needing_defaults:
schema = source_schemas_by_id[schema_update["id"]]
- discovered_schema = discovered_by_name.get(schema.name)
+ 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)
if discovered_schema is None:
failures[str(schema.id)] = (
schema.name,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index a7bac3630c63..b4fef33de81f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -172,6 +172,10 @@ class _BaseSource(ABC, Generic[ConfigType]):
# discovery but can never run a scheduled import.
supports_scheduled_sync: bool = True
+ # Sources with stable upstream resource ids need unfiltered discovery when a stored schema name
+ # may no longer match after an upstream rename.
+ uses_stable_schema_resource_ids: bool = False
+
# Vendor API versions this source implements, as opaque vendor labels (Stripe date
# versions, semver, names) — never parsed or ordered by the framework. Sources whose
# vendor has no meaningful API versioning keep the `UNVERSIONED_API_VERSION` default.
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.py
index 6fd25b1c1358..2a3e1fe9dd28 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
@@ -13,6 +13,8 @@ from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
from gspread.utils import numericise_all
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
@@ -286,8 +288,22 @@ def _get_worksheet(
return _retry_on_transient_api_error(execute)
+@frozen
+class DiscoveredWorksheet:
+ # The normalized title, which names the schema and its table.
+ name: str
+ # The title as the spreadsheet shows it.
+ title: str
+ # The sheet id (gid). It does not change when the worksheet is renamed.
+ worksheet_id: int
+
+
def get_schemas(config: GoogleSheetsSourceConfig) -> list[tuple[str, int]]:
"""Returns a tuple of worksheets in the form of (title, id)"""
+ return [(worksheet.name, worksheet.worksheet_id) for worksheet in get_worksheets(config)]
+
+
+def get_worksheets(config: GoogleSheetsSourceConfig) -> list[DiscoveredWorksheet]:
# `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
@@ -304,19 +320,39 @@ def get_schemas(config: GoogleSheetsSourceConfig) -> list[tuple[str, int]]:
worksheets = _retry_on_transient_api_error(execute)
- return [(NamingConvention.normalize_identifier(worksheet.title), worksheet.id) for worksheet in worksheets]
-
+ return [
+ DiscoveredWorksheet(
+ name=NamingConvention.normalize_identifier(worksheet.title),
+ title=worksheet.title,
+ worksheet_id=worksheet.id,
+ )
+ for worksheet in worksheets
+ ]
+
+
+def _resolve_worksheet_id(
+ config: GoogleSheetsSourceConfig, worksheet_name: str, worksheet_id: int | None, api_version: str
+) -> int:
+ # A renamed worksheet keeps its sheet id, so the stored id still finds it after the stored name
+ # stops matching any title. The name is the fallback for a schema stored before ids were, and for
+ # a worksheet that was deleted and then re-created under the same title.
+ if worksheet_id is not None:
+ try:
+ _get_worksheet(config.spreadsheet_url, worksheet_id, api_version)
+ return worksheet_id
+ except gspread.exceptions.WorksheetNotFound:
+ pass
-def get_schema_incremental_fields(
- config: GoogleSheetsSourceConfig, worksheet_name: str, api_version: str = GOOGLE_SHEETS_API_VERSION_V4
-) -> list[IncrementalField]:
- worksheets = get_schemas(config)
- selected_worksheet = [id for name, id in worksheets if name == worksheet_name]
+ selected_worksheet = [id for name, id in get_schemas(config) if name == worksheet_name]
if len(selected_worksheet) == 0:
raise Exception(f'Worksheet titled "{worksheet_name}" can\'t be found')
+ return selected_worksheet[0]
- worksheet_id = 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)
try:
@@ -355,14 +391,9 @@ def google_sheets_source(
db_incremental_field_last_value: Optional[Any],
api_version: str,
should_use_incremental_field: bool = False,
+ worksheet_id: int | None = None,
) -> SourceResponse:
- worksheets = get_schemas(config)
- selected_worksheet = [id for name, id in worksheets if name == worksheet_name]
- if len(selected_worksheet) == 0:
- raise Exception(f'Worksheet titled "{worksheet_name}" can\'t be found')
-
- worksheet_id = selected_worksheet[0]
-
+ worksheet_id = _resolve_worksheet_id(config, worksheet_name, worksheet_id, api_version)
worksheet = _get_worksheet(config.spreadsheet_url, worksheet_id, api_version)
try:
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.py
index 09d717cfd2fa..9e111514e27b 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
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldInputConfig,
SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.models.external_data_schema import SCHEMA_RESOURCE_ID_METADATA_KEY
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
UNVERSIONED_API_VERSION,
FieldType,
@@ -26,7 +27,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_schemas as get_google_sheets_schemas,
+ get_worksheets as get_google_sheets_worksheets,
google_sheets_client,
google_sheets_source,
)
@@ -36,6 +37,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):
api_docs_url = "https://developers.google.com/sheets/api"
+ uses_stable_schema_resource_ids = True
# "v1" is the framework's legacy UNVERSIONED default kept so pre-existing sources stay pinned
# and unchanged; "v4" names Google's current stable REST API version and is the default for new
@@ -114,22 +116,25 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):
# 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)
- sheets = get_google_sheets_schemas(config)
+ worksheets = get_google_sheets_worksheets(config)
if names is not None:
names_set = set(names)
- sheets = [(name, row_count) for name, row_count in sheets if name in names_set]
+ worksheets = [worksheet for worksheet in worksheets if worksheet.name in names_set]
schemas: list[SourceSchema] = []
- for name, _ in sheets:
- incremental_fields = get_google_sheets_schema_incremental_fields(config, name, resolved_version)
+ for worksheet in worksheets:
+ incremental_fields = get_google_sheets_schema_incremental_fields(config, worksheet.name, resolved_version)
schemas.append(
SourceSchema(
- name=name,
+ name=worksheet.name,
+ label=worksheet.title,
supports_incremental=len(incremental_fields) > 0,
supports_append=len(incremental_fields) > 0,
incremental_fields=incremental_fields,
+ # The sheet id survives a rename, so it keeps a renamed worksheet on its stored schema.
+ schema_metadata={SCHEMA_RESOURCE_ID_METADATA_KEY: str(worksheet.worksheet_id)},
)
)
@@ -144,6 +149,7 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):
if inputs.should_use_incremental_field
else None,
api_version=self.resolve_api_version(inputs.api_version),
+ worksheet_id=_stored_worksheet_id(inputs),
)
def validate_credentials(
@@ -244,3 +250,11 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):
),
featured=True,
)
+
+
+def _stored_worksheet_id(inputs: SourceInputs) -> int | None:
+ resource_id = (inputs.schema_metadata or {}).get(SCHEMA_RESOURCE_ID_METADATA_KEY)
+ try:
+ return int(resource_id) if resource_id is not None else None
+ except (TypeError, ValueError):
+ return None
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.py
index 4fced83a1e36..0db631077eef 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
@@ -8,6 +8,7 @@ import gspread
import requests
from google.auth import exceptions as google_auth_exceptions
+from products.warehouse_sources.backend.models.external_data_schema import SCHEMA_RESOURCE_ID_METADATA_KEY
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googlesheets import (
GoogleSheetsSourceConfig,
@@ -16,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_she
_PERMISSION_DENIED_MESSAGE,
_REQUEST_TIMEOUT_SECONDS,
GOOGLE_SHEETS_API_VERSION_V4,
+ DiscoveredWorksheet,
_assert_unique_normalized_column_names,
_get_worksheet,
_retry_on_transient_api_error,
@@ -930,8 +932,8 @@ def test_get_schemas_threads_resolved_pin_into_incremental_fields(pin, expected)
# source's resolved pin — otherwise a pinned source reads headers under a different key.
with (
mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.get_google_sheets_schemas",
- return_value=[("sheet1", 10)],
+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.get_google_sheets_worksheets",
+ return_value=[DiscoveredWorksheet(name="sheet1", title="Sheet1", worksheet_id=10)],
),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.get_google_sheets_schema_incremental_fields",
@@ -942,3 +944,64 @@ def test_get_schemas_threads_resolved_pin_into_incremental_fields(pin, expected)
GoogleSheetsSource().get_schemas(config, team_id=1, api_version=pin)
assert mock_incremental.call_args.args[-1] == expected
+
+
+ "stored_worksheet_id, worksheet_exists, expected_worksheet_id",
+ [
+ # The worksheet was renamed, so its stored name matches no title, but the stored id finds it.
+ (7, True, 7),
+ # The stored worksheet is gone, so a worksheet with the stored name is read instead.
+ (7, False, 123),
+ # A schema stored before ids were has only its name.
+ (None, True, 123),
+ ],
+ ids=["renamed_worksheet_found_by_id", "missing_id_falls_back_to_name", "no_stored_id_uses_name"],
+)
+def test_google_sheets_source_resolves_the_stored_worksheet_id_before_the_name(
+ stored_worksheet_id, worksheet_exists, expected_worksheet_id
+):
+ config = GoogleSheetsSourceConfig(spreadsheet_url="https://docs.google.com/spreadsheets/d/fake")
+ mock_worksheet = mock.MagicMock()
+ mock_worksheet.get_all_values.return_value = [["id"]]
+ mock_worksheet.get.return_value = [["id"], ["1"]]
+
+ def get_worksheet(_url, worksheet_id, _api_version):
+ if worksheet_id == 7 and not worksheet_exists:
+ raise gspread.exceptions.WorksheetNotFound("id 7 not found")
+ return mock_worksheet
+
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets"
+ with (
+ mock.patch(f"{module}.get_schemas", return_value=[("budget", 123)]),
+ mock.patch(f"{module}._get_worksheet", side_effect=get_worksheet) as mock_get_worksheet,
+ ):
+ response = google_sheets_source(
+ config,
+ "budget",
+ db_incremental_field_last_value=None,
+ api_version=GOOGLE_SHEETS_API_VERSION_V4,
+ worksheet_id=stored_worksheet_id,
+ )
+ list(cast(Iterable[Any], response.items()))
+
+ 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)
+
+ assert schema.name == "budget_2025"
+ assert schema.label == "Budget 2025"
+ assert schema.schema_metadata == {SCHEMA_RESOURCE_ID_METADATA_KEY: "7"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
index d48b8f44c729..14808247ae21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
@@ -189,9 +189,7 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:
source_id=inputs.source_id,
team_id=inputs.team_id,
strict_name_match=is_github,
- schema_metadata_by_name={s.name: s.schema_metadata for s in schemas if s.schema_metadata}
- if is_github
- else None,
+ schema_metadata_by_name={s.name: s.schema_metadata for s in schemas if s.schema_metadata},
)
if len(sync_result.created) > 0:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
index a3290e7f474b..cb30b576470c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
@@ -10,6 +10,7 @@ from posthog.models.integration import UndecryptedIntegrationSecretError
from posthog.temporal.common.errors import NonReportableError
from products.warehouse_sources.backend.models.external_data_schema import SchemaSyncResult
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import sync_new_schemas as module
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.sync_new_schemas import (
SyncNewSchemasActivityInputs,
@@ -239,6 +240,25 @@ def test_integration_secrets_failure_is_retried_and_reported_by_reportable(error
assert capture.called is expect_capture
+def test_discovery_passes_schema_metadata_for_non_github_sources():
+ source_mock = mock.MagicMock()
+ source_mock.parse_config.return_value = {}
+ source_mock.get_schemas.return_value = [
+ SourceSchema(
+ name="budget",
+ supports_incremental=False,
+ supports_append=False,
+ schema_metadata={"source_resource_id": "7"},
+ )
+ ]
+
+ mocks = _run_activity(source_mock)
+
+ assert mocks["sync_old_schemas_with_new_schemas"].call_args.kwargs["schema_metadata_by_name"] == {
+ "budget": {"source_resource_id": "7"}
+ }
+
+
def test_discovery_uses_source_pinned_api_version():
# A pinned source must discover schemas under its pin, not the default — dropping the pin
# here makes discovery reconcile under the wrong vendor version (tables vanish/duplicate).
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 883836f21378..32dad1813ffd 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -1683,6 +1683,53 @@ class TestExternalDataSource(APIBaseTest):
assert mock_sync_workflow.call_count == 1
assert mock_sync_workflow.call_args.kwargs == {"create": True, "should_sync": True}
+ @patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",
+ return_value=False,
+ )
+ def test_bulk_update_schemas_finds_renamed_google_sheet_by_resource_id(self, _mock_workflow_exists):
+ from products.warehouse_sources.backend.models.external_data_schema import SCHEMA_RESOURCE_ID_METADATA_KEY
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+
+ source = self._create_external_data_source()
+ source.source_type = "GoogleSheets"
+ source.job_inputs = {"spreadsheet_url": "https://docs.google.com/spreadsheets/d/fake"}
+ source.save(update_fields=["source_type", "job_inputs"])
+ schema = ExternalDataSchema.objects.create(
+ name="budget",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=False,
+ sync_type=None,
+ sync_type_config={"schema_metadata": {SCHEMA_RESOURCE_ID_METADATA_KEY: "7"}},
+ )
+ discovered = SourceSchema(
+ name="budget_2025",
+ supports_incremental=False,
+ supports_append=False,
+ schema_metadata={SCHEMA_RESOURCE_ID_METADATA_KEY: "7"},
+ )
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.source.GoogleSheetsSource.get_schemas",
+ return_value=[discovered],
+ ) as mock_get_schemas,
+ patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_schema.sync_external_data_job_workflow"
+ ),
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",
+ data={"schemas": [{"id": str(schema.id), "should_sync": True, "apply_sync_defaults": True}]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()[0]["should_sync"] is True
+ assert response.json()[0]["sync_type"] == "full_refresh"
+ assert mock_get_schemas.call_args.kwargs["names"] is None
+
@patch(
"products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",
return_value=False,
diff --git a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
index b075e1e31e02..dda0a8478442 100644
--- a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
+++ b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
@@ -8,6 +8,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from products.warehouse_sources.backend.models.external_data_schema import (
+ SCHEMA_RESOURCE_ID_METADATA_KEY,
ExternalDataSchema,
auto_enable_new_schemas,
schema_name_matches_auto_sync_patterns,
@@ -150,6 +151,69 @@ class TestSchemaDiscoveryReconcile(BaseTest):
assert unsynced_removed.deleted is True
mock_pause.assert_called_once_with(str(synced_removed.id))
+ def _with_resource_id(self, schema: ExternalDataSchema, resource_id: str) -> ExternalDataSchema:
+ schema.sync_type_config = {"schema_metadata": {SCHEMA_RESOURCE_ID_METADATA_KEY: resource_id}}
+ schema.save(update_fields=["sync_type_config"])
+ return schema
+
+ def test_renamed_resource_keeps_its_stored_schema(self) -> None:
+ source = self._make_source()
+ stored = self._with_resource_id(self._make_synced_schema(source, "budget"), "7")
+
+ sync_result = sync_old_schemas_with_new_schemas(
+ {"budget_2025": "Budget 2025"},
+ source_id=str(source.pk),
+ team_id=self.team.pk,
+ schema_metadata_by_name={"budget_2025": {SCHEMA_RESOURCE_ID_METADATA_KEY: "7"}},
+ )
+
+ stored.refresh_from_db()
+ assert stored.should_sync is True
+ assert stored.label == "Budget 2025"
+ assert sync_result.created == []
+ assert not ExternalDataSchema.objects.filter(source_id=source.pk, name="budget_2025").exists()
+
+ def test_a_new_resource_that_takes_the_old_name_does_not_replace_the_stored_resource(self) -> None:
+ # Stable identity wins when a new resource takes the old name. The colliding new resource
+ # cannot get a second row with that name, but it must not silently replace the synced one.
+ source = self._make_source()
+ stored = self._with_resource_id(self._make_synced_schema(source, "budget"), "7")
+
+ sync_result = sync_old_schemas_with_new_schemas(
+ {"budget": "Budget", "budget_2025": "Budget 2025"},
+ source_id=str(source.pk),
+ team_id=self.team.pk,
+ schema_metadata_by_name={
+ "budget": {SCHEMA_RESOURCE_ID_METADATA_KEY: "9"},
+ "budget_2025": {SCHEMA_RESOURCE_ID_METADATA_KEY: "7"},
+ },
+ )
+
+ stored.refresh_from_db()
+ assert stored.should_sync is True
+ assert stored.label == "Budget 2025"
+ assert stored.schema_metadata == {SCHEMA_RESOURCE_ID_METADATA_KEY: "7"}
+ assert sync_result.created == []
+
+ def test_a_schema_stored_without_a_resource_id_learns_it_and_keeps_other_metadata(self) -> None:
+ source = self._make_source()
+ stored = self._make_synced_schema(source, "budget")
+ stored.sync_type_config = {"schema_metadata": {"existing": "value"}, "incremental_field": "id"}
+ stored.save(update_fields=["sync_type_config"])
+
+ sync_old_schemas_with_new_schemas(
+ {"budget": "Budget"},
+ source_id=str(source.pk),
+ team_id=self.team.pk,
+ schema_metadata_by_name={"budget": {SCHEMA_RESOURCE_ID_METADATA_KEY: "7", "other": "ignored"}},
+ )
+
+ stored.refresh_from_db()
+ assert stored.sync_type_config == {
+ "schema_metadata": {"existing": "value", SCHEMA_RESOURCE_ID_METADATA_KEY: "7"},
+ "incremental_field": "id",
+ }
+
def test_dropped_user_enabled_schema_is_disabled_not_deleted_before_first_sync(self) -> None:
# A row the user enabled that never produced a table (every sync failed, then discovery
# stopped offering the endpoint, e.g. a scope-gated HubSpot table) must stay visible as