: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(warehouse-sources): pause schedules of tables discovery turns off (#106956)
Daniel RCc908bb9b218e
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex f12abc553d15..71df010b1786 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -7,6 +7,7 @@ from contextlib import contextmanagerfrom contextvars import ContextVarfrom dataclasses import dataclassfrom datetime import UTC, date, datetime, timedelta+from functools import partialfrom typing import TYPE_CHECKING, Any, Literal, Optionalfrom django.conf import settings@@ -1748,6 +1749,38 @@ class SchemaSyncResult:deleted: list[str]+def _pause_schedule_then_disable_schema(schema: "ExternalDataSchema") -> None:+ """Pause a discovery-removed table's schedule, and only then persist the table as off.++ The sync workflow does not read `should_sync`, so the schedule is what actually stops the+ billable runs. Writing the row off first would strand the table whenever the pause fails: the+ schedule keeps starting runs, and the next discovery run sees a row that is already off, so it+ never retries the pause. Keeping the row on until the pause lands makes a failed pause+ self-healing, because the table is still on and still unlisted when discovery next runs.++ Nothing here raises: Django drops the remaining `on_commit` callbacks once one of them raises,+ so an error would also strand every other table removed in the same commit, and on the API+ paths it would fail a request whose reconcile already committed. A pause that lands without its+ write (or without its teardown dispatch) heals the same way, on the next discovery run. The+ write is scoped to its own columns because the row was read before the commit, so a full save+ would push back whatever a concurrent writer changed in the meantime.+ """+ # Call-time import for the reason given in update_should_sync above.+ from products.data_warehouse.backend.facade.api import pause_external_data_schedule # noqa: PLC0415++ try:+ pause_external_data_schedule(str(schema.id))+ schema.should_sync = False+ schema.status = ExternalDataSchema.Status.COMPLETED+ schema.save(update_fields=["should_sync", "status", "updated_at"])+ except Exception:+ logger.exception(+ "discovery_removed_schema_disable_failed",+ external_data_schema_id=str(schema.id),+ team_id=schema.team_id,+ )++def sync_old_schemas_with_new_schemas(new_schemas: dict[str, str | None],source_id: str,@@ -1846,8 +1879,12 @@ def sync_old_schemas_with_new_schemas(if s.table_id is None and not s.should_sync:s.soft_delete()deleted_schemas.append(schema)+ elif s.should_sync:+ # After the commit because callers can hold the source row lock, and the Temporal+ # call must not run inside it. A row already off needs no pause, and pausing it+ # again every run would open a Temporal connection per table per run.+ transaction.on_commit(partial(_pause_schedule_then_disable_schema, s))else:- s.should_sync = Falses.status = ExternalDataSchema.Status.COMPLETEDs.save()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.pyindex 44ad78525512..0d58848e7bde 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@@ -14361,15 +14361,20 @@ class TestGithubMultiRepoPatch(APIBaseTest):},)- response = self.client.patch(- f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",- data={- "job_inputs": {- "auth_method": {"selection": "pat"},- "repositories": ["org/repo", "new/repo"],- }- },- )+ # Retiring a removed repo's rows finishes after the commit, so run the callbacks.+ with (+ patch("products.data_warehouse.backend.facade.api.pause_external_data_schedule"),+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "auth_method": {"selection": "pat"},+ "repositories": ["org/repo", "new/repo"],+ }+ },+ )assert response.status_code == 200, response.json()# New repo's hooks are pinned to the source's existing secret; removed repo's hook deleted.diff --git a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.pyindex 326f99c98b15..b075e1e31e02 100644--- a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py+++ b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py@@ -18,6 +18,8 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+_PAUSE_FN = "products.data_warehouse.backend.facade.api.pause_external_data_schedule"+# Managed/scheduled discovery calls sync_old_schemas_with_new_schemas with no rename step, so a# qualified/bare name mismatch against the stored row used to flip the live row to should_sync=False.@@ -131,12 +133,13 @@ class TestSchemaDiscoveryReconcile(BaseTest):team_id=self.team.pk, source_id=source.pk, name="acme/other.commits", should_sync=False)- sync_old_schemas_with_new_schemas(- {"issues": None},- source_id=str(source.pk),- team_id=self.team.pk,- strict_name_match=True,- )+ with patch(_PAUSE_FN) as mock_pause, self.captureOnCommitCallbacks(execute=True):+ sync_old_schemas_with_new_schemas(+ {"issues": None},+ source_id=str(source.pk),+ team_id=self.team.pk,+ strict_name_match=True,+ )legacy.refresh_from_db()synced_removed.refresh_from_db()@@ -145,6 +148,7 @@ class TestSchemaDiscoveryReconcile(BaseTest):assert synced_removed.should_sync is Falseassert synced_removed.deleted is Falseassert unsynced_removed.deleted is True+ mock_pause.assert_called_once_with(str(synced_removed.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@@ -155,17 +159,43 @@ class TestSchemaDiscoveryReconcile(BaseTest):team_id=self.team.pk, source_id=source.pk, name="leads", should_sync=True)- sync_result = sync_old_schemas_with_new_schemas(- {"contacts": None},- source_id=str(source.pk),- team_id=self.team.pk,- )+ with patch(_PAUSE_FN) as mock_pause, self.captureOnCommitCallbacks(execute=True):+ sync_result = sync_old_schemas_with_new_schemas(+ {"contacts": None},+ source_id=str(source.pk),+ team_id=self.team.pk,+ )enabled_unsynced.refresh_from_db()assert sync_result.deleted == []assert enabled_unsynced.deleted is Falseassert enabled_unsynced.should_sync is Falseassert enabled_unsynced.status == ExternalDataSchema.Status.COMPLETED+ mock_pause.assert_called_once_with(str(enabled_unsynced.id))++ def test_failed_pause_leaves_the_table_on_and_still_pauses_the_others(self) -> None:+ # A row written off while its schedule still runs keeps billing, and the next discovery run+ # would skip it as already off, so a failed pause has to leave the row on for that retry.+ source = self._make_source()+ unreachable = self._make_synced_schema(source, "leads")+ other_removed = self._make_synced_schema(source, "deals")++ def pause(schema_id: str) -> None:+ if schema_id == str(unreachable.id):+ raise Exception("temporal unavailable")++ with patch(_PAUSE_FN, side_effect=pause) as mock_pause, self.captureOnCommitCallbacks(execute=True):+ sync_old_schemas_with_new_schemas(+ {"contacts": None},+ source_id=str(source.pk),+ team_id=self.team.pk,+ )++ unreachable.refresh_from_db()+ other_removed.refresh_from_db()+ assert {call.args[0] for call in mock_pause.call_args_list} == {str(unreachable.id), str(other_removed.id)}+ assert unreachable.should_sync is True+ assert other_removed.should_sync is Falseclass TestSchemaNameMatchesAutoSyncPatterns(SimpleTestCase):