: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
feat(data-warehouse): add recreate schedule admin action for schemas (#69866)
Luke Beltonb88c3aa21e34
diff --git a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.htmlindex 7706d5d94c9f..3b59a01e5294 100644--- a/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html+++ b/posthog/templates/admin/data_warehouse/externaldataschema/change_form.html@@ -91,6 +91,9 @@<form id="unpause-schedule-action-form" method="post" action="{{ unpause_schedule_url }}" style="display:none;">{% csrf_token %}</form>+ <form id="recreate-schedule-action-form" method="post" action="{{ recreate_schedule_url }}" style="display:none;">+ {% csrf_token %}+ </form>{% endblock %}{# Suppress the default bottom submit_row — we render it inside `after_field_sets` #}@@ -325,6 +328,18 @@Unpause schedule</button></div>+ <p class="help">+ If the schedule is missing entirely (pause/unpause/sync fail with "workflow not found",+ typically after an interrupted source creation), recreate it below. This also works as a+ repair when the schedule exists: it is updated in place. No run is triggered; kick one+ off with "Trigger sync" below, which is non-billable by default.+ </p>+ <div class="partitioning-controls">+ <button type="submit" form="recreate-schedule-action-form" class="default"+ onclick="return confirm('Recreate the Temporal schedule for this schema? No sync run is triggered.');">+ Recreate schedule+ </button>+ </div></div><div class="form-row partitioning-section">diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.pyindex 22152164b93f..a98fabbfd887 100644--- a/products/data_warehouse/backend/logic/data_load/service.py+++ b/products/data_warehouse/backend/logic/data_load/service.py@@ -152,18 +152,30 @@ def to_temporal_schedule(def sync_external_data_job_workflow(- external_data_schema: ExternalDataSchema, create: bool = False, should_sync: bool = True+ external_data_schema: ExternalDataSchema,+ create: bool = False,+ should_sync: bool = True,+ trigger_immediately: bool = True,) -> ExternalDataSchema:+ """Create or update the schema's Temporal schedule.++ Runs fired through the schedule use its stored action, whose `billable` is always True,+ so callers that must not bill (e.g. admin recovery) pass trigger_immediately=False and+ start their own ad-hoc run if one is needed.+ """temporal = sync_connect()schedule = get_sync_schedule(external_data_schema, should_sync=should_sync)if create:try:- create_schedule(temporal, id=str(external_data_schema.id), schedule=schedule, trigger_immediately=True)+ create_schedule(+ temporal, id=str(external_data_schema.id), schedule=schedule, trigger_immediately=trigger_immediately+ )except ScheduleAlreadyRunningError:update_schedule(temporal, id=str(external_data_schema.id), schedule=schedule)- trigger_schedule(temporal, schedule_id=str(external_data_schema.id))+ if trigger_immediately:+ trigger_schedule(temporal, schedule_id=str(external_data_schema.id))else:update_schedule(temporal, id=str(external_data_schema.id), schedule=schedule)diff --git a/products/data_warehouse/backend/tests/test_data_load_service.py b/products/data_warehouse/backend/tests/test_data_load_service.pynew file mode 100644index 000000000000..a707a59fdd80--- /dev/null+++ b/products/data_warehouse/backend/tests/test_data_load_service.py@@ -0,0 +1,70 @@+import uuid++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized+from temporalio.client import ScheduleAlreadyRunningError++from products.data_warehouse.backend.logic.data_load.service import sync_external_data_job_workflow+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++_SERVICE_MODULE = "products.data_warehouse.backend.logic.data_load.service"+++class TestSyncExternalDataJobWorkflow(BaseTest):+ def _schema(self) -> 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", should_sync=True+ )++ @parameterized.expand(+ [+ ("fresh_create", False),+ ("schedule_already_exists", True),+ ]+ )+ def test_create_without_trigger_never_fires_a_run(self, _name: str, already_exists: bool) -> None:+ # trigger_immediately=False exists for admin recovery: runs fired through the schedule+ # use its stored action, which is always billable, so recreating a schedule must not+ # fire one in either the fresh-create or the already-exists fallback branch.+ schema = self._schema()++ with (+ patch(f"{_SERVICE_MODULE}.sync_connect"),+ patch(+ f"{_SERVICE_MODULE}.create_schedule",+ side_effect=ScheduleAlreadyRunningError if already_exists else None,+ ) as mock_create,+ patch(f"{_SERVICE_MODULE}.update_schedule") as mock_update,+ patch(f"{_SERVICE_MODULE}.trigger_schedule") as mock_trigger,+ ):+ sync_external_data_job_workflow(schema, create=True, trigger_immediately=False)++ assert mock_create.call_args.kwargs["trigger_immediately"] is False+ if already_exists:+ mock_update.assert_called_once()+ mock_trigger.assert_not_called()++ def test_create_triggers_immediately_by_default(self) -> None:+ # Every pre-existing create=True caller (enabling sync on a schema, the reload/resync+ # heal) relies on the created schedule firing its first run right away.+ schema = self._schema()++ with (+ patch(f"{_SERVICE_MODULE}.sync_connect"),+ patch(f"{_SERVICE_MODULE}.create_schedule") as mock_create,+ patch(f"{_SERVICE_MODULE}.trigger_schedule") as mock_trigger,+ ):+ sync_external_data_job_workflow(schema, create=True)++ assert mock_create.call_args.kwargs["trigger_immediately"] is True+ mock_trigger.assert_not_called()diff --git a/products/warehouse_sources/backend/admin/external_data_schema_admin.py b/products/warehouse_sources/backend/admin/external_data_schema_admin.pyindex 73233d186a3b..c62569a1e115 100644--- a/products/warehouse_sources/backend/admin/external_data_schema_admin.py+++ b/products/warehouse_sources/backend/admin/external_data_schema_admin.py@@ -16,7 +16,11 @@ from temporalio.common import WorkflowIDReusePolicyfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.utils import ExternalDataWorkflowInputs-from products.data_warehouse.backend.facade.api import pause_external_data_schedule, unpause_external_data_schedule+from products.data_warehouse.backend.facade.api import (+ pause_external_data_schedule,+ sync_external_data_job_workflow,+ unpause_external_data_schedule,+)from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (@@ -148,6 +152,11 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):self.admin_site.admin_view(self.unpause_schedule_view),name="external_data_schema_unpause_schedule",),+ path(+ "<uuid:schema_id>/recreate-schedule/",+ self.admin_site.admin_view(self.recreate_schedule_view),+ name="external_data_schema_recreate_schedule",+ ),]return custom_urls + urls@@ -494,6 +503,54 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):messages.error(request, f"Failed to unpause schedule: {e}")return redirect(_change_url(schema_id))+ def recreate_schedule_view(self, request, schema_id):+ # Recovery for schemas whose per-schema Temporal schedule is missing (e.g. the source+ # creation request was killed between committing the rows and creating the schedules,+ # or the schema was resurrected after a soft-delete). Safe on an existing schedule too:+ # sync_external_data_job_workflow falls back to updating it in place. Deliberately does+ # NOT trigger a run: the schedule's stored action is always billable, so operators kick+ # off an immediate run with the (non-billable by default) "Trigger sync" action instead.+ if request.method != "POST":+ return redirect(_change_url(schema_id))++ # Resolve through the admin's scoped object path (get_queryset) rather than a bare+ # manager .get(), so any queryset scoping applies to this action exactly as it does+ # to the change form.+ schema = self.get_object(request, str(schema_id))+ if schema is None:+ messages.error(request, f"Schema {schema_id} not found.")+ return redirect(reverse("admin:warehouse_sources_externaldataschema_changelist"))++ if not self.has_change_permission(request, schema):+ raise PermissionDenied++ if not schema.source.supports_scheduled_sync:+ messages.error(+ request,+ "This source is queried directly and does not use per-schema sync schedules.",+ )+ return redirect(_change_url(schema_id))++ try:+ sync_external_data_job_workflow(+ schema, create=True, should_sync=schema.should_sync, trigger_immediately=False+ )+ except Exception as e:+ messages.error(request, f"Failed to recreate schedule: {e}")+ return redirect(_change_url(schema_id))++ paused_note = (+ " The schedule was created paused because sync is disabled for this schema."+ if not schema.should_sync+ else ""+ )+ messages.success(+ request,+ f"Recreated Temporal schedule for {schema.name}. No run was triggered; "+ f'use "Trigger sync" for an immediate non-billable run.{paused_note}',+ )+ return redirect(_change_url(schema_id))+def change_view(self, request, object_id, form_url="", extra_context=None):extra_context = extra_context or {}obj = self.get_object(request, object_id)@@ -536,6 +593,9 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):extra_context["unpause_schedule_url"] = reverse("admin:external_data_schema_unpause_schedule", args=[obj.id])+ extra_context["recreate_schedule_url"] = reverse(+ "admin:external_data_schema_recreate_schedule", args=[obj.id]+ )# CDC schemas stream via a source-level extraction schedule; the per-schema schedule# above is paused once streaming starts, so surface the real one too.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.pyindex 906ac983775b..e7937c0024a9 100644--- a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py+++ b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py@@ -281,3 +281,73 @@ class TestExternalDataSchemaAdmin(BaseTest):schema.refresh_from_db()assert "partition_mode_override" not in schema.sync_type_configmock_start.assert_not_called()++ @parameterized.expand([(True,), (False,)])+ def test_recreate_schedule_passes_should_sync_through(self, should_sync: bool) -> None:+ # Guards the recovery action for schemas left without a Temporal schedule: it must+ # recreate with the schema's own should_sync so a disabled schema comes back paused+ # instead of silently starting recurring syncs, and it must not trigger a run (runs+ # fired through the schedule are always billable; operators use "Trigger sync" for a+ # non-billable one).+ schema = self._schema(should_sync=should_sync)++ with patch(f"{_ADMIN_MODULE}.sync_external_data_job_workflow") as mock_sync:+ response = self.admin.recreate_schedule_view(self._request("post"), schema.id)++ assert response.status_code == 302+ assert str(schema.id) in response.url+ mock_sync.assert_called_once_with(schema, create=True, should_sync=should_sync, trigger_immediately=False)++ def test_recreate_schedule_get_does_not_recreate(self) -> None:+ schema = self._schema()++ with patch(f"{_ADMIN_MODULE}.sync_external_data_job_workflow") as mock_sync:+ response = self.admin.recreate_schedule_view(self._request("get"), schema.id)++ assert response.status_code == 302+ mock_sync.assert_not_called()++ def test_recreate_schedule_denies_without_change_permission(self) -> None:+ schema = self._schema()++ with (+ patch(f"{_ADMIN_MODULE}.sync_external_data_job_workflow") as mock_sync,+ patch.object(self.admin, "has_change_permission", return_value=False),+ ):+ with self.assertRaises(PermissionDenied):+ self.admin.recreate_schedule_view(self._request("post"), schema.id)++ mock_sync.assert_not_called()++ def test_recreate_schedule_rejects_direct_query_source(self) -> None:+ # Direct-query sources have no per-schema schedules by design; recreating one would+ # start scheduled syncs on a source that is only ever queried live.+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ status="Completed",+ source_type="Postgres",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ )+ schema = ExternalDataSchema.objects.create(team_id=self.team.pk, source=source, name="public.users")++ with patch(f"{_ADMIN_MODULE}.sync_external_data_job_workflow") as mock_sync:+ response = self.admin.recreate_schedule_view(self._request("post"), schema.id)++ assert response.status_code == 302+ assert str(schema.id) in response.url+ mock_sync.assert_not_called()++ def test_recreate_schedule_temporal_failure_flashes_error(self) -> None:+ # A Temporal outage must surface as an admin flash message, not a 500.+ schema = self._schema()++ with patch(+ f"{_ADMIN_MODULE}.sync_external_data_job_workflow",+ side_effect=Exception("connect failed"),+ ):+ response = self.admin.recreate_schedule_view(self._request("post"), schema.id)++ assert response.status_code == 302+ assert str(schema.id) in response.url