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 a broken cdc source's tables paused on edit (#111826)

Daniel RCb758ddfd3105
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index 4beff66b2198..7ca9564ed398 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -59,6 +59,9 @@ Recovery clears the flag once the slot is back, and so does any read that succee
A resync, a table-mode switch, re-enabling a table's sync, and Repair CDC use the same key: when a sync of the table can still hand over, they pause its schedule and leave the reset to capture, which also starts the new snapshot.
They then start a capture run right away, and recreate the capture schedule if it is gone, so the reset does not wait for the next tick. A source that is marked broken, or whose capture is paused after a non-retryable error, is left alone: Repair CDC or resuming capture restarts it.
A table edit or a sync frequency change rewrites the capture schedule too, and it keeps the pause, so it does not restart capture on such a source either.
+A table edit leaves the table's own schedule as it is while a broken marker holds the source's tables for Repair CDC: turning the table's sync on does not unpause it, and a frequency change keeps whatever pause the schedule has.
+Self-managed critical lag and a billing stop that kept the slot do not pause table schedules, so an edit under those markers leaves them running.
+While a repair holds the source's lock, an edit gets no such hold, because the repair has already listed the tables it will resume.
Once slot-invalidation recovery has recreated the slot, it removes the markers of the lost slot (`auto_dropped_critical_lag`, `slot_missing`, `publication_missing`), so its tables stop reading as halted. A failed recreation keeps them.
Each write that stages a reset gives the key a new `generation`, so capture drops only the reset it finished, even when a request stages the same reset again while that snapshot starts.
The admin resync refuses instead, because it starts its own non-billable run, so it asks the operator to retry once the sync stops.
diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.py
index 8e6f206d0254..5b58927e1886 100644
--- a/products/data_warehouse/backend/logic/data_load/service.py
+++ b/products/data_warehouse/backend/logic/data_load/service.py
@@ -160,12 +160,14 @@ def sync_external_data_job_workflow(
create: bool = False,
should_sync: bool = True,
trigger_immediately: bool = True,
+ keep_paused: bool = False,
) -> ExternalDataSchema:
"""Create or update the schema's Temporal schedule.
Runs fired through the schedule use its stored action, whose `billable` is always True,
so callers that must not bill (e.g. admin recovery) pass trigger_immediately=False and
- start their own ad-hoc run if one is needed.
+ start their own ad-hoc run if one is needed. `keep_paused` makes an update leave an existing
+ pause in place, whatever `should_sync` says.
"""
temporal = sync_connect()
@@ -181,7 +183,7 @@ def sync_external_data_job_workflow(
if trigger_immediately:
trigger_schedule(temporal, schedule_id=str(external_data_schema.id))
else:
- update_schedule(temporal, id=str(external_data_schema.id), schedule=schedule)
+ update_schedule(temporal, id=str(external_data_schema.id), schedule=schedule, keep_paused=keep_paused)
return external_data_schema
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 210ec41667ba..00574d30a6a6 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -23,7 +23,9 @@ _LAZY = {
"CDCRepairError": "cdc.repair",
"CDCRepairInProgress": "cdc.repair",
"repair_cdc_source": "cdc.repair",
+ "repair_is_running": "cdc.repair",
"SELF_MANAGED_LAG_REASON": "cdc.broken",
+ "tables_wait_for_repair": "cdc.broken",
"purge_buffer_prefix": "cdc.buffer",
"CDC_SEQ_COLUMN": "cdc.batcher",
"BUFFER_LANE": "cdc.snapshot_lane",
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 c3a12961499e..d71a50442458 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -70,8 +70,10 @@ from products.warehouse_sources.backend.facade.source_management import (
get_cdc_adapter,
hand_reset_to_capture_if_sync_running,
purge_buffer_prefix,
+ repair_is_running,
resnapshot_stays_in_buffer,
source_type_supports_cdc,
+ tables_wait_for_repair,
validate_and_coerce_row_filters,
)
from products.warehouse_sources.backend.facade.types import (
@@ -1394,12 +1396,30 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
should_sync_value = should_sync if should_sync is not None else updated_instance.should_sync
# A reset left to capture keeps the schedule paused, and capture unpauses it once the reset is done.
reset_pending = bool((updated_instance.sync_type_config or {}).get(CDC_RESET_PENDING_KEY))
+ # Repair CDC unpauses the tables of a broken source, so an edit must not. A repair that
+ # is already running has listed its tables, so a table turned on now gets no hold. The
+ # lock is read first: a repair clears the markers before it releases the lock, so
+ # markers read after a free lock belong to no repair that is about to end.
+ repair_running = updated_instance.is_cdc and repair_is_running(source)
+ source_is_broken = updated_instance.is_cdc and tables_wait_for_repair(source)
+ waits_for_repair = source_is_broken and not repair_running
+ held = reset_pending or waits_for_repair
schedule_exists = external_data_workflow_exists(str(updated_instance.id))
if schedule_exists:
if should_sync is False:
pause_external_data_schedule(str(updated_instance.id))
- elif (should_sync is True or (resume_paused_schedule and should_sync_value)) and not reset_pending:
+ elif (should_sync is True or (resume_paused_schedule and should_sync_value)) and not held:
+ unpause_external_data_schedule(str(updated_instance.id))
+ elif should_sync_value and waits_for_repair:
+ # Repair CDC unpauses a schedule but cannot create one, and a new schedule's
+ # first run would start even while it is paused.
+ sync_external_data_job_workflow(
+ updated_instance, create=True, should_sync=False, trigger_immediately=False
+ )
+ # A repair that started after the checks above may have resumed its tables
+ # before this schedule existed, and it does not come back for it.
+ if not reset_pending and (repair_is_running(source) or not tables_wait_for_repair(source)):
unpause_external_data_schedule(str(updated_instance.id))
elif should_sync_value:
# No schedule yet but the schema should be syncing — create (or recover) it. The
@@ -1413,9 +1433,16 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
# schedule has nothing to update — updating a missing schedule raises "workflow not
# found" — so its new cadence is just saved and applies if/when it is enabled.
if (was_sync_frequency_updated or was_sync_time_of_day_updated) and schedule_exists:
- sync_external_data_job_workflow(
- updated_instance, create=False, should_sync=should_sync_value and not reset_pending
- )
+ if source_is_broken:
+ # The pause stays as it is, because a repair may have resumed the table
+ # since the check above, and one that fails must not find it running.
+ sync_external_data_job_workflow(
+ updated_instance, create=False, should_sync=should_sync_value, keep_paused=True
+ )
+ else:
+ sync_external_data_job_workflow(
+ updated_instance, create=False, should_sync=should_sync_value and not reset_pending
+ )
self._run_temporal_side_effect(update_schedule)
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 982dfa9d66cc..53c3beead768 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
@@ -145,6 +145,27 @@ def broken_for_another_reason(source: ExternalDataSource, reason: str) -> bool:
)
+def tables_wait_for_repair(source: ExternalDataSource) -> bool:
+ """Whether a broken marker holds this source's CDC table schedules paused, for Repair CDC to unpause.
+
+ A marker set with `pause=False` leaves the schedules running, so it does not count: self-managed
+ critical lag, and a billing stop that kept the slot. A table with sync off counts, because every
+ path that lifts a marker lifts it from those tables too.
+ """
+ return (
+ ExternalDataSchema.objects.filter(
+ team_id=source.team_id,
+ source=source,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ sync_type_config__has_key="cdc_broken",
+ )
+ .exclude(deleted=True)
+ .exclude(sync_type_config__cdc_broken__reason=SELF_MANAGED_LAG_REASON)
+ .exclude(sync_type_config__cdc_broken__has_key="slot_kept")
+ .exists()
+ )
+
+
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.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
index ccb9d998729a..86f24d60e8ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
@@ -63,6 +63,11 @@ def _repair_lock_key(source_id: str) -> str:
return f"cdc_repair_lock:{source_id}"
+def repair_is_running(source: ExternalDataSource) -> bool:
+ """Whether a repair of this source holds its lock."""
+ return bool(get_client().exists(_repair_lock_key(str(source.id))))
+
+
def repair_cdc_source(source: ExternalDataSource) -> int:
"""Repair CDC on a source whose change-stream resources were lost.
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 4e71c5327620..0b9cccc892f8 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
@@ -25,10 +25,15 @@ from posthog.api.test.test_user import create_user
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.utils import generate_random_token_personal
-from posthog.temporal.common.schedule import describe_schedule
+from posthog.redis import get_client
+from posthog.temporal.common.schedule import create_schedule, describe_schedule
from products.data_modeling.backend.facade.models import Edge, Node
-from products.data_warehouse.backend.facade.api import DIRECT_POSTGRES_URL_PATTERN, DIRECT_SNOWFLAKE_URL_PATTERN
+from products.data_warehouse.backend.facade.api import (
+ DIRECT_POSTGRES_URL_PATTERN,
+ DIRECT_SNOWFLAKE_URL_PATTERN,
+ sync_external_data_job_workflow,
+)
from products.data_warehouse.backend.facade.contracts import WebhookHogFunctionCreateResult
from products.warehouse_sources.backend.facade.models import (
DataWarehouseTable,
@@ -38,6 +43,7 @@ from products.warehouse_sources.backend.facade.models import (
)
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
from products.warehouse_sources.backend.presentation.views.external_data_schema import schema_display_status
+from products.warehouse_sources.backend.temporal.data_imports.cdc.repair import _repair_lock_key
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
VersionDeprecation,
WebhookCreationResult,
@@ -3218,6 +3224,233 @@ class TestUpdateExternalDataSchema:
schedule_desc = describe_schedule(temporal, str(schema.id))
assert schedule_desc.schedule.spec.intervals[0].every == timedelta(days=7)
+ @pytest.mark.parametrize(
+ "marker, marked_table_sync_type, synced_before, payload, runs",
+ [
+ pytest.param(
+ {"reason": "auto_dropped_critical_lag"},
+ "cdc",
+ True,
+ {"sync_frequency": "1hour"},
+ False,
+ id="frequency_change_on_a_broken_source",
+ ),
+ pytest.param(
+ {"reason": "auto_dropped_critical_lag"},
+ "cdc",
+ False,
+ {"should_sync": True},
+ False,
+ id="sync_turned_on_on_a_broken_source",
+ ),
+ pytest.param(
+ {"reason": "auto_dropped_critical_lag"},
+ "cdc",
+ True,
+ {"sync_frequency": "1hour"},
+ True,
+ id="frequency_change_after_a_repair_resumed_the_table",
+ ),
+ pytest.param(
+ {"reason": "critical_lag_self_managed"},
+ "cdc",
+ True,
+ {"sync_frequency": "1hour"},
+ True,
+ id="frequency_change_under_self_managed_lag",
+ ),
+ pytest.param(
+ {"reason": "billing_limit_expired", "slot_kept": True},
+ "cdc",
+ True,
+ {"sync_frequency": "1hour"},
+ True,
+ id="frequency_change_after_a_billing_stop_that_kept_the_slot",
+ ),
+ pytest.param(
+ {"reason": "auto_dropped_critical_lag"},
+ "incremental",
+ True,
+ {"sync_frequency": "1hour"},
+ True,
+ id="frequency_change_beside_a_marker_left_on_a_table_that_left_cdc",
+ ),
+ ],
+ )
+ def test_an_edit_leaves_a_cdc_tables_schedule_as_the_broken_marker_left_it(
+ self, team, user, client: HttpClient, temporal, marker, marked_table_sync_type, synced_before, payload, runs
+ ):
+ client.force_login(user)
+ schema = self._cdc_table_beside_a_marked_one(team, marker, marked_table_sync_type, synced_before)
+ sync_external_data_job_workflow(schema, create=True, should_sync=runs, trigger_immediately=False)
+
+ with self._patch_cdc_edit():
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data=payload,
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+ schema.refresh_from_db()
+ assert schema.should_sync is True
+ schedule = describe_schedule(temporal, str(schema.id)).schedule
+ assert schedule.state.paused is (not runs)
+ if "sync_frequency" in payload:
+ assert schedule.spec.intervals[0].every == timedelta(hours=1)
+
+ def test_sync_turned_on_without_a_schedule_on_a_broken_source_creates_it_paused(
+ self, team, user, client: HttpClient, temporal
+ ):
+ client.force_login(user)
+ schema = self._cdc_table_beside_a_marked_one(team, {"reason": "auto_dropped_critical_lag"}, "cdc", False)
+
+ service = "products.data_warehouse.backend.logic.data_load.service"
+ with (
+ self._patch_cdc_edit(),
+ mock.patch(f"{service}.create_schedule", wraps=create_schedule) as create,
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"should_sync": True},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+ assert describe_schedule(temporal, str(schema.id)).schedule.state.paused is True
+ assert create.call_args.kwargs["trigger_immediately"] is False
+
+ @pytest.mark.parametrize(
+ "synced_before, payload, runs_after",
+ [
+ pytest.param(False, {"should_sync": True}, True, id="sync_turned_on_is_resumed"),
+ pytest.param(True, {"sync_frequency": "1hour"}, False, id="frequency_change_keeps_the_pause"),
+ ],
+ )
+ def test_an_edit_while_a_repair_runs(
+ self, team, user, client: HttpClient, temporal, synced_before, payload, runs_after
+ ):
+ client.force_login(user)
+ schema = self._cdc_table_beside_a_marked_one(
+ team, {"reason": "auto_dropped_critical_lag"}, "cdc", synced_before
+ )
+ sync_external_data_job_workflow(schema, create=True, should_sync=False, trigger_immediately=False)
+ repair_lock = _repair_lock_key(str(schema.source_id))
+ get_client().set(repair_lock, "1", ex=60)
+
+ try:
+ with self._patch_cdc_edit():
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data=payload,
+ content_type="application/json",
+ )
+ finally:
+ get_client().delete(repair_lock)
+
+ assert response.status_code == 200, response.content
+ assert describe_schedule(temporal, str(schema.id)).schedule.state.paused is (not runs_after)
+
+ def test_sync_turned_on_as_a_repair_finishes_resumes_the_table(self, team, user, client: HttpClient, temporal):
+ client.force_login(user)
+ schema = self._cdc_table_beside_a_marked_one(team, {"reason": "auto_dropped_critical_lag"}, "cdc", False)
+ sync_external_data_job_workflow(schema, create=True, should_sync=False, trigger_immediately=False)
+
+ def finish_the_repair(_source: ExternalDataSource) -> bool:
+ self._clear_broken_markers(schema)
+ return False
+
+ views = "products.warehouse_sources.backend.presentation.views.external_data_schema"
+ with (
+ self._patch_cdc_edit(),
+ mock.patch(f"{views}.repair_is_running", side_effect=finish_the_repair),
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"should_sync": True},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+ assert describe_schedule(temporal, str(schema.id)).schedule.state.paused is False
+
+ @pytest.mark.parametrize(
+ "reset_left_to_capture, runs_after",
+ [
+ pytest.param(False, True, id="resumes_the_table"),
+ pytest.param(True, False, id="keeps_a_reset_left_to_capture_paused"),
+ ],
+ )
+ def test_sync_turned_on_without_a_schedule_as_a_repair_ends(
+ self, team, user, client: HttpClient, temporal, reset_left_to_capture, runs_after
+ ):
+ client.force_login(user)
+ schema = self._cdc_table_beside_a_marked_one(team, {"reason": "auto_dropped_critical_lag"}, "cdc", False)
+
+ def create_as_the_repair_ends(*args: Any, **kwargs: Any) -> Any:
+ created = create_schedule(*args, **kwargs)
+ self._clear_broken_markers(schema)
+ return created
+
+ service = "products.data_warehouse.backend.logic.data_load.service"
+ with (
+ self._patch_cdc_edit(queued_batches=reset_left_to_capture),
+ mock.patch(f"{service}.create_schedule", side_effect=create_as_the_repair_ends),
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"should_sync": True},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+ assert describe_schedule(temporal, str(schema.id)).schedule.state.paused is (not runs_after)
+
+ @staticmethod
+ def _clear_broken_markers(schema: ExternalDataSchema) -> None:
+ marked = ExternalDataSchema.objects.filter(source_id=schema.source_id, sync_type_config__has_key="cdc_broken")
+ for schema_id in marked.values_list("id", flat=True):
+ update_sync_type_config_keys(schema_id, schema.team_id, removes=["cdc_broken"])
+
+ def _cdc_table_beside_a_marked_one(
+ self, team, marker: dict[str, Any], marked_table_sync_type: str, synced_before: bool
+ ) -> ExternalDataSchema:
+ streaming = {"cdc_mode": "streaming", "cdc_table_mode": "consolidated"}
+ source_is_marked = marked_table_sync_type == "cdc"
+ source, schema = self._managed_cdc_source_and_full_refresh_schema(
+ team,
+ should_sync=synced_before,
+ initial_sync_complete=True,
+ sync_frequency_interval=timedelta(minutes=5),
+ sync_type_config={**streaming, **({"cdc_broken": marker} if synced_before and source_is_marked else {})},
+ )
+ ExternalDataSchema.objects.filter(id=schema.id).update(sync_type=ExternalDataSchema.SyncType.CDC)
+ ExternalDataSchema.objects.create(
+ team=team,
+ source=source,
+ name="analytics.orders",
+ should_sync=True,
+ sync_type=marked_table_sync_type,
+ sync_type_config={**streaming, "cdc_broken": marker},
+ )
+ schema.refresh_from_db()
+ return schema
+
+ @staticmethod
+ def _patch_cdc_edit(queued_batches: bool = False) -> contextlib.ExitStack:
+ stack = contextlib.ExitStack()
+ views = "products.warehouse_sources.backend.presentation.views.external_data_schema"
+ data_imports = "products.warehouse_sources.backend.temporal.data_imports"
+ facade = "products.data_warehouse.backend.facade.api"
+ stack.enter_context(mock.patch(f"{views}.is_cdc_enabled_for_team", return_value=True))
+ stack.enter_context(mock.patch(f"{views}.sync_cdc_extraction_schedule"))
+ stack.enter_context(mock.patch(f"{facade}.trigger_cdc_extraction_schedule", return_value=True))
+ stack.enter_context(mock.patch(f"{data_imports}.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table"))
+ stack.enter_context(
+ mock.patch(f"{data_imports}.cdc.source_manager.has_queued_batches", return_value=queued_batches)
+ )
+ return stack
+
def test_update_schema_sync_time_of_day_when_previously_not_set(self, team, user, client: HttpClient, temporal):
client.force_login(user)
source_id = create_external_data_source_ok(client, team.pk)