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.

feat(warehouse): add a bulk non-billable resync management command (#94153)

Daniel RC1aae880b7a95
diff --git a/products/warehouse_sources/backend/ad_hoc_sync.py b/products/warehouse_sources/backend/ad_hoc_sync.py
new file mode 100644
index 000000000000..d966643590d2
--- /dev/null
+++ b/products/warehouse_sources/backend/ad_hoc_sync.py
@@ -0,0 +1,153 @@
+"""Start a single external-data-job run outside the schema's Temporal schedule.
+
+The schedule's stored input is always billable, so a run that must not be charged, or that must
+stage a reset first, cannot go through it. Operators reach this from Django admin's "Trigger sync"; a bulk cleanup
+reaches it from the `resync_schemas_non_billable` management command. Those two share the sequence
+here so they cannot drift.
+
+The partition-tuning admin actions still hold their own copy in `_pause_save_and_resync`. They stage
+arbitrary partition keys and skip the CDC re-snapshot, so folding them in would change their
+behavior rather than just their shape.
+"""
+
+import time
+
+from django.conf import settings
+
+from asgiref.sync import async_to_sync
+from temporalio.client import Client
+from temporalio.common import WorkflowIDReusePolicy
+
+from posthog.dataclasses import frozen
+from posthog.temporal.utils import ExternalDataWorkflowInputs
+
+from products.data_warehouse.backend.facade.api import pause_external_data_schedule, unpause_external_data_schedule
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+
+@frozen
+class AdHocSyncTrigger:
+ workflow_id: str
+ # True only when this call paused the schedule, so the caller can say whether it will auto-unpause.
+ schedule_paused_now: bool
+
+
+class SchedulePauseError(Exception):
+ """Pausing the schedule failed, so no run was started and nothing was staged."""
+
+
+class WorkflowStartError(Exception):
+ """The workflow failed to start. Any pause taken by this call has been rolled back."""
+
+
+@async_to_sync
+async def start_external_data_workflow(client: Client, workflow_id: str, inputs: ExternalDataWorkflowInputs) -> None:
+ await client.start_workflow(
+ "external-data-job",
+ inputs,
+ id=workflow_id,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
+ task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,
+ )
+
+
+@async_to_sync
+async def is_schedule_paused(client: Client, schedule_id: str) -> bool:
+ """Best-effort check whether the per-schema Temporal schedule is currently paused.
+
+ Returns False if the schedule does not exist or describe fails — the caller
+ treats that as 'no schedule to pause' and proceeds without pausing.
+ """
+ handle = client.get_schedule_handle(schedule_id)
+ try:
+ desc = await handle.describe()
+ except Exception:
+ return False
+ return bool(desc.schedule.state.paused)
+
+
+def trigger_ad_hoc_sync(
+ client: Client,
+ schema: ExternalDataSchema,
+ *,
+ billable: bool,
+ reset_pipeline: bool,
+ workflow_id_prefix: str,
+) -> AdHocSyncTrigger:
+ """Pause the schedule, stage the reset when asked, and start one run.
+
+ Pausing comes first because Temporal's "OnlyOne" overlap policy is per-schedule, not across a
+ schedule plus an ad-hoc workflow, so without it the scheduled run can race this one. A schedule
+ the caller already paused by hand is left alone, so this does not undo their action.
+ """
+ was_paused = is_schedule_paused(client, str(schema.id))
+ paused_now = False
+ if not was_paused:
+ try:
+ pause_external_data_schedule(str(schema.id))
+ paused_now = True
+ except Exception as e:
+ raise SchedulePauseError(str(e)) from e
+
+ # Single save: the reset, the CDC re-snapshot, and the auto-unpause marker in one round-trip.
+ # reset_pipeline goes on sync_type_config rather than the workflow input because the pipeline
+ # pops it after the first reset; on the input every activity retry would re-read True and wipe
+ # Delta plus the cursor, restarting from row 0.
+ config_before = dict(schema.sync_type_config)
+ initial_sync_complete_before = schema.initial_sync_complete
+
+ update_fields: list[str] = []
+ if reset_pipeline:
+ schema.sync_type_config["reset_pipeline"] = 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. The job is created non-billable when the caller asks for that, 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 paused_now:
+ schema.sync_type_config["admin_unpause_schedule_after_run"] = True
+ 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,
+ external_data_source_id=schema.source.id,
+ external_data_schema_id=schema.id,
+ billable=billable,
+ reset_pipeline=None,
+ )
+ workflow_id = f"{schema.id}-{workflow_id_prefix}-{int(time.time())}"
+ try:
+ start_external_data_workflow(client, workflow_id, inputs)
+ except Exception as e:
+ # Two things have to come undone here, or a run that never started still changes behavior.
+ # The unpause marker is only read by a workflow that never began, so the schedule would stay
+ # paused forever. And the staged reset would be consumed by the next *scheduled* run, which
+ # would wipe the Delta table, or re-snapshot a CDC schema whose log position staging already
+ # deleted. Restoring the whole prior config covers the deleted keys, which a key-by-key undo
+ # cannot.
+ if paused_now:
+ try:
+ unpause_external_data_schedule(str(schema.id))
+ except Exception:
+ pass
+ if update_fields:
+ schema.sync_type_config = config_before
+ schema.initial_sync_complete = initial_sync_complete_before
+ try:
+ schema.save(update_fields=["sync_type_config", "initial_sync_complete"])
+ except Exception:
+ pass
+ raise WorkflowStartError(str(e)) from e
+
+ return AdHocSyncTrigger(workflow_id=workflow_id, schedule_paused_now=paused_now)
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 ac25fdb190d7..a518b55f889e 100644
--- a/products/warehouse_sources/backend/admin/external_data_schema_admin.py
+++ b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
@@ -9,10 +9,6 @@ from django.shortcuts import redirect
from django.urls import path, reverse
from django.utils.html import format_html
-from asgiref.sync import async_to_sync
-from temporalio.client import Client
-from temporalio.common import WorkflowIDReusePolicy
-
from posthog.temporal.common.client import sync_connect
from posthog.temporal.utils import ExternalDataWorkflowInputs
@@ -21,6 +17,13 @@ from products.data_warehouse.backend.facade.api import (
sync_external_data_job_workflow,
unpause_external_data_schedule,
)
+from products.warehouse_sources.backend.ad_hoc_sync import (
+ SchedulePauseError,
+ WorkflowStartError,
+ is_schedule_paused as _is_schedule_paused,
+ start_external_data_workflow as _start_external_data_workflow,
+ trigger_ad_hoc_sync,
+)
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
@@ -34,32 +37,6 @@ PARTITION_FORMAT_CHOICES: tuple[str, ...] = get_args(PartitionFormat)
PARTITION_MODE_CHOICES: tuple[str, ...] = get_args(PartitionMode)
-@async_to_sync
-async def _start_external_data_workflow(client: Client, workflow_id: str, inputs: ExternalDataWorkflowInputs) -> None:
- await client.start_workflow(
- "external-data-job",
- inputs,
- id=workflow_id,
- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
- task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,
- )
-
-
-@async_to_sync
-async def _is_schedule_paused(client: Client, schedule_id: str) -> bool:
- """Best-effort check whether the per-schema Temporal schedule is currently paused.
-
- Returns False if the schedule does not exist or describe fails — the caller
- treats that as 'no schedule to pause' and proceeds without pausing.
- """
- handle = client.get_schedule_handle(schedule_id)
- try:
- desc = await handle.describe()
- except Exception:
- return False
- return bool(desc.schedule.state.paused)
-
-
def _change_url(schema_id) -> str:
return reverse("admin:warehouse_sources_externaldataschema_change", args=[schema_id])
@@ -410,66 +387,23 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
messages.error(request, f"Failed to connect to Temporal: {e}.")
return redirect(_change_url(schema_id))
- was_paused = _is_schedule_paused(client, str(schema.id))
- admin_paused_now = False
- if not was_paused:
- try:
- pause_external_data_schedule(str(schema.id))
- admin_paused_now = True
- except Exception as e:
- messages.error(request, f"Failed to pause schedule before sync: {e}.")
- return redirect(_change_url(schema_id))
-
- # Single save: stage reset_pipeline (only when ticked) + the auto-unpause
- # 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.
- update_fields: list[str] = []
- if reset_pipeline:
- schema.sync_type_config["reset_pipeline"] = 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
- 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,
- external_data_source_id=schema.source.id,
- external_data_schema_id=schema.id,
- billable=billable,
- reset_pipeline=None,
- )
- workflow_id = f"{schema.id}-admin-resync-{int(time.time())}"
try:
- _start_external_data_workflow(client, workflow_id, inputs)
- except Exception as e:
- # Best-effort rollback of the pause we just did so the schedule doesn't
- # stay paused forever after a failed workflow start.
- if admin_paused_now:
- try:
- unpause_external_data_schedule(str(schema.id))
- schema.sync_type_config.pop("admin_unpause_schedule_after_run", None)
- schema.save(update_fields=["sync_type_config"])
- except Exception:
- pass
+ trigger = trigger_ad_hoc_sync(
+ client,
+ schema,
+ billable=billable,
+ reset_pipeline=reset_pipeline,
+ workflow_id_prefix="admin-resync",
+ )
+ except SchedulePauseError as e:
+ messages.error(request, f"Failed to pause schedule before sync: {e}.")
+ return redirect(_change_url(schema_id))
+ except WorkflowStartError as e:
messages.error(request, f"Failed to trigger sync: {e}")
return redirect(_change_url(schema_id))
+ workflow_id = trigger.workflow_id
+ admin_paused_now = trigger.schedule_paused_now
billable_label = "billable" if billable else "non-billable"
action_label = "resync (with reset)" if reset_pipeline else "sync"
pause_note = (
diff --git a/products/warehouse_sources/backend/management/commands/resync_schemas_non_billable.py b/products/warehouse_sources/backend/management/commands/resync_schemas_non_billable.py
new file mode 100644
index 000000000000..ffcb43584a7b
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/resync_schemas_non_billable.py
@@ -0,0 +1,172 @@
+import time
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+import structlog
+from temporalio.client import Client
+
+from posthog.temporal.common.client import sync_connect
+
+from products.warehouse_sources.backend.ad_hoc_sync import SchedulePauseError, WorkflowStartError, trigger_ad_hoc_sync
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+logger = structlog.get_logger(__name__)
+
+
+def _read_ids(raw: str | None, path: str | None) -> list[str]:
+ ids: list[str] = []
+ if raw:
+ ids.extend(part.strip() for part in raw.split(",") if part.strip())
+ if path:
+ with open(path) as handle:
+ for line in handle:
+ line = line.split("#", 1)[0].strip()
+ if line:
+ ids.append(line)
+ # Preserve caller order so an operator can stage small tables first, and drop repeats.
+ seen: set[str] = set()
+ unique: list[str] = []
+ for schema_id in ids:
+ if schema_id not in seen:
+ seen.add(schema_id)
+ unique.append(schema_id)
+ return unique
+
+
+class Command(BaseCommand):
+ help = (
+ "Trigger a non-billable sync for many schemas at once, mirroring the admin 'Trigger sync' action. "
+ "A full_refresh run replaces its table wholesale, so plain (no --reset) is enough to replace bad data. "
+ "Use --reset for incremental or xmin schemas, which otherwise only read forward from their cursor."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument(
+ "--schema-ids",
+ type=str,
+ default=None,
+ help="Comma-separated schema ids.",
+ )
+ parser.add_argument(
+ "--schema-ids-file",
+ type=str,
+ default=None,
+ help="File with one schema id per line. Blank lines and '#' comments are ignored.",
+ )
+ parser.add_argument(
+ "--reset",
+ action="store_true",
+ help=(
+ "Stage reset_pipeline, which wipes the Delta table and cursor before re-reading. "
+ "Needed for incremental and xmin schemas. Note a failed run then leaves the table empty."
+ ),
+ )
+ parser.add_argument(
+ "--sleep-seconds",
+ type=float,
+ default=30.0,
+ help="Pause between triggers so a batch does not stampede the workers or the source. Default 30.",
+ )
+ parser.add_argument(
+ "--limit",
+ type=int,
+ default=None,
+ help="Only act on the first N schemas, for a cautious first batch.",
+ )
+ parser.add_argument(
+ "--live-run",
+ action="store_true",
+ help="Actually trigger the syncs. Without this the command only lists what it would do.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ schema_ids = _read_ids(options["schema_ids"], options["schema_ids_file"])
+ if not schema_ids:
+ raise CommandError("Pass --schema-ids or --schema-ids-file.")
+
+ reset = options["reset"]
+ live_run = options["live_run"]
+ sleep_seconds = options["sleep_seconds"]
+
+ # Validate before anything is triggered. A negative limit silently drops the *last* schemas
+ # via slice semantics, and a negative sleep raises partway through, leaving a live batch
+ # half-run with no summary.
+ if sleep_seconds < 0:
+ raise CommandError("--sleep-seconds cannot be negative.")
+ if options["limit"] is not None and options["limit"] < 1:
+ raise CommandError("--limit must be at least 1.")
+
+ by_id = {
+ str(schema.id): schema
+ for schema in ExternalDataSchema.objects.select_related("source").filter(id__in=schema_ids)
+ }
+ missing = [schema_id for schema_id in schema_ids if schema_id not in by_id]
+ if missing:
+ self.stdout.write(self.style.WARNING(f"Not found, skipping {len(missing)}: {', '.join(missing)}"))
+
+ schemas = [by_id[schema_id] for schema_id in schema_ids if schema_id in by_id]
+ if options["limit"] is not None:
+ schemas = schemas[: options["limit"]]
+
+ if not schemas:
+ raise CommandError("No matching schemas.")
+
+ mode = "reset resync (re-pulls from source, wipes table first)" if reset else "sync (no reset)"
+ self.stdout.write(f"{len(schemas)} schema(s), non-billable {mode}:\n")
+ for schema in schemas:
+ self.stdout.write(
+ f" schema={schema.id} team={schema.team_id} name={schema.name} "
+ f"sync_type={schema.sync_type} source_type={schema.source.source_type} "
+ f"should_sync={schema.should_sync}"
+ )
+
+ if not live_run:
+ self.stdout.write(
+ self.style.WARNING(f"\nDry run. Pass --live-run to trigger {len(schemas)} non-billable run(s).")
+ )
+ return
+
+ try:
+ client = sync_connect()
+ except Exception as e:
+ raise CommandError(f"Failed to connect to Temporal: {e}")
+
+ succeeded = 0
+ failed = 0
+
+ for index, schema in enumerate(schemas):
+ if index and sleep_seconds:
+ time.sleep(sleep_seconds)
+ if self._trigger(client, schema, reset=reset):
+ succeeded += 1
+ else:
+ failed += 1
+
+ self.stdout.write(self.style.SUCCESS(f"\nDone. Triggered: {succeeded}, Failed: {failed}"))
+
+ def _trigger(self, client: Client, schema: ExternalDataSchema, *, reset: bool) -> bool:
+ try:
+ trigger = trigger_ad_hoc_sync(
+ client,
+ schema,
+ billable=False,
+ reset_pipeline=reset,
+ workflow_id_prefix="bulk-resync",
+ )
+ except SchedulePauseError:
+ logger.exception("Failed to pause schedule, skipping", schema_id=str(schema.id))
+ return False
+ except WorkflowStartError:
+ logger.exception("Failed to trigger sync", schema_id=str(schema.id), team_id=schema.team_id)
+ return False
+
+ self.stdout.write(f" triggered {schema.id} workflow_id={trigger.workflow_id}")
+ logger.info(
+ "Triggered non-billable sync",
+ schema_id=str(schema.id),
+ team_id=schema.team_id,
+ workflow_id=trigger.workflow_id,
+ reset=reset,
+ )
+ return True
diff --git a/products/warehouse_sources/backend/tests/management/test_resync_schemas_non_billable.py b/products/warehouse_sources/backend/tests/management/test_resync_schemas_non_billable.py
new file mode 100644
index 000000000000..bf851e1dc5de
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/management/test_resync_schemas_non_billable.py
@@ -0,0 +1,141 @@
+import pytest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from posthog.api.test.test_organization import create_organization
+from posthog.api.test.test_team import create_team
+
+from products.warehouse_sources.backend.ad_hoc_sync import AdHocSyncTrigger, WorkflowStartError
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+pytestmark = [pytest.mark.django_db]
+
+COMMAND = "products.warehouse_sources.backend.management.commands.resync_schemas_non_billable"
+# The pause/stage/start sequence now lives in one place, so that is where it gets stubbed.
+SHARED = "products.warehouse_sources.backend.ad_hoc_sync"
+
+
+def team():
+ return create_team(organization=create_organization("test org"))
+
+
+def _create_schema(team, name="test_table"):
+ source = ExternalDataSource.objects.create(team=team, source_type="Postgres", job_inputs={})
+ return ExternalDataSchema.objects.create(
+ name=name,
+ team=team,
+ source=source,
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ sync_type_config={},
+ )
+
+
+@patch(f"{COMMAND}.sync_connect")
+@patch(f"{SHARED}.is_schedule_paused", return_value=True)
+@patch(f"{SHARED}.start_external_data_workflow")
+class TestResyncSchemasNonBillable:
+ def test_dry_run_triggers_nothing(self, mock_start, _mock_paused, _mock_connect, team):
+ schema = _create_schema(team)
+
+ call_command("resync_schemas_non_billable", schema_ids=str(schema.id))
+
+ mock_start.assert_not_called()
+
+ def test_live_run_triggers_each_schema_as_non_billable(self, mock_start, _mock_paused, _mock_connect, team):
+ schemas = [_create_schema(team, name=f"table_{i}") for i in range(2)]
+
+ call_command(
+ "resync_schemas_non_billable",
+ schema_ids=",".join(str(s.id) for s in schemas),
+ live_run=True,
+ sleep_seconds=0,
+ )
+
+ assert mock_start.call_count == 2
+ triggered = set()
+ for call in mock_start.call_args_list:
+ inputs = call.args[2]
+ # A billable bulk resync would charge customers for our own data-correctness fix.
+ assert inputs.billable is False
+ triggered.add(str(inputs.external_data_schema_id))
+ assert triggered == {str(s.id) for s in schemas}
+
+ @pytest.mark.parametrize("reset,expected", [(True, True), (False, False)])
+ def test_reset_pipeline_is_staged_only_when_asked(
+ self, mock_start, _mock_paused, _mock_connect, team, reset, expected
+ ):
+ schema = _create_schema(team)
+
+ call_command(
+ "resync_schemas_non_billable",
+ schema_ids=str(schema.id),
+ live_run=True,
+ sleep_seconds=0,
+ reset=reset,
+ )
+
+ schema.refresh_from_db()
+ # Staging the reset wipes the table before the re-read, so it must not happen by default.
+ assert schema.sync_type_config.get("reset_pipeline", False) is expected
+
+ def test_limit_caps_the_batch(self, mock_start, _mock_paused, _mock_connect, team):
+ schemas = [_create_schema(team, name=f"table_{i}") for i in range(3)]
+
+ call_command(
+ "resync_schemas_non_billable",
+ schema_ids=",".join(str(s.id) for s in schemas),
+ live_run=True,
+ sleep_seconds=0,
+ limit=1,
+ )
+
+ assert mock_start.call_count == 1
+
+ @patch(f"{COMMAND}.trigger_ad_hoc_sync")
+ def test_one_failure_does_not_strand_the_rest_of_the_batch(
+ self, mock_trigger, _mock_start, _mock_paused, _mock_connect, team, capsys
+ ):
+ schemas = [_create_schema(team, name=f"table_{i}") for i in range(3)]
+ mock_trigger.side_effect = [
+ WorkflowStartError("temporal down"),
+ AdHocSyncTrigger(workflow_id="wf-2", schedule_paused_now=False),
+ AdHocSyncTrigger(workflow_id="wf-3", schedule_paused_now=False),
+ ]
+
+ call_command(
+ "resync_schemas_non_billable",
+ schema_ids=",".join(str(s.id) for s in schemas),
+ live_run=True,
+ sleep_seconds=0,
+ )
+
+ # Batching dozens of schemas is the point, so one bad schema must not abort the run.
+ assert mock_trigger.call_count == 3
+ assert "Triggered: 2, Failed: 1" in capsys.readouterr().out
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [{"sleep_seconds": -1}, {"limit": 0}, {"limit": -2}],
+ ids=["negative_sleep", "zero_limit", "negative_limit"],
+ )
+ def test_bad_options_are_rejected_before_anything_is_triggered(
+ self, mock_start, _mock_paused, _mock_connect, team, kwargs
+ ):
+ schemas = [_create_schema(team, name=f"table_{i}") for i in range(3)]
+
+ with pytest.raises(CommandError):
+ call_command(
+ "resync_schemas_non_billable",
+ schema_ids=",".join(str(s.id) for s in schemas),
+ live_run=True,
+ **kwargs,
+ )
+
+ # A negative limit silently drops the last schemas, and a negative sleep raises partway
+ # through, so both must fail before a single workflow starts.
+ mock_start.assert_not_called()
diff --git a/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py b/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py
new file mode 100644
index 000000000000..41f731be3cf7
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py
@@ -0,0 +1,83 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.api.test.test_organization import create_organization
+from posthog.api.test.test_team import create_team
+
+from products.warehouse_sources.backend.ad_hoc_sync import WorkflowStartError, trigger_ad_hoc_sync
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+pytestmark = [pytest.mark.django_db]
+
+MODULE = "products.warehouse_sources.backend.ad_hoc_sync"
+
+
+def schema():
+ team = create_team(organization=create_organization("test org"))
+ source = ExternalDataSource.objects.create(team=team, source_type="Postgres", job_inputs={})
+ return ExternalDataSchema.objects.create(
+ name="public.users",
+ team=team,
+ source=source,
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ sync_type_config={},
+ )
+
+
+def test_failed_start_rolls_back_the_pause_it_took(schema):
+ with (
+ patch(f"{MODULE}.is_schedule_paused", return_value=False),
+ patch(f"{MODULE}.pause_external_data_schedule"),
+ patch(f"{MODULE}.unpause_external_data_schedule") as mock_unpause,
+ patch(f"{MODULE}.start_external_data_workflow", side_effect=RuntimeError("temporal down")),
+ pytest.raises(WorkflowStartError),
+ ):
+ trigger_ad_hoc_sync(MagicMock(), schema, billable=False, reset_pipeline=False, workflow_id_prefix="test")
+
+ # The unpause marker is only read by a workflow that never began, so without the rollback the
+ # schedule stays paused forever and the flag is orphaned in config.
+ mock_unpause.assert_called_once_with(str(schema.id))
+ schema.refresh_from_db()
+ assert "admin_unpause_schedule_after_run" not in schema.sync_type_config
+
+
+def test_a_schedule_already_paused_is_left_paused(schema):
+ with (
+ patch(f"{MODULE}.is_schedule_paused", return_value=True),
+ patch(f"{MODULE}.pause_external_data_schedule") as mock_pause,
+ patch(f"{MODULE}.start_external_data_workflow"),
+ ):
+ trigger = trigger_ad_hoc_sync(
+ MagicMock(), schema, billable=False, reset_pipeline=False, workflow_id_prefix="test"
+ )
+
+ # Auto-unpausing would undo an operator's own manual pause.
+ mock_pause.assert_not_called()
+ assert trigger.schedule_paused_now is False
+ schema.refresh_from_db()
+ assert "admin_unpause_schedule_after_run" not in schema.sync_type_config
+
+
+def test_failed_start_restores_staged_reset_state(schema):
+ schema.sync_type_config = {"cdc_mode": "streaming", "cdc_last_log_position": "0/ABC"}
+ schema.sync_type = ExternalDataSchema.SyncType.CDC
+ schema.initial_sync_complete = True
+ schema.save()
+
+ with (
+ patch(f"{MODULE}.is_schedule_paused", return_value=True),
+ patch(f"{MODULE}.start_external_data_workflow", side_effect=RuntimeError("temporal down")),
+ pytest.raises(WorkflowStartError),
+ ):
+ trigger_ad_hoc_sync(MagicMock(), schema, billable=False, reset_pipeline=True, workflow_id_prefix="test")
+
+ # A run that never started must not change what the next scheduled run does. Leaving the reset
+ # staged would wipe the Delta table, and the deleted CDC log position cannot be undone key by key.
+ schema.refresh_from_db()
+ assert "reset_pipeline" not in schema.sync_type_config
+ assert schema.sync_type_config["cdc_mode"] == "streaming"
+ assert schema.sync_type_config["cdc_last_log_position"] == "0/ABC"
+ assert schema.initial_sync_complete is True
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
index e7937c0024a9..0e5556676f48 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
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.models.external_data_schema import Exter
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
_ADMIN_MODULE = "products.warehouse_sources.backend.admin.external_data_schema_admin"
+_SHARED_MODULE = "products.warehouse_sources.backend.ad_hoc_sync"
class TestExternalDataSchemaAdmin(BaseTest):
@@ -65,8 +66,8 @@ class TestExternalDataSchemaAdmin(BaseTest):
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,
+ patch(f"{_SHARED_MODULE}.is_schedule_paused", return_value=True),
+ patch(f"{_SHARED_MODULE}.start_external_data_workflow") as mock_start,
):
response = self.admin.trigger_sync_view(self._request("post", {"reset_pipeline": "on"}), schema.id)