: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(data-warehouse): tear down in-flight runs when a schema stops syncing (#81034)
estefaniad475acbca606
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 51b4833f039c..6e2c6e111403 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -118,6 +118,7 @@ from products.tasks.backend.facade.tasks import (refresh_stale_sandbox_custom_images_task,sweep_loop_task_retention_task,)+from products.warehouse_sources.backend.facade.tasks import sweep_stopped_schema_syncsfrom products.web_analytics.backend.achievements.tasks import sweep_web_analytics_achievement_team_tracksfrom products.web_analytics.backend.tasks.heatmap_screenshot import (reap_stale_prewarm_heatmaps,@@ -571,6 +572,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="send external data failure digest catch-up",)+ # Backstop for the write-time teardown dispatch: Running import jobs whose schema+ # stopped syncing (disabled or deleted) get the same teardown on the next tick.+ sender.add_periodic_task(+ crontab(hour="*", minute="25"),+ sweep_stopped_schema_syncs.s(),+ name="sweep stopped schema syncs",+ )+# Background net for tables created while nobody visits the warehouse status page. Each# reconcile opens a real warehouse session (one worker pod, billed compute), so the sweep is# deliberately infrequent — the 60s-coalesced status-read path is the interactive fast path.diff --git a/posthog/temporal/tests/external_data/test_external_data_job.py b/posthog/temporal/tests/external_data/test_external_data_job.pyindex 5c714a2bbe9b..d638607bd39c 100644--- a/posthog/temporal/tests/external_data/test_external_data_job.py+++ b/posthog/temporal/tests/external_data/test_external_data_job.py@@ -138,6 +138,15 @@ async def postgres_connection(postgres_config, setup_postgres_test_db):await connection.close()[email protected](autouse=True)+def _stub_sync_teardown_dispatch():+ # transaction=True plus eager Celery makes a real auto-disable run the+ # disable-teardown task inline, reaching for the queue DB and Temporal.+ # Tests that assert the dispatch layer their own patch over this one.+ with mock.patch("products.warehouse_sources.backend.tasks.cleanup_disabled_external_data_schema.delay"):+ yield++def _create_schema(schema_name: str, source: ExternalDataSource, team: Team, table_id: Optional[str] = None):return ExternalDataSchema.objects.create(name=schema_name,@@ -551,10 +560,15 @@ async def test_update_external_job_activity_with_non_retryable_error(activity_ensource_id=str(new_source.pk),team_id=team.id,)- with mock.patch(- # patched at its defining module: update_should_sync imports it function-locally now- "products.data_warehouse.backend.logic.data_load.service.external_data_workflow_exists",- return_value=False,+ with (+ mock.patch(+ # patched at its defining module: update_should_sync imports it function-locally now+ "products.data_warehouse.backend.logic.data_load.service.external_data_workflow_exists",+ return_value=False,+ ),+ mock.patch(+ "products.warehouse_sources.backend.tasks.cleanup_disabled_external_data_schema.delay"+ ) as mock_teardown,):await activity_environment.run(update_external_data_job_model, inputs)@@ -564,6 +578,9 @@ async def test_update_external_job_activity_with_non_retryable_error(activity_enassert new_job.status == ExternalDataJob.Status.COMPLETEDassert schema.status == ExternalDataJob.Status.COMPLETEDassert schema.should_sync is False+ # The disable must tear down the run's leftovers without cancelling its own workflow.+ mock_teardown.assert_called_once()+ assert mock_teardown.call_args.kwargs["exclude_workflow_id"] == activity_environment.info.workflow_id@pytest.mark.django_db(transaction=True)@@ -604,10 +621,15 @@ async def test_update_external_job_activity_with_not_source_sepecific_non_retryasource_id=str(new_source.pk),team_id=team.id,)- with mock.patch(- # patched at its defining module: update_should_sync imports it function-locally now- "products.data_warehouse.backend.logic.data_load.service.external_data_workflow_exists",- return_value=False,+ with (+ mock.patch(+ # patched at its defining module: update_should_sync imports it function-locally now+ "products.data_warehouse.backend.logic.data_load.service.external_data_workflow_exists",+ return_value=False,+ ),+ mock.patch(+ "products.warehouse_sources.backend.tasks.cleanup_disabled_external_data_schema.delay"+ ) as mock_teardown,):await activity_environment.run(update_external_data_job_model, inputs)@@ -617,6 +639,9 @@ async def test_update_external_job_activity_with_not_source_sepecific_non_retryaassert new_job.status == ExternalDataJob.Status.COMPLETEDassert schema.status == ExternalDataJob.Status.COMPLETEDassert schema.should_sync is False+ # The disable must tear down the run's leftovers without cancelling its own workflow.+ mock_teardown.assert_called_once()+ assert mock_teardown.call_args.kwargs["exclude_workflow_id"] == activity_environment.info.workflow_id# The full message carries volatile parts (host, URL, `_ssl.c:NNNN`) around the stable alert name.diff --git a/products/warehouse_sources/backend/facade/tasks.py b/products/warehouse_sources/backend/facade/tasks.pynew file mode 100644index 000000000000..3e9d26e165a5--- /dev/null+++ b/products/warehouse_sources/backend/facade/tasks.py@@ -0,0 +1,5 @@+"""Celery tasks core schedules for warehouse_sources (see products/architecture.md, wiring couplings)."""++from products.warehouse_sources.backend.tasks import sweep_stopped_schema_syncs++__all__ = ["sweep_stopped_schema_syncs"]diff --git a/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.pyindex 75ea7d2611d4..621e9ba87d1c 100644--- a/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py+++ b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py@@ -23,12 +23,10 @@ from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URLfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.sync_teardown import teardown_runfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (RECOVERY_GRACE_SECONDS,)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (- mark_job_failed_if_not_terminal,-)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (PARTITION_PRUNING_INTERVAL,TAKEOVER_STALE_THRESHOLD_SECONDS,@@ -514,37 +512,43 @@ class Command(BaseCommand):reason: str,queue: QueueType,) -> None:- """Mirror the consumer's fail path; each step isolated so one failure doesn't abort the rest."""+ """Run the shared teardown core (also used by the disable-sync Celery task) and report each step."""+ outcome = teardown_run(+ conn,+ run_uuid=target.run_uuid,+ job_id=target.job_id,+ team_id=target.team_id,+ schema_id=target.schema_id,+ workflow_run_id=target.workflow_run_id,+ reason=reason,+ queue=queue,+ )+if target.run_uuid:- try:- failed = queue.fail_run_sync(conn, run_uuid=target.run_uuid, reason=reason)- self.stdout.write(f" queue: marked {failed} pending batch(es) failed")- except Exception:- logger.exception("manage_warehouse_queue_fail_run_queue_write_failed", run_uuid=target.run_uuid)+ if outcome.queue_write_failed:self.stdout.write(self.style.ERROR(" queue: FAILED to write failed statuses (see logs)"))+ else:+ self.stdout.write(f" queue: marked {outcome.batches_failed} pending batch(es) failed")- try:- transitioned = mark_job_failed_if_not_terminal(job_id=target.job_id, team_id=target.team_id, error=reason)- self.stdout.write(" job: marked Failed" if transitioned else " job: already terminal - left unchanged")- except Exception:- logger.exception("manage_warehouse_queue_fail_run_job_update_failed", job_id=target.job_id)+ if outcome.job_transitioned is None:self.stdout.write(self.style.ERROR(" job: FAILED to update status (see logs)"))+ elif outcome.job_transitioned:+ self.stdout.write(" job: marked Failed")+ else:+ self.stdout.write(" job: already terminal - left unchanged")if target.workflow_run_id and target.schema_id:- released = release_v3_pipeline_lock(target.team_id, target.schema_id, token=target.workflow_run_id)- if released:+ if outcome.lock_released:self.stdout.write(" redis lock: released")+ elif outcome.lock_holder is None:+ self.stdout.write(" redis lock: not held")else:- holder = get_v3_pipeline_lock_holder(target.team_id, target.schema_id)- if holder is None:- self.stdout.write(" redis lock: not held")- else:- self.stdout.write(- self.style.WARNING(- f" redis lock: held by a different token ({holder!r}) - a newer run may own it; "- "use release-locks if it is genuinely stale"- )+ self.stdout.write(+ self.style.WARNING(+ f" redis lock: held by a different token ({outcome.lock_holder!r}) - a newer run may own it; "+ "use release-locks if it is genuinely stale")+ )def _cancel_workflows(self, options: dict[str, Any], jobs: list[ExternalDataJob | None]) -> None:"""Cancel each job's Temporal workflow over a single client connection.diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex c875e507958e..8fb8942c5e97 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -2,7 +2,9 @@ import reimport sysimport uuidimport fnmatch-from collections.abc import Callable, Iterable+from collections.abc import Callable, Generator, Iterable+from contextlib import contextmanager+from contextvars import ContextVarfrom dataclasses import dataclassfrom datetime import date, datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literal, Optional@@ -32,6 +34,114 @@ if TYPE_CHECKING:type IncrementalFieldValue = str | int | float | None+# Recorded as the job's latest_error, which the syncs UI shows to the customer.+SYNC_DISABLED_JOB_ERROR = "Sync stopped because syncing was turned off"+SCHEMA_DELETED_JOB_ERROR = "Sync stopped because the table was deleted"+AUTO_DISABLED_JOB_ERROR = "Sync stopped because of an error that retrying would not fix"+++@dataclass(frozen=True, kw_only=True)+class SyncDisableContext:+ """Caller-supplied context for a should_sync disable, carried to the teardown task.++ ``error_message`` overrides the default job error (the auto-disable path records+ its user-facing non-retryable error instead of the generic "turned off" copy).+ ``exclude_workflow_id`` names a Temporal workflow the teardown must not cancel,+ for disables issued from inside the workflow's own failure handling.+ """++ error_message: str | None = None+ exclude_workflow_id: str | None = None+++_sync_disable_context: ContextVar[SyncDisableContext | None] = ContextVar("sync_disable_context", default=None)+++@contextmanager+def sync_disable_context(+ *, error_message: str | None = None, exclude_workflow_id: str | None = None+) -> Generator[None]:+ token = _sync_disable_context.set(+ SyncDisableContext(error_message=error_message, exclude_workflow_id=exclude_workflow_id)+ )+ try:+ yield+ finally:+ _sync_disable_context.reset(token)+++def _schedule_sync_teardown(*, schema_id: str, team_id: int, deleted: bool) -> None:+ """Dispatch the async teardown of a schema's in-flight sync work, post-commit.++ Stopping the scheduler is not enough: the in-flight run keeps its Temporal+ workflow, its Running job, and its enqueued v3 batches, and a run that still+ trickles progress falls through both reconcile sweeps. The teardown runs in a+ Celery task because it may fail tens of thousands of queue rows and talks to+ Temporal, neither of which may block the write that flipped the flag; cancelling+ a workflow is irreversible, so the dispatch waits for the commit.+ """+ ctx = _sync_disable_context.get()+ if ctx is not None and ctx.error_message:+ reason = ctx.error_message+ elif deleted:+ reason = SCHEMA_DELETED_JOB_ERROR+ else:+ reason = SYNC_DISABLED_JOB_ERROR+ exclude_workflow_id = ctx.exclude_workflow_id if ctx is not None else None++ def _dispatch() -> None:+ # Deferred to keep Celery off the import path of this models module.+ from products.warehouse_sources.backend.tasks import cleanup_disabled_external_data_schema # noqa: PLC0415++ cleanup_disabled_external_data_schema.delay(+ team_id=team_id,+ schema_id=schema_id,+ reason=reason,+ exclude_workflow_id=exclude_workflow_id,+ )++ transaction.on_commit(_dispatch)+++def _schema_ids_with_running_jobs(schema_ids: list[uuid.UUID]) -> set[uuid.UUID]:+ # Deferred to break the import cycle with external_data_job.+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob # noqa: PLC0415++ return set(+ ExternalDataJob.objects.filter(schema_id__in=schema_ids, status=ExternalDataJob.Status.RUNNING).values_list(+ "schema_id", flat=True+ )+ )+++class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):+ def update(self, **kwargs: Any) -> int:+ """Chokepoint for bulk writes that stop a schema from syncing.++ Queryset ``.update()`` bypasses ``Model.save()``, so without this override a+ bulk disable (e.g. ``disable_cdc``) or bulk soft-delete (source ``destroy``)+ would strand its in-flight runs. The transition set is read before the write+ so rows already disabled/deleted are not re-torn-down, and only schemas with+ a Running job dispatch a task.+ """+ disabling = kwargs.get("should_sync") is False+ deleting = kwargs.get("deleted") is True+ transitioning: list[tuple[uuid.UUID, int]] = []+ if disabling or deleting:+ predicate = models.Q()+ if disabling:+ predicate |= models.Q(should_sync=True)+ if deleting:+ predicate |= ~models.Q(deleted=True)+ transitioning = list(self.filter(predicate).values_list("id", "team_id"))+ updated = super().update(**kwargs)+ if transitioning:+ running = _schema_ids_with_running_jobs([schema_id for schema_id, _ in transitioning])+ for schema_id, team_id in transitioning:+ if schema_id in running:+ _schedule_sync_teardown(schema_id=str(schema_id), team_id=team_id, deleted=deleting)+ return updated+class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields):class Status(models.TextChoices):@@ -101,11 +211,38 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField# null (default) = sync all rows. List of {column, operator, value} predicates ANDed onto the WHERE clause.row_filters = models.JSONField(null=True, blank=True, default=None)+ objects = ExternalDataSchemaQuerySet.as_manager()+__repr__ = sane_repr("name")class Meta:db_table = "posthog_externaldataschema"+ def _sync_teardown_kind(self, update_fields: Iterable[str] | None) -> str | None:+ """Which stop-syncing transition this save performs, read from the DB before writing.++ The DB read (rather than a value cached at load time) is what makes a no-op+ re-save of ``should_sync=False`` not re-fail anything: only a row that is+ currently syncing (or not yet deleted) counts as a transition. Saves scoped+ by ``update_fields`` to other columns skip the read entirely, so the+ pipeline's frequent bookkeeping saves pay nothing.+ """+ if self._state.adding:+ return None+ disabling = self.should_sync is False and (update_fields is None or "should_sync" in update_fields)+ deleting = self.deleted is True and (update_fields is None or "deleted" in update_fields)+ if not disabling and not deleting:+ return None+ prior = ExternalDataSchema.objects.filter(pk=self.pk).values_list("should_sync", "deleted").first()+ if prior is None:+ return None+ prior_should_sync, prior_deleted = prior+ if deleting and not prior_deleted:+ return "deleted"+ if disabling and prior_should_sync:+ return "disabled"+ return None+def save(self, *args: Any, skip_activity_log: bool = False, **kwargs: Any) -> None:# Populate the S3 folder on first write so the column is always authoritative for new rows.# Legacy/qualified rows set it explicitly before renaming (see `_qualify_legacy_row`); this@@ -116,6 +253,11 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldif update_fields is not None:kwargs["update_fields"] = {*update_fields, "s3_folder_name"}+ # Chokepoint for instance writes that stop this schema from syncing; the queryset+ # `.update()` twin lives on ExternalDataSchemaQuerySet. Detected before the write,+ # dispatched only after it succeeds.+ teardown_kind = self._sync_teardown_kind(kwargs.get("update_fields"))+if skip_activity_log:# Internal pipeline-driven bookkeeping saves (sync_type_config / xmin state) don't need# an audit trail. Bypass ModelActivityMixin.save() so we skip its extra _get_before_update@@ -132,6 +274,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldelse:super().save(*args, **kwargs)+ if teardown_kind is not None and _schema_ids_with_running_jobs([self.pk]):+ _schedule_sync_teardown(schema_id=str(self.pk), team_id=self.team_id, deleted=teardown_kind == "deleted")+def folder_path(self) -> str:return f"team_{self.team_id}_{self.source.source_type}_{str(self.id)}".lower().replace("-", "_")@@ -896,7 +1041,14 @@ def aget_schema_by_id(schema_id: str, team_id: int) -> ExternalDataSchema | None)-def update_should_sync(schema_id: str, team_id: int, should_sync: bool) -> ExternalDataSchema | None:+def update_should_sync(+ schema_id: str,+ team_id: int,+ should_sync: bool,+ *,+ disable_error_message: str | None = None,+ disable_exclude_workflow_id: str | None = None,+) -> ExternalDataSchema | None:# data_load.service imports temporalio at module scope; this is a models module, so a# top-level import would put the Temporal client on the django.setup() pathfrom products.data_warehouse.backend.facade.api import ( # noqa: PLC0415@@ -908,7 +1060,8 @@ def update_should_sync(schema_id: str, team_id: int, should_sync: bool) -> Exterschema = ExternalDataSchema.objects.select_related("source").get(id=schema_id, team_id=team_id)schema.should_sync = should_sync- schema.save()+ with sync_disable_context(error_message=disable_error_message, exclude_workflow_id=disable_exclude_workflow_id):+ schema.save()if not schema.source.supports_scheduled_sync:return schemadiff --git a/products/warehouse_sources/backend/sync_teardown.py b/products/warehouse_sources/backend/sync_teardown.pynew file mode 100644index 000000000000..3f2a933a2c84--- /dev/null+++ b/products/warehouse_sources/backend/sync_teardown.py@@ -0,0 +1,285 @@+"""Teardown of in-flight sync work when a schema stops syncing.++Setting ``should_sync=False`` (or soft-deleting a schema) only stops the scheduler+from starting new runs. Without this teardown, an in-flight run keeps its Temporal+workflow alive, its ExternalDataJob in Running, and its already-enqueued v3 queue+batches claimable. A run that is still trickling batches falls through both+reconcile sweeps (it has no failed batch and it has loader progress), so its queue+depth is consumed until the run would have finished on its own.++``teardown_run`` is the per-run core shared with the ``manage_warehouse_queue``+``fail-run`` ops command; ``teardown_schema_syncs`` is the schema-level+orchestration the ``cleanup_disabled_external_data_schema`` Celery task runs.+Every step is idempotent: pending batches already failed are not re-failed, a+terminal job is left unchanged, and lock releases are token-compared.+"""++from dataclasses import dataclass+from typing import Any++import psycopg+import structlog+from prometheus_client import Counter++from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL++from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BatchQueue,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (+ get_v3_pipeline_lock_holder,+ release_v3_pipeline_lock,+)++logger = structlog.get_logger(__name__)++SYNC_TEARDOWN_ERRORS = Counter(+ "dwh_sync_teardown_errors",+ "Errors hit while tearing down in-flight sync work after a schema stopped syncing",+)+++@dataclass(frozen=True, kw_only=True)+class RunTeardownOutcome:+ """Per-step result of failing one run, so callers can report or retry precisely.++ ``batches_failed`` is None when there was no queue run to touch or the queue+ write raised (``queue_write_failed`` distinguishes the two). ``job_transitioned``+ is None when the job-status write raised, False when the job was already+ terminal. ``lock_released`` is None when there was no token to compare against;+ ``lock_holder`` carries the current holder when the release was refused.+ """++ batches_failed: int | None+ queue_write_failed: bool+ job_transitioned: bool | None+ lock_released: bool | None+ lock_holder: str | None+++@dataclass(frozen=True, kw_only=True)+class SchemaTeardownSummary:+ runs_failed: int+ batches_failed: int+ jobs_finalized: int+ leases_released: int+ workflows_cancelled: int+ errors: int+++def teardown_run(+ conn: psycopg.Connection[Any] | None,+ *,+ run_uuid: str | None,+ job_id: str,+ team_id: int,+ schema_id: str | None,+ workflow_run_id: str | None,+ reason: str,+ queue: type[BatchQueue] = BatchQueue,+) -> RunTeardownOutcome:+ """Fail one run's pending batches, mark its job Failed, release its v3 Redis lock.++ Each step is isolated so one failure doesn't abort the rest; the outcome+ records what actually happened. Failing the batches before anything can+ also serve as the reconcile backstop: once a run has a failed batch, the+ consumers' ``get_failed_runs`` sweep will finish the cleanup even if the+ remaining steps here never succeed.+ """+ # Deferred: consumer.py pulls in the batch-consumer engine, which callers on the+ # django.setup() path (models, Celery autodiscovery) must not pay for.+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import ( # noqa: PLC0415+ mark_job_failed_if_not_terminal,+ )++ batches_failed: int | None = None+ queue_write_failed = False+ if run_uuid and conn is not None:+ try:+ batches_failed = queue.fail_run_sync(conn, run_uuid=run_uuid, reason=reason)+ except Exception:+ logger.exception("sync_teardown_queue_write_failed", run_uuid=run_uuid, job_id=job_id)+ queue_write_failed = True++ job_transitioned: bool | None = None+ try:+ job_transitioned = mark_job_failed_if_not_terminal(job_id=job_id, team_id=team_id, error=reason)+ except Exception:+ logger.exception("sync_teardown_job_update_failed", job_id=job_id)++ lock_released: bool | None = None+ lock_holder: str | None = None+ if workflow_run_id and schema_id:+ lock_released = release_v3_pipeline_lock(team_id, schema_id, token=workflow_run_id)+ if not lock_released:+ lock_holder = get_v3_pipeline_lock_holder(team_id, schema_id)++ return RunTeardownOutcome(+ batches_failed=batches_failed,+ queue_write_failed=queue_write_failed,+ job_transitioned=job_transitioned,+ lock_released=lock_released,+ lock_holder=lock_holder,+ )+++def teardown_schema_syncs(+ *,+ team_id: int,+ schema_id: str,+ reason: str,+ exclude_workflow_id: str | None = None,+) -> SchemaTeardownSummary:+ """Stop all in-flight sync work for a schema that no longer syncs.++ Ordering mirrors the schema ``cancel`` endpoint: the Failed job marker is+ written first (terminal statuses absorb any later status write from the+ workflow), then queue batches are failed, then the Temporal workflow is asked+ to cancel. ``exclude_workflow_id`` skips cancelling the caller's own workflow+ when the disable originates from inside a run's failure handling; the batch+ and job cleanup still applies there.++ Raises when any step failed after doing everything else it could, so the+ Celery task retries; every step is a no-op on rows it already processed.+ """+ # Deferred: the Temporal client stack stays off the import path of everything+ # that imports this module for the dataclasses alone.+ import temporalio.service # noqa: PLC0415++ from products.data_warehouse.backend.facade.api import cancel_external_data_workflow # noqa: PLC0415+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import ( # noqa: PLC0415+ mark_job_failed_if_not_terminal,+ )++ errors = 0+ runs_failed = 0+ batches_failed = 0+ jobs_finalized = 0+ leases_released = 0+ workflows_cancelled = 0++ running_jobs = list(+ ExternalDataJob.objects.filter(team_id=team_id, schema_id=schema_id, status=ExternalDataJob.Status.RUNNING)+ )++ conn: psycopg.Connection[Any] | None = None+ try:+ conn = psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)+ except Exception:+ # Queue-side cleanup will happen on the retry; still finalize jobs and+ # cancel workflows below so the run stops producing work in the meantime.+ logger.exception("sync_teardown_queue_connect_failed", team_id=team_id, external_data_schema_id=schema_id)+ errors += 1++ try:+ handled_job_ids: set[str] = set()+ if conn is not None:+ try:+ active_runs = BatchQueue.get_active_runs(conn, team_id=team_id, schema_ids=[schema_id])+ except Exception:+ logger.exception("sync_teardown_queue_read_failed", team_id=team_id, external_data_schema_id=schema_id)+ errors += 1+ active_runs = []+ for run in active_runs:+ outcome = teardown_run(+ conn,+ run_uuid=run.run_uuid,+ job_id=run.job_id,+ team_id=run.team_id,+ schema_id=run.schema_id,+ workflow_run_id=run.workflow_run_id,+ reason=reason,+ )+ handled_job_ids.add(run.job_id)+ runs_failed += 1+ batches_failed += outcome.batches_failed or 0+ if outcome.queue_write_failed or outcome.job_transitioned is None:+ errors += 1+ if outcome.job_transitioned:+ jobs_finalized += 1++ # Running v3 jobs the queue knows nothing about (nothing enqueued yet, or the+ # queue rows aged out of retention) still need the Failed marker and lock release.+ for job in running_jobs:+ if str(job.id) in handled_job_ids or job.pipeline_version != ExternalDataJob.PipelineVersion.V3:+ continue+ outcome = teardown_run(+ conn,+ run_uuid=None,+ job_id=str(job.id),+ team_id=team_id,+ schema_id=schema_id,+ workflow_run_id=job.workflow_run_id,+ reason=reason,+ )+ if outcome.job_transitioned is None:+ errors += 1+ if outcome.job_transitioned:+ jobs_finalized += 1++ # Only expired leases are dropped: a live lease belongs to a consumer pod that+ # will finish its claimed batches and let the lease lapse once nothing is pending.+ if conn is not None:+ try:+ expired_pairs = [+ (lease.team_id, lease.schema_id)+ for lease in BatchQueue.get_leases(conn, team_id=team_id, schema_ids=[schema_id])+ if not lease.is_live+ ]+ if expired_pairs:+ leases_released = BatchQueue.force_release_leases(conn, pairs=expired_pairs)+ except Exception:+ logger.exception(+ "sync_teardown_lease_release_failed", team_id=team_id, external_data_schema_id=schema_id+ )+ errors += 1+ finally:+ if conn is not None:+ conn.close()++ for job in running_jobs:+ if not job.workflow_id or job.workflow_id == exclude_workflow_id:+ continue+ try:+ cancel_external_data_workflow(job.workflow_id)+ workflows_cancelled += 1+ except temporalio.service.RPCError as e:+ if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:+ # Already finished or terminated. v1/v2 jobs rely on the workflow to+ # write their terminal status, so unstick them here (the v3 marker was+ # already written above).+ if job.pipeline_version != ExternalDataJob.PipelineVersion.V3:+ try:+ mark_job_failed_if_not_terminal(job_id=str(job.id), team_id=team_id, error=reason)+ except Exception:+ logger.exception("sync_teardown_job_update_failed", job_id=str(job.id))+ errors += 1+ else:+ logger.exception("sync_teardown_workflow_cancel_failed", workflow_id=job.workflow_id)+ errors += 1+ except Exception:+ logger.exception("sync_teardown_workflow_cancel_failed", workflow_id=job.workflow_id)+ errors += 1++ summary = SchemaTeardownSummary(+ runs_failed=runs_failed,+ batches_failed=batches_failed,+ jobs_finalized=jobs_finalized,+ leases_released=leases_released,+ workflows_cancelled=workflows_cancelled,+ errors=errors,+ )+ logger.info(+ "sync_teardown_completed",+ team_id=team_id,+ external_data_schema_id=schema_id,+ reason=reason,+ **summary.__dict__,+ )+ if errors:+ SYNC_TEARDOWN_ERRORS.inc(errors)+ raise RuntimeError(+ f"Sync teardown for schema {schema_id} hit {errors} error(s); retry will re-run the remaining steps"+ )+ return summarydiff --git a/products/warehouse_sources/backend/tasks/__init__.py b/products/warehouse_sources/backend/tasks/__init__.pynew file mode 100644index 000000000000..33b7a22a641e--- /dev/null+++ b/products/warehouse_sources/backend/tasks/__init__.py@@ -0,0 +1,4 @@+from products.warehouse_sources.backend.tasks.tasks import ( # noqa: F401+ cleanup_disabled_external_data_schema,+ sweep_stopped_schema_syncs,+)diff --git a/products/warehouse_sources/backend/tasks/tasks.py b/products/warehouse_sources/backend/tasks/tasks.pynew file mode 100644index 000000000000..d34abe77ff80--- /dev/null+++ b/products/warehouse_sources/backend/tasks/tasks.py@@ -0,0 +1,114 @@+from datetime import timedelta++from django.db.models import Q+from django.utils import timezone++import structlog+from celery import shared_task++from posthog.scoping_audit import skip_team_scope_audit++from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.models.external_data_schema import (+ SCHEMA_DELETED_JOB_ERROR,+ SYNC_DISABLED_JOB_ERROR,+ ExternalDataSchema,+)++logger = structlog.get_logger(__name__)++# Bounds the teardown-task fanout of one sweep tick; the remainder drains on later ticks.+STOPPED_SYNC_SWEEP_CAP = 500++# A schema saved within this window may have been auto-disabled by its own workflow's+# failure handling, which the write-time dispatch excludes from cancellation; sweeping it+# this tick would cancel that still-finishing workflow. `updated_at` only bumps on+# `save()`, so bulk `.update()` disables are not delayed.+STOPPED_SYNC_SWEEP_GRACE = timedelta(minutes=30)++# Jobs stuck in Running from before this sweep shipped are left alone rather than+# mass-failed (and their latest_error rewritten) on the first ticks after deploy.+STOPPED_SYNC_SWEEP_MAX_JOB_AGE = timedelta(days=7)+++@shared_task(+ ignore_result=True,+ autoretry_for=(Exception,),+ retry_backoff=60,+ retry_backoff_max=3600,+ max_retries=10,+)+@skip_team_scope_audit+def cleanup_disabled_external_data_schema(+ *,+ team_id: int,+ schema_id: str,+ reason: str,+ exclude_workflow_id: str | None = None,+) -> None:+ """Stop in-flight sync work after a schema stopped syncing (disabled or deleted).++ Dispatched from the ``ExternalDataSchema`` write chokepoints via+ ``transaction.on_commit``. Runs asynchronously because the teardown talks to+ Temporal and may fail tens of thousands of queue batch rows, which must not+ block the API response that flipped the flag. Retries with backoff; every+ teardown step is idempotent, so a retry only re-runs what previously failed.+ """+ # Deferred: keeps the queue/Temporal stack out of Celery task autodiscovery.+ from products.warehouse_sources.backend.sync_teardown import teardown_schema_syncs # noqa: PLC0415++ # A dispatch can go stale: if the schema was re-enabled before this task (or one+ # of its retries) ran, tearing down now would kill the new legitimate run.+ if (+ ExternalDataSchema.objects.filter(id=schema_id, team_id=team_id, should_sync=True)+ .exclude(deleted=True)+ .exists()+ ):+ logger.info(+ "cleanup_disabled_external_data_schema_skipped_syncing_again",+ team_id=team_id,+ external_data_schema_id=schema_id,+ )+ return++ teardown_schema_syncs(+ team_id=team_id,+ schema_id=schema_id,+ reason=reason,+ exclude_workflow_id=exclude_workflow_id,+ )+++@shared_task(ignore_result=True)+@skip_team_scope_audit+def sweep_stopped_schema_syncs() -> None:+ """Backstop for the write-time disable/delete teardown dispatch.++ The model chokepoint is event-based, and events can be missed: a job created+ concurrently with the disable, a writer the chokepoint cannot see (bulk_update,+ raw SQL, a hard delete), or a dropped task. This sweep finds Running jobs whose+ schema no longer syncs and dispatches the same idempotent teardown, so a missed+ event heals on the next cycle instead of never. Overlap with a write-time+ dispatch still in flight is harmless for the same reason.+ """+ now = timezone.now()+ stopped = list(+ ExternalDataJob.objects.filter(status=ExternalDataJob.Status.RUNNING)+ .filter(Q(schema__should_sync=False) | Q(schema__deleted=True))+ .filter(created_at__gte=now - STOPPED_SYNC_SWEEP_MAX_JOB_AGE)+ .exclude(schema__updated_at__gte=now - STOPPED_SYNC_SWEEP_GRACE)+ .values_list("schema_id", "team_id", "schema__deleted")+ .distinct()[: STOPPED_SYNC_SWEEP_CAP + 1]+ )+ if len(stopped) > STOPPED_SYNC_SWEEP_CAP:+ logger.warning("sweep_stopped_schema_syncs_capped", cap=STOPPED_SYNC_SWEEP_CAP)+ stopped = stopped[:STOPPED_SYNC_SWEEP_CAP]++ for schema_id, team_id, deleted in stopped:+ cleanup_disabled_external_data_schema.delay(+ team_id=team_id,+ schema_id=str(schema_id),+ reason=SCHEMA_DELETED_JOB_ERROR if deleted else SYNC_DISABLED_JOB_ERROR,+ )+ if stopped:+ logger.info("sweep_stopped_schema_syncs_dispatched", count=len(stopped))diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex d6629135e13c..486b59b147d6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -37,7 +37,11 @@ from products.managed_warehouse.backend.facade.temporal import (DuckLakeRegisterDataImportsWorkflow,)from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, update_should_sync+from products.warehouse_sources.backend.models.external_data_schema import (+ AUTO_DISABLED_JOB_ERROR,+ ExternalDataSchema,+ update_should_sync,+)from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (EmitSignalsActivityInputs,@@ -286,10 +290,6 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpu"error": inputs.internal_error,},)- await database_sync_to_async_pool(update_should_sync)(- schema_id=inputs.schema_id, team_id=inputs.team_id, should_sync=False- )-friendly_errors = [friendly_errorfor error, friendly_error in non_retryable_errors.items()@@ -300,6 +300,17 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpulogger.exception(friendly_errors[0])inputs.latest_error = friendly_errors[0]+ # Computed after the friendly error so the teardown records the same message+ # the job will show. Excluding this workflow keeps the disable's teardown from+ # cancelling the very run that is already finishing through its failure path.+ await database_sync_to_async_pool(update_should_sync)(+ schema_id=inputs.schema_id,+ team_id=inputs.team_id,+ should_sync=False,+ disable_error_message=inputs.latest_error or AUTO_DISABLED_JOB_ERROR,+ disable_exclude_workflow_id=activity.info().workflow_id,+ )+await database_sync_to_async_pool(update_external_job_status)(job_id=job_id,status=ExternalDataJob.Status(inputs.status),diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.pyindex 6f9cdc708129..083ff31fccc0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py@@ -45,6 +45,16 @@ SESSION = aioboto3.Session()create_test_client = functools.partial(SESSION.client, endpoint_url=settings.OBJECT_STORAGE_ENDPOINT)[email protected](autouse=True)+def _stub_sync_teardown_dispatch():+ # These suites run with transaction=True and eager Celery, so a real auto-disable+ # (non-retryable source error) would execute the disable-teardown task inline,+ # reaching for the queue DB and Temporal mid-workflow. The dispatch has its own+ # tests (test_sync_teardown.py); keep it out of these runs.+ with mock.patch("products.warehouse_sources.backend.tasks.cleanup_disabled_external_data_schema.delay"):+ yield++@pytest.fixture(scope="package")def _ensure_sourcebatch_tables(django_db_setup, django_db_blocker):"""Create sourcebatch/sourcebatchstatus tables in the default test database.diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.pyindex 0a765c9f9abc..c418ef66a456 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py@@ -3119,6 +3119,8 @@ async def test_postgres_duplicate_primary_key(team, postgres_config, postgres_coschema_id=str(schema.id),team_id=team.id,should_sync=False,+ disable_error_message=job.latest_error,+ disable_exclude_workflow_id=mock.ANY,)diff --git a/products/warehouse_sources/backend/tests/test_sync_teardown.py b/products/warehouse_sources/backend/tests/test_sync_teardown.pynew file mode 100644index 000000000000..8e8e9da9434c--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_sync_teardown.py@@ -0,0 +1,310 @@+from collections.abc import Generator+from contextlib import contextmanager+from datetime import timedelta+from typing import Any+from uuid import uuid4++import pytest+from unittest.mock import patch++from django.utils import timezone++import psycopg+import fakeredis++from posthog.api.test.test_organization import create_organization+from posthog.api.test.test_team import create_team++from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.models.external_data_schema import (+ SCHEMA_DELETED_JOB_ERROR,+ SYNC_DISABLED_JOB_ERROR,+ ExternalDataSchema,+ update_should_sync,+)+from products.warehouse_sources.backend.sync_teardown import teardown_schema_syncs+from products.warehouse_sources.backend.tasks.tasks import (+ STOPPED_SYNC_SWEEP_GRACE,+ STOPPED_SYNC_SWEEP_MAX_JOB_AGE,+ cleanup_disabled_external_data_schema,+ sweep_stopped_schema_syncs,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import sync_lock+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (+ _ensure_tables,+ _get_test_database_url,+ _truncate_tables,+)+from products.warehouse_sources.backend.tests.management.test_manage_warehouse_queue import (+ _create_pipeline,+ _failed_status_counts_by_run,+ _insert_lease,+ _lease_count,+ _seed_active_run,+)++pytestmark = [pytest.mark.django_db]++TASK_DELAY = "products.warehouse_sources.backend.tasks.cleanup_disabled_external_data_schema.delay"+++def organization():+ return create_organization("test org")+++def team(organization):+ return create_team(organization=organization)+++def _create_schema_with_running_job(team) -> tuple[ExternalDataSchema, ExternalDataJob]:+ _, schema, job = _create_pipeline(team)+ return schema, job+++class TestDisableChokepointDispatch:+ def test_save_disable_with_running_job_dispatches_teardown(self, team, django_capture_on_commit_callbacks):+ schema, _job = _create_schema_with_running_job(team)++ with patch(TASK_DELAY) as mock_delay, django_capture_on_commit_callbacks(execute=True):+ schema.should_sync = False+ schema.save()++ mock_delay.assert_called_once_with(+ team_id=team.pk,+ schema_id=str(schema.id),+ reason=SYNC_DISABLED_JOB_ERROR,+ exclude_workflow_id=None,+ )++ @pytest.mark.parametrize(+ "case",+ ["already_disabled", "no_running_job", "re_enable"],+ )+ def test_no_dispatch_without_a_real_disable_of_live_work(self, case, team, django_capture_on_commit_callbacks):+ schema, job = _create_schema_with_running_job(team)+ if case in ("already_disabled", "re_enable"):+ ExternalDataSchema.objects.filter(pk=schema.pk).update(should_sync=False)+ schema.refresh_from_db()+ if case == "no_running_job":+ job.status = ExternalDataJob.Status.COMPLETED+ job.save()++ with patch(TASK_DELAY) as mock_delay, django_capture_on_commit_callbacks(execute=True):+ schema.should_sync = case == "re_enable"+ schema.save()++ mock_delay.assert_not_called()++ def test_queryset_update_dispatches_only_for_rows_that_were_syncing(self, team, django_capture_on_commit_callbacks):+ syncing_schema, _ = _create_schema_with_running_job(team)+ disabled_schema, _ = _create_schema_with_running_job(team)+ ExternalDataSchema.objects.filter(pk=disabled_schema.pk).update(should_sync=False)++ with patch(TASK_DELAY) as mock_delay, django_capture_on_commit_callbacks(execute=True):+ ExternalDataSchema.objects.filter(pk__in=[syncing_schema.pk, disabled_schema.pk]).update(should_sync=False)++ mock_delay.assert_called_once()+ assert mock_delay.call_args.kwargs["schema_id"] == str(syncing_schema.id)+ assert mock_delay.call_args.kwargs["reason"] == SYNC_DISABLED_JOB_ERROR++ def test_bulk_soft_delete_dispatches_with_deleted_reason(self, team, django_capture_on_commit_callbacks):+ schema, _job = _create_schema_with_running_job(team)++ with patch(TASK_DELAY) as mock_delay, django_capture_on_commit_callbacks(execute=True):+ ExternalDataSchema.objects.filter(pk=schema.pk).update(deleted=True)++ mock_delay.assert_called_once()+ assert mock_delay.call_args.kwargs["reason"] == SCHEMA_DELETED_JOB_ERROR++ def test_soft_delete_save_dispatches_with_deleted_reason(self, team, django_capture_on_commit_callbacks):+ schema, _job = _create_schema_with_running_job(team)++ with patch(TASK_DELAY) as mock_delay, django_capture_on_commit_callbacks(execute=True):+ schema.soft_delete()++ mock_delay.assert_called_once()+ assert mock_delay.call_args.kwargs["reason"] == SCHEMA_DELETED_JOB_ERROR++ def test_update_should_sync_carries_error_and_workflow_exclusion(self, team, django_capture_on_commit_callbacks):+ schema, job = _create_schema_with_running_job(team)++ with (+ patch(TASK_DELAY) as mock_delay,+ patch(+ "products.data_warehouse.backend.logic.data_load.service.external_data_workflow_exists",+ return_value=False,+ ),+ django_capture_on_commit_callbacks(execute=True),+ ):+ update_should_sync(+ schema_id=str(schema.id),+ team_id=team.pk,+ should_sync=False,+ disable_error_message="Your account does not have access to this table",+ disable_exclude_workflow_id=job.workflow_id,+ )++ mock_delay.assert_called_once_with(+ team_id=team.pk,+ schema_id=str(schema.id),+ reason="Your account does not have access to this table",+ exclude_workflow_id=job.workflow_id,+ )+++class TestSweepStoppedSchemaSyncs:+ @pytest.mark.parametrize("deleted", [False, True], ids=["disabled", "deleted"])+ def test_sweep_dispatches_teardown_only_for_stopped_schemas_with_running_jobs(self, deleted, team):+ stopped_schema, _running_job = _create_schema_with_running_job(team)+ _healthy_schema, _healthy_job = _create_schema_with_running_job(team)+ idle_schema, idle_job = _create_schema_with_running_job(team)+ idle_job.status = ExternalDataJob.Status.COMPLETED+ idle_job.save()+ fresh_schema, _fresh_job = _create_schema_with_running_job(team)+ old_schema, old_job = _create_schema_with_running_job(team)++ update = {"deleted": True} if deleted else {"should_sync": False}+ ExternalDataSchema.objects.filter(+ pk__in=[stopped_schema.pk, idle_schema.pk, fresh_schema.pk, old_schema.pk]+ ).update(**update)++ # fresh_schema keeps its just-created updated_at (inside the grace window); the+ # rest are backdated past it. old_job predates the sweep's max age.+ now = timezone.now()+ ExternalDataSchema.objects.exclude(pk=fresh_schema.pk).update(+ updated_at=now - STOPPED_SYNC_SWEEP_GRACE - timedelta(minutes=1)+ )+ ExternalDataJob.objects.filter(pk=old_job.pk).update(+ created_at=now - STOPPED_SYNC_SWEEP_MAX_JOB_AGE - timedelta(days=1)+ )++ with patch(TASK_DELAY) as mock_delay:+ sweep_stopped_schema_syncs()++ mock_delay.assert_called_once_with(+ team_id=team.pk,+ schema_id=str(stopped_schema.id),+ reason=SCHEMA_DELETED_JOB_ERROR if deleted else SYNC_DISABLED_JOB_ERROR,+ )++[email protected](autouse=True)+def _keep_test_connection():+ # The reused consumer fail path calls close_old_connections(), which closes the+ # pytest-django test connection out from under the test transaction.+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.close_old_connections"+ ):+ yield+++def queue_conn() -> Generator[psycopg.Connection[Any]]:+ url = _get_test_database_url()+ with psycopg.connect(url, autocommit=True) as conn:+ _ensure_tables(conn)+ _truncate_tables(conn)+ with patch("products.warehouse_sources.backend.sync_teardown.WAREHOUSE_SOURCES_DATABASE_URL", url):+ yield conn+++def fake_redis():+ client = fakeredis.FakeRedis()++ @contextmanager+ def _fake_client():+ yield client++ with patch.object(sync_lock, "_get_redis_client", _fake_client):+ yield client+++class TestCleanupTaskReenableGuard:+ @pytest.mark.parametrize("syncing_again", [True, False], ids=["reenabled_skips", "disabled_proceeds"])+ def test_stale_dispatch_leaves_a_reenabled_schema_alone(self, syncing_again, team, queue_conn, fake_redis):+ _, schema, job = _create_pipeline(team)+ if not syncing_again:+ ExternalDataSchema.objects.filter(pk=schema.pk).update(should_sync=False)++ with patch("products.data_warehouse.backend.facade.api.cancel_external_data_workflow") as mock_cancel:+ cleanup_disabled_external_data_schema(+ team_id=team.pk, schema_id=str(schema.id), reason=SYNC_DISABLED_JOB_ERROR+ )++ job.refresh_from_db()+ if syncing_again:+ assert job.status == ExternalDataJob.Status.RUNNING+ mock_cancel.assert_not_called()+ else:+ assert job.status == ExternalDataJob.Status.FAILED+ mock_cancel.assert_called_once_with(job.workflow_id)+++class TestTeardownSchemaSyncs:+ def test_fails_batches_finalizes_job_releases_locks_and_cancels_workflow(self, team, queue_conn, fake_redis):+ _, schema, job = _create_pipeline(team)+ run_uuid = str(uuid4())+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid)+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)+ assert job.workflow_run_id is not None+ assert sync_lock.acquire_v3_pipeline_lock(team.pk, str(schema.id), job.workflow_run_id)++ with patch("products.data_warehouse.backend.facade.api.cancel_external_data_workflow") as mock_cancel:+ teardown_schema_syncs(team_id=team.pk, schema_id=str(schema.id), reason="stopped for test")++ assert _failed_status_counts_by_run(queue_conn) == {run_uuid: 2}+ job.refresh_from_db()+ assert job.status == ExternalDataJob.Status.FAILED+ assert job.latest_error == "stopped for test"+ assert _lease_count(queue_conn, str(schema.id)) == 0+ assert sync_lock.get_v3_pipeline_lock_holder(team.pk, str(schema.id)) is None+ mock_cancel.assert_called_once_with(job.workflow_id)++ def test_exclude_workflow_skips_cancel_but_still_fails_batches(self, team, queue_conn, fake_redis):+ _, schema, job = _create_pipeline(team)+ run_uuid = str(uuid4())+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid)++ with patch("products.data_warehouse.backend.facade.api.cancel_external_data_workflow") as mock_cancel:+ teardown_schema_syncs(+ team_id=team.pk,+ schema_id=str(schema.id),+ reason="stopped for test",+ exclude_workflow_id=job.workflow_id,+ )++ mock_cancel.assert_not_called()+ assert _failed_status_counts_by_run(queue_conn) == {run_uuid: 2}+ job.refresh_from_db()+ assert job.status == ExternalDataJob.Status.FAILED++ def test_running_job_without_queue_batches_is_finalized(self, team, queue_conn, fake_redis):+ _, schema, job = _create_pipeline(team)++ with patch("products.data_warehouse.backend.facade.api.cancel_external_data_workflow") as mock_cancel:+ teardown_schema_syncs(team_id=team.pk, schema_id=str(schema.id), reason="stopped for test")++ job.refresh_from_db()+ assert job.status == ExternalDataJob.Status.FAILED+ mock_cancel.assert_called_once_with(job.workflow_id)++ def test_second_run_is_a_noop(self, team, queue_conn, fake_redis):+ _, schema, job = _create_pipeline(team)+ run_uuid = str(uuid4())+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid)++ with patch("products.data_warehouse.backend.facade.api.cancel_external_data_workflow") as mock_cancel:+ teardown_schema_syncs(team_id=team.pk, schema_id=str(schema.id), reason="first reason")+ second = teardown_schema_syncs(team_id=team.pk, schema_id=str(schema.id), reason="second reason")++ # No pending batches remain, the job is already terminal, and the finished+ # workflow is not re-cancelled, so the retry changes nothing.+ assert _failed_status_counts_by_run(queue_conn) == {run_uuid: 2}+ job.refresh_from_db()+ assert job.latest_error == "first reason"+ assert second.batches_failed == 0+ assert second.jobs_finalized == 0+ assert mock_cancel.call_count == 1