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): fix schema admin reverse + non-billable CDC resync (#64962)

Daniel RCc0b6dca7466c
diff --git a/products/warehouse_sources/backend/admin/external_data_schema_admin.py b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
index a4ccba7a49e7..ab256520861b 100644
--- a/products/warehouse_sources/backend/admin/external_data_schema_admin.py
+++ b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
@@ -55,7 +55,7 @@ async def _is_schedule_paused(client: Client, schedule_id: str) -> bool:
def _change_url(schema_id) -> str:
- return reverse("admin:data_warehouse_externaldataschema_change", args=[schema_id])
+ return reverse("admin:warehouse_sources_externaldataschema_change", args=[schema_id])
@admin.register(ExternalDataSchema)
@@ -128,7 +128,7 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
schema = ExternalDataSchema.objects.select_related("source").get(id=schema_id)
except ExternalDataSchema.DoesNotExist:
messages.error(request, f"Schema {schema_id} not found.")
- return redirect(reverse("admin:data_warehouse_externaldataschema_changelist"))
+ return redirect(reverse("admin:warehouse_sources_externaldataschema_changelist"))
if schema.partition_mode is None:
messages.error(
@@ -272,7 +272,7 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
schema = ExternalDataSchema.objects.select_related("source").get(id=schema_id)
except ExternalDataSchema.DoesNotExist:
messages.error(request, f"Schema {schema_id} not found.")
- return redirect(reverse("admin:data_warehouse_externaldataschema_changelist"))
+ return redirect(reverse("admin:warehouse_sources_externaldataschema_changelist"))
# Both checkboxes default to off: an unchecked checkbox isn't sent in the
# POST body, so .get() returns None, and `None == "on"` is False.
@@ -299,15 +299,28 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
# marker. reset_pipeline goes on sync_type_config rather than the workflow
# input — the pipeline pops it after the first reset; on the input it
# would re-fire on every activity retry and wipe progress.
- sync_type_config_dirty = False
+ update_fields: list[str] = []
if reset_pipeline:
schema.sync_type_config["reset_pipeline"] = True
- sync_type_config_dirty = True
+ update_fields.append("sync_type_config")
+ # A streaming CDC schema no-ops a normal reset — CDCExtractionWorkflow owns it and the
+ # per-schema run raises CDCHandledExternally. Flip it back to snapshot so this run does a
+ # full re-snapshot, mirroring ExternalDataSchemaViewSet.reset. The job below is created
+ # billable=False, and on completion set_initial_sync_complete transitions it back to
+ # streaming, so ongoing CDC stays billable. The save must precede the workflow start so
+ # the source reloads cdc_mode="snapshot" instead of racing on stale "streaming".
+ if schema.is_cdc and schema.cdc_mode == "streaming":
+ schema.sync_type_config["cdc_mode"] = "snapshot"
+ schema.sync_type_config.pop("cdc_last_log_position", None)
+ schema.sync_type_config.pop("cdc_deferred_runs", None)
+ schema.initial_sync_complete = False
+ update_fields.append("initial_sync_complete")
if admin_paused_now:
schema.sync_type_config["admin_unpause_schedule_after_run"] = True
- sync_type_config_dirty = True
- if sync_type_config_dirty:
- schema.save(update_fields=["sync_type_config"])
+ if "sync_type_config" not in update_fields:
+ update_fields.append("sync_type_config")
+ if update_fields:
+ schema.save(update_fields=update_fields)
inputs = ExternalDataWorkflowInputs(
team_id=schema.team_id,
diff --git a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py
new file mode 100644
index 000000000000..a3468b7e6125
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py
@@ -0,0 +1,78 @@
+import uuid
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.contrib.admin import AdminSite
+from django.contrib.messages.storage.fallback import FallbackStorage
+from django.test import RequestFactory
+
+from products.warehouse_sources.backend.admin.external_data_schema_admin import ExternalDataSchemaAdmin
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+_ADMIN_MODULE = "products.warehouse_sources.backend.admin.external_data_schema_admin"
+
+
+class TestExternalDataSchemaAdmin(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.admin = ExternalDataSchemaAdmin(ExternalDataSchema, AdminSite())
+ self.factory = RequestFactory()
+
+ def _request(self, method: str, data: dict | None = None):
+ request = getattr(self.factory, method)("/", data=data or {})
+ request.session = {}
+ request._messages = FallbackStorage(request)
+ return request
+
+ def _schema(self, **kwargs) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+ return ExternalDataSchema.objects.create(team_id=self.team.pk, source=source, name="public.users", **kwargs)
+
+ def test_trigger_sync_get_redirects_to_change_page(self) -> None:
+ # Guards the admin-app-label reverse: resolving the change URL must not raise NoReverseMatch.
+ schema = self._schema()
+ response = self.admin.trigger_sync_view(self._request("get"), schema.id)
+ assert response.status_code == 302
+ assert str(schema.id) in response.url
+
+ def test_pause_schedule_redirects_to_change_page(self) -> None:
+ schema = self._schema()
+ with patch(f"{_ADMIN_MODULE}.pause_external_data_schedule"):
+ response = self.admin.pause_schedule_view(self._request("post"), schema.id)
+ assert response.status_code == 302
+ assert str(schema.id) in response.url
+
+ def test_reset_streaming_cdc_flips_to_snapshot_non_billable(self) -> None:
+ schema = self._schema(
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ sync_type_config={"cdc_mode": "streaming", "cdc_last_log_position": "0/ABC", "cdc_deferred_runs": [{}]},
+ initial_sync_complete=True,
+ )
+
+ with (
+ patch(f"{_ADMIN_MODULE}.sync_connect"),
+ patch(f"{_ADMIN_MODULE}._is_schedule_paused", return_value=True),
+ patch(f"{_ADMIN_MODULE}._start_external_data_workflow") as mock_start,
+ ):
+ response = self.admin.trigger_sync_view(self._request("post", {"reset_pipeline": "on"}), schema.id)
+
+ assert response.status_code == 302
+ schema.refresh_from_db()
+ assert schema.cdc_mode == "snapshot"
+ assert schema.initial_sync_complete is False
+ assert "cdc_last_log_position" not in schema.sync_type_config
+ assert "cdc_deferred_runs" not in schema.sync_type_config
+
+ # The re-snapshot must persist before the workflow starts (the source reloads cdc_mode), and
+ # the job must be non-billable so the initial full refresh isn't charged to the customer.
+ mock_start.assert_called_once()
+ inputs = mock_start.call_args.args[2]
+ assert inputs.billable is False