Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse-sources): keep halted cdc tables visibly failed (#104759)

Daniel RC451a81a639d6
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index 3549002a0751..c71d86dba565 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
auto_enable_new_schemas,
get_all_schemas_for_source_id,
get_schemas_for_direct_reconciliation,
+ mark_schema_running_unless_halted,
sync_frequency_interval_to_sync_frequency,
sync_frequency_to_sync_frequency_interval,
sync_old_schemas_with_new_schemas,
@@ -123,6 +124,7 @@ __all__ = [
"sync_frequency_to_sync_frequency_interval",
"sync_old_schemas_with_new_schemas",
"update_should_sync",
+ "mark_schema_running_unless_halted",
"update_sync_type_config_keys",
"validate_source_prefix",
"validate_warehouse_table_url_pattern",
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 6e7f6ab0b9a9..202e26effb6f 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1558,6 +1558,24 @@ def complete_schema_run(schema: ExternalDataSchema, *, last_synced_at: datetime)
return repainted
+def mark_schema_running_unless_halted(schema: ExternalDataSchema) -> bool:
+ """Paint a schema Running at the start of a run, unless a CDC halt marker holds.
+
+ A halted schema absorbs every later status update, so Running painted over it would hide its
+ FAILED status and error until the marker clears. One conditional UPDATE: a marker written
+ under the row lock either commits first and blocks this, or commits after and repaints FAILED.
+ """
+ updated = (
+ ExternalDataSchema.objects.filter(id=schema.id, team_id=schema.team_id)
+ .exclude(sync_type_config__has_key="cdc_broken")
+ .exclude(sync_type_config__has_key="cdc_extraction_paused")
+ .update(status=ExternalDataSchema.Status.RUNNING, updated_at=timezone.now())
+ )
+ if updated:
+ schema.status = ExternalDataSchema.Status.RUNNING
+ return bool(updated)
+
+
def mark_initial_sync_complete(schema_id: str | uuid.UUID, team_id: int) -> None:
"""Mark a schema's first successful sync complete. Shared by the V2 pipelines and the V3 loader.
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index 8ea7769eda00..30c8e455f648 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -47,6 +47,7 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSchema,
ExternalDataSchemaDestination,
ExternalDataSource,
+ mark_schema_running_unless_halted,
resolve_destinations,
sync_frequency_interval_to_sync_frequency,
sync_frequency_to_sync_frequency_interval,
@@ -195,8 +196,7 @@ def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:
)
return
- instance.status = ExternalDataSchema.Status.RUNNING
- instance.save(update_fields=["status", "updated_at"])
+ mark_schema_running_unless_halted(instance)
# A schedule divides the sync time of day by the cadence, so a null interval cannot build one.
@@ -1812,8 +1812,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
logger.exception(f"Could not trigger external data job for schema {instance.id}", exc_info=e)
raise
- instance.status = ExternalDataSchema.Status.RUNNING
- instance.save()
+ mark_schema_running_unless_halted(instance)
return Response(status=status.HTTP_200_OK)
@extend_schema(
@@ -1888,8 +1887,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=status.HTTP_400_BAD_REQUEST,
)
- instance.status = ExternalDataSchema.Status.RUNNING
- instance.save(update_fields=["status", "updated_at"])
+ mark_schema_running_unless_halted(instance)
return Response(status=status.HTTP_200_OK)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index 946a664d6770..1675d5048044 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
complete_schema_run,
+ mark_schema_running_unless_halted,
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -55,7 +56,11 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
enrich_delete_rows,
enrich_toast_omitted_rows,
)
-from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import mark_cdc_broken
+from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import (
+ SELF_MANAGED_LAG_REASON,
+ clear_recovered_self_managed_lag,
+ mark_cdc_broken,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
CDCBufferWriter,
is_shadow_write_enabled,
@@ -1046,11 +1051,7 @@ class CDCExtractActivity:
def _mark_schemas_running(self) -> None:
"""Mark CDC schemas as Running at the start."""
for schema in self.cdc_schemas:
- schema.status = ExternalDataSchema.Status.RUNNING
- # skip_activity_log avoids the extra _get_before_update SELECT, which raises
- # OperationalError when the transaction pooler has dropped the connection since the
- # last activity attempt — see ExternalDataSchema.save.
- schema.save(update_fields=["status", "updated_at"], skip_activity_log=True)
+ mark_schema_running_unless_halted(schema)
def _reconcile_orphaned_prior_jobs(self) -> None:
"""Finalize this source's prior RUNNING jobs that were stranded mid-run.
@@ -1896,6 +1897,10 @@ class CDCExtractActivity:
# Repainting COMPLETED here would erase a failing consumer run within one capture tick,
# hiding a buffer backlog until its files hit the S3 TTL — which is unrecoverable.
if schema.name in self._buffered_table_names:
+ # A completed tick proves extraction runs again. The consumer cannot clear this
+ # marker: its job completions are absorbed while the marker holds.
+ if (schema.sync_type_config or {}).get("cdc_extraction_paused"):
+ self._update_schema_sync_type_config(schema, removes=["cdc_extraction_paused"])
return False
if not complete_schema_run(schema, last_synced_at=now):
self._schema_log(schema).info("cdc_success_repaint_skipped_broken")
@@ -2094,7 +2099,7 @@ def cleanup_orphan_slots_activity() -> None:
try:
mark_cdc_broken(
source,
- "critical_lag_self_managed",
+ SELF_MANAGED_LAG_REASON,
f"Change data capture replication lag exceeded {critical_threshold_mb} MB. "
f"This slot is self-managed, so PostHog did not drop it — reduce load or WAL "
f"retention on the source database, or it may invalidate the slot and "
@@ -2113,6 +2118,15 @@ def cleanup_orphan_slots_activity() -> None:
lag_mb=round(lag_mb, 1),
threshold_mb=cdc_config.lag_warning_threshold_mb,
)
+ elif cdc_config.management_mode == "self_managed":
+ try:
+ cleared = clear_recovered_self_managed_lag(source)
+ if cleared:
+ source_log.info("slot_lag_recovered_self_managed", lag_mb=round(lag_mb, 1), schemas=cleared)
+ except Exception:
+ source_log.exception("failed_to_clear_recovered_lag")
+ metrics.get_sweeper_source_errors_metric().add(1)
+ sources_errored += 1
source_log.info(
"slot_lag_checked",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
index 63549d1fd48b..19dee2f0ecfc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
@@ -19,6 +19,8 @@ from __future__ import annotations
import typing
import datetime as dt
+from django.db import transaction
+
import structlog
import posthoganalytics
@@ -36,6 +38,8 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
logger = structlog.get_logger(__name__)
+SELF_MANAGED_LAG_REASON = "critical_lag_self_managed"
+
def mark_cdc_broken(
source: ExternalDataSource,
@@ -58,37 +62,41 @@ def mark_cdc_broken(
"""
log = logger.bind(source_id=str(source.id), team_id=source.team_id, reason=reason)
- source.status = ExternalDataSource.Status.ERROR
- source.save(update_fields=["status", "updated_at"])
-
broken_marker = {"reason": reason, "at": dt.datetime.now(tz=dt.UTC).isoformat(), **extra}
- cdc_schemas = list(
- ExternalDataSchema.objects.filter(
- source=source,
- sync_type=ExternalDataSchema.SyncType.CDC,
- should_sync=True,
- ).exclude(deleted=True)
- )
- # The sweeper re-marks an unrepaired source on every sweep while the condition persists.
- # Report once: only schemas newly entering this broken state produce failure-digest
- # evidence, otherwise an ongoing condition would re-email the team daily and pile a
- # synthetic FAILED run per sweep onto the Syncs tab.
- newly_broken = [
- schema
- for schema in cdc_schemas
- if ((schema.sync_type_config or {}).get("cdc_broken") or {}).get("reason") != reason
- ]
- for schema in cdc_schemas:
- # Locked merge so a concurrent API PATCH of sync_type_config can't clobber the marker.
- update_sync_type_config_keys(
- schema.id,
- source.team_id,
- updates={"cdc_broken": broken_marker},
- extra_model_fields={
- "status": ExternalDataSchema.Status.FAILED,
- "latest_error": message,
- },
+ # The source row lock serializes this with clear_recovered_self_managed_lag, which must not
+ # see the source status and the markers half-written.
+ with transaction.atomic():
+ ExternalDataSource.objects.select_for_update(of=("self",)).get(id=source.id, team_id=source.team_id)
+ source.status = ExternalDataSource.Status.ERROR
+ source.save(update_fields=["status", "updated_at"])
+
+ cdc_schemas = list(
+ ExternalDataSchema.objects.filter(
+ source=source,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ ).exclude(deleted=True)
)
+ # The sweeper re-marks an unrepaired source on every sweep while the condition persists.
+ # Report once: only schemas newly entering this broken state produce failure-digest
+ # evidence, otherwise an ongoing condition would re-email the team daily and pile a
+ # synthetic FAILED run per sweep onto the Syncs tab.
+ newly_broken = [
+ schema
+ for schema in cdc_schemas
+ if ((schema.sync_type_config or {}).get("cdc_broken") or {}).get("reason") != reason
+ ]
+ for schema in cdc_schemas:
+ # Locked merge so a concurrent API PATCH of sync_type_config can't clobber the marker.
+ update_sync_type_config_keys(
+ schema.id,
+ source.team_id,
+ updates={"cdc_broken": broken_marker},
+ extra_model_fields={
+ "status": ExternalDataSchema.Status.FAILED,
+ "latest_error": message,
+ },
+ )
if pause:
_pause_schedule(source, log)
@@ -107,6 +115,42 @@ def mark_cdc_broken(
log.warning("cdc_marked_broken", schemas=len(cdc_schemas), newly_broken=len(newly_broken), paused=pause)
+def clear_recovered_self_managed_lag(source: ExternalDataSource) -> int:
+ """Lift the ``critical_lag_self_managed`` marker once the slot's lag is back under the warning threshold.
+
+ PostHog never drops a self-managed slot, so this marker reports a condition, not lost state.
+ Left in place it keeps absorbing every status update and makes resume refuse the source,
+ long after the customer has recovered. Returns how many schemas were cleared.
+ """
+
+ def _clear(config: dict[str, typing.Any]) -> None:
+ if (config.get("cdc_broken") or {}).get("reason") == SELF_MANAGED_LAG_REASON:
+ config.pop("cdc_broken")
+
+ marked = ExternalDataSchema.objects.filter(
+ team_id=source.team_id, source=source, sync_type_config__cdc_broken__reason=SELF_MANAGED_LAG_REASON
+ )
+ if not marked.exists():
+ return 0
+ # Source lock first, the order mark_cdc_broken takes, so a concurrent re-mark cannot interleave.
+ with transaction.atomic():
+ locked = ExternalDataSource.objects.select_for_update(of=("self",)).get(id=source.id, team_id=source.team_id)
+ schema_ids = list(
+ ExternalDataSchema.objects.filter(
+ team_id=source.team_id, source=source, sync_type_config__cdc_broken__reason=SELF_MANAGED_LAG_REASON
+ ).values_list("id", flat=True)
+ )
+ for schema_id in schema_ids:
+ update_sync_type_config_keys(schema_id, source.team_id, mutate=_clear)
+ still_broken = ExternalDataSchema.objects.filter(
+ team_id=source.team_id, source=source, sync_type_config__has_key="cdc_broken"
+ ).exists()
+ if schema_ids and not still_broken:
+ locked.status = ExternalDataSource.Status.RUNNING
+ locked.save(update_fields=["status", "updated_at"])
+ return len(schema_ids)
+
+
def _create_failure_visibility_jobs(
source: ExternalDataSource,
cdc_schemas: list[ExternalDataSchema],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
index 267102962669..d371f6ef6f64 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
@@ -163,6 +163,30 @@ def test_critical_lag_posthog_auto_drop_marks_broken_and_pauses(team):
mock_pause.assert_called_once_with(str(source.id))
+ "reason, lag_mb, cleared",
+ [
+ ("critical_lag_self_managed", 10, True),
+ ("critical_lag_self_managed", 1500, False),
+ ("auth_failed", 10, False),
+ ],
+)
+def test_self_managed_lag_marker_clears_once_lag_recovers(team, reason, lag_mb, cleared):
+ source = _create_source(team, job_inputs=_cdc_job_inputs(management="self_managed"))
+ source.status = ExternalDataSource.Status.ERROR
+ source.save()
+ schema = _create_cdc_schema(team, source)
+ schema.sync_type_config = {**schema.sync_type_config, "cdc_broken": {"reason": reason}}
+ schema.save()
+
+ _run(_mock_adapter(lag_bytes=lag_mb * 1024 * 1024))
+
+ schema.refresh_from_db()
+ source.refresh_from_db()
+ assert ("cdc_broken" not in schema.sync_type_config) is cleared
+ assert (source.status == ExternalDataSource.Status.RUNNING) is cleared
+
+
def test_critical_lag_auto_drop_disabled_does_not_drop(team):
# cdc_auto_drop_slot stored as boolean False round-trips to "False"; str_to_bool must
# decode it as False so the safety net stays off.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
index d75de837f520..e0376a368c0d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -113,6 +113,7 @@ def _make_schema(
schema.partition_count = partition_count
schema.partition_size = partition_size
schema.save = MagicMock()
+ type(schema).cdc_halted = ExternalDataSchema.cdc_halted
return schema
@@ -151,10 +152,23 @@ def _fake_complete_schema_run(schema, *, last_synced_at):
return True
+def _fake_mark_schema_running_unless_halted(schema):
+ """Stand-in for mark_schema_running_unless_halted on the in-memory mock schema. The real
+ conditional update is covered by tests/test_models.py::TestMarkSchemaRunningUnlessHalted."""
+ if schema.cdc_halted:
+ return False
+ schema.status = ExternalDataSchema.Status.RUNNING
+ return True
+
+
@pytest.fixture(autouse=True)
def _stub_sync_type_config_merge():
"""Route every activity sync_type_config write onto the in-memory mock schema (no DB)."""
with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_schema_running_unless_halted",
+ side_effect=_fake_mark_schema_running_unless_halted,
+ ),
patch.object(
CDCExtractActivity,
"_update_schema_sync_type_config",
@@ -437,22 +451,6 @@ class TestBackpressureGuard:
assert act.reader is None
-class TestMarkSchemasRunning:
- def test_skips_activity_log_to_avoid_stale_pooled_connection(self):
- # A previous attempt may have left the pooler connection stale; the extra
- # _get_before_update SELECT that activity logging would run raises OperationalError
- # ("the connection is closed") on it, failing the run before extraction even starts.
- source = _make_source()
- act = _make_extract_activity(source)
- schema = _make_schema("users", source=source)
- act.cdc_schemas = [schema]
-
- act._mark_schemas_running()
-
- assert schema.status == ExternalDataSchema.Status.RUNNING
- schema.save.assert_called_once_with(update_fields=["status", "updated_at"], skip_activity_log=True)
-
-
class TestFlushDeferredRuns:
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.PostgresProducer")
def test_sends_kafka_messages_for_deferred_runs(self, MockProducer):
@@ -1053,7 +1051,6 @@ class TestCDCExtractActivity:
mock_reader.close.assert_called_once()
# Schema marked completed even with no changes
- schema.save.assert_called()
assert schema.status == "Completed"
assert schema.latest_error is None
assert schema.last_synced_at is not None
@@ -3257,6 +3254,19 @@ class TestSuccessRepaintGuards:
# digest email reporting "paused, action required".
assert "cdc_extraction_paused" not in recovered.sync_type_config
+ def test_a_buffered_schema_clears_its_pause_marker_but_keeps_the_consumers_status(self):
+ source = _make_source()
+ buffered = _make_schema("buffered_table", source=source)
+ buffered.status = ExternalDataSchema.Status.FAILED
+ buffered.sync_type_config["cdc_extraction_paused"] = {"reason": "transaction_too_large"}
+ act = self._activity_with(buffered)
+ act._buffered_table_names = {"buffered_table"}
+
+ act._finalize_success()
+
+ assert "cdc_extraction_paused" not in buffered.sync_type_config
+ assert buffered.status == ExternalDataSchema.Status.FAILED
+
class TestCDCBoundedReadLoop:
"""The read loop peeks at most CDC_MAX_CHANGES_PER_READ changes per pass, advancing the slot
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
index 27c1e39010f1..ee8decad8a79 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
@@ -142,6 +142,7 @@ def _extract_patches(source, schemas, events):
patch.object(CDCExtractActivity, "_update_schema_sync_type_config"),
# The success repaint runs a locked DB transaction; these metric smoke tests are DB-less.
patch(f"{_ACTIVITIES}.complete_schema_run", return_value=True),
+ patch(f"{_ACTIVITIES}.mark_schema_running_unless_halted", return_value=True),
patch(f"{_ACTIVITIES}.get_cdc_adapter", return_value=adapter),
patch(f"{_ACTIVITIES}.S3BatchWriter", return_value=s3),
patch(f"{_ACTIVITIES}.PostgresProducer"),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index bd9f6670f6f4..eb034715bba3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -22,7 +22,10 @@ from products.data_warehouse.backend.facade.api import delete_external_data_sche
from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation
from products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatistics
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.models.external_data_schema import (
+ ExternalDataSchema,
+ mark_schema_running_unless_halted,
+)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import HIDDEN_COLUMNS, DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.destinations.enablement import (
@@ -342,10 +345,6 @@ def create_external_data_job_model_activity(
pipeline_version = ExternalDataJob.PipelineVersion.V3
_verify_v3_lock_still_held(inputs.team_id, inputs.schema_id)
- # Persist the Running status only after the job row exists: a Running schema with no job
- # behind it can never be finalized, so it would stay stuck on Running forever. With the job
- # committed first, the workflow's finalizer can always resolve it and repaint the schema.
- schema.status = ExternalDataSchema.Status.RUNNING
# Only v3 runs deliver to destinations; v2 has no per-batch queue to carry the ids.
destination_ids: list[str] = []
if pipeline_version == ExternalDataJob.PipelineVersion.V3 and is_multi_destination_enabled(
@@ -361,7 +360,10 @@ def create_external_data_job_model_activity(
schema_snapshot=_build_schema_snapshot(schema),
destination_ids=destination_ids,
)
- schema.save(update_fields=["status", "updated_at"])
+ # Persist the Running status only after the job row exists: a Running schema with no job
+ # behind it can never be finalized, so it would stay stuck on Running forever. With the job
+ # committed first, the workflow's finalizer can always resolve it and repaint the schema.
+ mark_schema_running_unless_halted(schema)
logger.info(
f"Created external data job for external data source {inputs.source_id}",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
index c0afce3025c9..77b5cd305723 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
@@ -274,6 +274,30 @@ class TestCreateJobActivityStatusOrdering:
schema.refresh_from_db()
assert schema.status == ExternalDataSchema.Status.FAILED
+ @parameterized.expand([("broken", "cdc_broken"), ("paused", "cdc_extraction_paused")])
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}.activity")
+ def test_a_halted_cdc_schema_keeps_its_failed_status(
+ self, _name: str, marker: str, mock_activity: MagicMock, _mock_close_connections: MagicMock
+ ) -> None:
+ mock_activity.info.return_value.workflow_id = "wf-1"
+ mock_activity.info.return_value.workflow_run_id = "run-1"
+ team = _team()
+ schema = _schema(team, None)
+ schema.status = ExternalDataSchema.Status.FAILED
+ schema.sync_type_config = {marker: {"reason": "critical_lag_self_managed"}}
+ schema.save()
+
+ create_external_data_job_model_activity(
+ CreateExternalDataJobModelActivityInputs(
+ team_id=team.id, schema_id=schema.id, source_id=schema.source_id, billable=True
+ )
+ )
+
+ schema.refresh_from_db()
+ assert ExternalDataJob.objects.filter(schema_id=schema.id).exists()
+ assert schema.status == ExternalDataSchema.Status.FAILED
+
@pytest.mark.django_db
class TestCreateJobActivityDeletedSourceOrSchema:
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
index aa192ba865ce..d1ec725ce709 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py
@@ -90,6 +90,37 @@ class TestExternalDataSchema(APIBaseTest):
self.postgres_config = postgres_config
self.temporal = temporal
+ @parameterized.expand(
+ [
+ ("healthy", {}, ExternalDataSchema.Status.RUNNING),
+ (
+ "halted",
+ {"cdc_extraction_paused": {"reason": "transaction_too_large"}},
+ ExternalDataSchema.Status.FAILED,
+ ),
+ ]
+ )
+ def test_sync_now_leaves_a_halted_cdc_schema_failed(self, _name: str, config: dict, expected: str) -> None:
+ source = ExternalDataSource.objects.create(team=self.team, source_type=ExternalDataSourceType.POSTGRES)
+ schema = ExternalDataSchema.objects.create(
+ name="users",
+ team=self.team,
+ source=source,
+ should_sync=True,
+ status=ExternalDataSchema.Status.FAILED,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ sync_type_config=config,
+ )
+
+ with mock.patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_schema._trigger_schema_sync"
+ ):
+ response = self.client.post(f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/reload/")
+
+ assert response.status_code == 200, response.content
+ schema.refresh_from_db()
+ assert schema.status == expected
+
def test_incremental_fields_stripe(self):
source = ExternalDataSource.objects.create(
team=self.team,
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 5fa5dfbbcf43..d8717a1fcf75 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
apply_incremental_lookback,
complete_schema_run,
mark_initial_sync_complete,
+ mark_schema_running_unless_halted,
process_incremental_value,
update_sync_type_config_keys,
)
@@ -785,6 +786,42 @@ class TestMarkInitialSyncComplete(BaseTest):
assert schema.sync_type_config == expected_config
+class TestMarkSchemaRunningUnlessHalted(BaseTest):
+ @parameterized.expand(
+ [
+ ("healthy", {}, True),
+ ("broken", {"cdc_broken": {"reason": "critical_lag_self_managed"}}, False),
+ ("paused", {"cdc_extraction_paused": {"reason": "transaction_too_large"}}, False),
+ ]
+ )
+ def test_only_a_schema_without_a_halt_marker_is_painted_running(
+ self, _name: str, sync_type_config: dict, painted: bool
+ ) -> None:
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+ schema = ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source=source,
+ name="users",
+ sync_type="cdc",
+ sync_type_config=sync_type_config,
+ status=ExternalDataSchema.Status.FAILED,
+ )
+ stale = ExternalDataSchema.objects.get(id=schema.id)
+ stale.sync_type_config = {}
+
+ assert mark_schema_running_unless_halted(stale) is painted
+
+ schema.refresh_from_db()
+ expected = ExternalDataSchema.Status.RUNNING if painted else ExternalDataSchema.Status.FAILED
+ assert schema.status == expected
+
+
class TestCompleteSchemaRun(BaseTest):
"""The success repaint checks the broken marker under the row lock: the sweeper can mark the
source broken while a run is in flight, and an unlocked check on a stale instance would