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 broken cdc paused and clear stale markers (#109168)

Daniel RC33c2b3ec3c1d
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index cbdcd73bdf7c..e99de330dde1 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -58,6 +58,8 @@ A reset from slot-invalidation recovery marks the key `awaiting_slot` until the
Recovery clears the flag once the slot is back, and so does any read that succeeds, so a failure right after the recreation cannot leave the table waiting for good.
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.
+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.
Turning a table's sync off, or adding it back to capture, drops its marker, because capture skipped the table in between and its buffer has a gap.
diff --git a/posthog/temporal/common/schedule.py b/posthog/temporal/common/schedule.py
index 964489d47543..5c2fa88a109e 100644
--- a/posthog/temporal/common/schedule.py
+++ b/posthog/temporal/common/schedule.py
@@ -64,6 +64,17 @@ async def a_create_schedule(
)
+def _keep_pause(schedule: Schedule, current: ScheduleDescription) -> None:
+ """Carry a pause, and the note that gives its reason, onto a replacement definition.
+
+ An update replaces the whole schedule, its state included, so a definition built unpaused would
+ otherwise unpause a schedule that something paused on purpose.
+ """
+ if current.schedule.state.paused:
+ schedule.state.paused = True
+ schedule.state.note = current.schedule.state.note
+
+
@async_to_sync
async def update_schedule(
temporal: Client,
@@ -71,6 +82,7 @@ async def update_schedule(
schedule: Schedule,
keep_tz: bool = False,
search_attributes: TypedSearchAttributes | None = None,
+ keep_paused: bool = False,
) -> None:
"""Update a Temporal Schedule."""
handle = temporal.get_schedule_handle(id)
@@ -79,7 +91,9 @@ async def update_schedule(
desc = await handle.describe()
schedule.spec.time_zone_name = desc.schedule.spec.time_zone_name
- async def updater(_: ScheduleUpdateInput) -> ScheduleUpdate:
+ async def updater(update_input: ScheduleUpdateInput) -> ScheduleUpdate:
+ if keep_paused:
+ _keep_pause(schedule, update_input.description)
return ScheduleUpdate(schedule=schedule, search_attributes=search_attributes)
return await handle.update(
@@ -92,11 +106,14 @@ async def a_update_schedule(
id: str,
schedule: Schedule,
search_attributes: TypedSearchAttributes | None = None,
+ keep_paused: bool = False,
) -> None:
"""Async update a Temporal Schedule."""
handle = temporal.get_schedule_handle(id)
- async def updater(_: ScheduleUpdateInput) -> ScheduleUpdate:
+ async def updater(update_input: ScheduleUpdateInput) -> ScheduleUpdate:
+ if keep_paused:
+ _keep_pause(schedule, update_input.description)
return ScheduleUpdate(schedule=schedule, search_attributes=search_attributes)
return await handle.update(
diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.py
index 61230acd4555..88d6938db65f 100644
--- a/products/data_warehouse/backend/logic/data_load/service.py
+++ b/products/data_warehouse/backend/logic/data_load/service.py
@@ -591,7 +591,7 @@ def sync_cdc_extraction_schedule(
create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=trigger_immediately)
else:
try:
- update_schedule(temporal, id=schedule_id, schedule=schedule)
+ update_schedule(temporal, id=schedule_id, schedule=schedule, keep_paused=True)
except temporalio.service.RPCError as e:
if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:
create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=trigger_immediately)
@@ -707,7 +707,7 @@ async def bulk_sync_cdc_extraction_schedules(
schedule_id = _get_cdc_extraction_schedule_id(str(source.id))
schedule = get_cdc_extraction_schedule(source, min_interval)
try:
- await a_update_schedule(temporal, id=schedule_id, schedule=schedule)
+ await a_update_schedule(temporal, id=schedule_id, schedule=schedule, keep_paused=True)
except temporalio.service.RPCError as e:
if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:
await a_create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=True)
diff --git a/products/data_warehouse/backend/logic/data_load/test/test_service.py b/products/data_warehouse/backend/logic/data_load/test/test_service.py
index fe04f81617cd..b67b0ed367d9 100644
--- a/products/data_warehouse/backend/logic/data_load/test/test_service.py
+++ b/products/data_warehouse/backend/logic/data_load/test/test_service.py
@@ -20,6 +20,7 @@ from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from posthog.models import Organization, Team
from posthog.temporal.common.client import sync_connect
+from posthog.temporal.common.schedule import describe_schedule
from products.data_warehouse.backend.logic.data_load.service import (
CDC_DEFAULT_INTERVAL,
@@ -35,6 +36,7 @@ from products.data_warehouse.backend.logic.data_load.service import (
get_discover_schemas_schedule,
get_sync_schedule,
is_cdc_extraction_schedule_paused,
+ pause_cdc_extraction_schedule,
pause_external_data_schedule,
sync_cdc_extraction_schedule,
trigger_cdc_extraction_schedule,
@@ -466,6 +468,34 @@ def test_sync_cdc_refuses_a_schedule_for_a_source_type_without_cdc(source_type:
delete_mock.assert_called_once_with(_get_cdc_extraction_schedule_id(str(source.id)))
[email protected]("paused", [True, False])
[email protected]("via_bulk", [False, True])
+def test_a_cadence_sync_leaves_the_capture_schedule_pause_as_it_was(temporal, paused: bool, via_bulk: bool) -> None:
+ team = _sync_team()
+ source = _make_source(team)
+ schema = _make_schema(team, source, sync_type=ExternalDataSchema.SyncType.CDC)
+ schedule_id = _get_cdc_extraction_schedule_id(str(source.id))
+ sync_cdc_extraction_schedule(source, create=True, trigger_immediately=False)
+ try:
+ if paused:
+ pause_cdc_extraction_schedule(str(source.id))
+ note_before = describe_schedule(temporal, schedule_id).schedule.state.note
+
+ schema.sync_frequency_interval = dt.timedelta(hours=1)
+ schema.save(update_fields=["sync_frequency_interval"])
+ if via_bulk:
+ assert bulk_sync_cdc_extraction_schedules([(source, dt.timedelta(hours=1))]) == []
+ else:
+ sync_cdc_extraction_schedule(source)
+
+ schedule = describe_schedule(temporal, schedule_id).schedule
+ assert schedule.spec.intervals[0].every == dt.timedelta(hours=1)
+ assert schedule.state.paused is paused
+ assert schedule.state.note == note_before
+ finally:
+ delete_temporal_schedule(temporal, schedule_id)
+
+
# --- bulk_update_external_data_job_schedules (update-only; missing => skipped) ---
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 c31d49c98f21..4185272dc664 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -54,8 +54,10 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.billing_expiry
stop_cdc_past_billing_retention,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import (
+ AUTO_DROPPED_LAG_REASON,
SELF_MANAGED_LAG_REASON,
clear_recovered_self_managed_lag,
+ clear_slot_loss_markers,
mark_cdc_broken,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import CDCBufferWriter, purge_buffer_prefix
@@ -1251,6 +1253,7 @@ class CDCExtractActivity:
self._release_reset_awaiting_slot(schema)
for schema in reset_schemas:
self._unpause_schema_schedule(schema)
+ clear_slot_loss_markers(self.source)
self.log.info("cdc_slot_recovery_complete", schemas_reset=len(self.cdc_schemas))
@@ -1689,7 +1692,7 @@ def cleanup_orphan_slots_activity() -> None:
# schedule so it stops retrying against a slot that no longer exists.
mark_cdc_broken(
source,
- "auto_dropped_critical_lag",
+ AUTO_DROPPED_LAG_REASON,
f"Change data capture was automatically stopped because replication lag "
f"exceeded {critical_threshold_mb} MB and the safety net dropped the "
f"replication slot. Use Repair CDC to recreate it and re-sync.",
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 f9ed0d098f89..64c48d23cd88 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
_build_schema_snapshot,
)
@@ -40,6 +41,15 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
logger = structlog.get_logger(__name__)
SELF_MANAGED_LAG_REASON = "critical_lag_self_managed"
+AUTO_DROPPED_LAG_REASON = "auto_dropped_critical_lag"
+
+# Markers that report a lost slot or publication. A recreated slot resolves them. Billing and a
+# customer-owned slot's lag have causes of their own, so their markers stay.
+_SLOT_LOSS_REASONS = (
+ AUTO_DROPPED_LAG_REASON,
+ CDCErrorCategory.SLOT_MISSING.value,
+ CDCErrorCategory.PUBLICATION_MISSING.value,
+)
def mark_cdc_broken(
@@ -126,6 +136,15 @@ def clear_recovered_self_managed_lag(source: ExternalDataSource) -> int:
return clear_broken_markers(source, reason=SELF_MANAGED_LAG_REASON)
+def clear_slot_loss_markers(source: ExternalDataSource) -> int:
+ """Lift the markers of a lost slot once capture has recreated it. Returns how many schemas were cleared.
+
+ Left in place, a marker keeps each table's status on the old error, and every check that reads
+ ``cdc_halted`` treats the table as halted although it streams again.
+ """
+ return sum(clear_broken_markers(source, reason=reason) for reason in _SLOT_LOSS_REASONS)
+
+
def clear_broken_markers(source: ExternalDataSource, **marker_fields: typing.Any) -> int:
"""Remove each ``cdc_broken`` marker whose fields match ``marker_fields``, and set the source back to
Running once no schema is still marked. Returns how many schemas were cleared.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_broken.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_broken.py
index cda30ca7fbf3..705099df0b4a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_broken.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_broken.py
@@ -7,7 +7,8 @@ from unittest.mock import call, patch
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_source import ExternalDataSource
-from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import mark_cdc_broken
+from products.warehouse_sources.backend.temporal.data_imports.cdc.billing_expiry import BILLING_LIMIT_EXPIRED_REASON
+from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import clear_slot_loss_markers, mark_cdc_broken
pytestmark = pytest.mark.django_db
@@ -150,3 +151,27 @@ def test_only_active_cdc_schemas_are_marked(team):
# Visibility job rows follow the same scoping — a user-paused schema must not resurface
# in the failure digest.
assert list(ExternalDataJob.objects.values_list("schema_id", flat=True)) == [active.id]
+
+
+ "reason,cleared",
+ [
+ ("auto_dropped_critical_lag", True),
+ ("slot_missing", True),
+ ("publication_missing", True),
+ ("critical_lag_self_managed", False),
+ (BILLING_LIMIT_EXPIRED_REASON, False),
+ ],
+)
+def test_a_recreated_slot_lifts_only_the_markers_of_a_lost_slot(team, reason, cleared):
+ source = _source(team)
+ schema = _cdc_schema(team, source)
+ with _mocked_boundaries():
+ mark_cdc_broken(source, reason, "msg")
+
+ assert clear_slot_loss_markers(source) == (1 if cleared else 0)
+
+ schema.refresh_from_db()
+ source.refresh_from_db()
+ assert ("cdc_broken" in schema.sync_type_config) is not cleared
+ assert source.status == (ExternalDataSource.Status.RUNNING if cleared else ExternalDataSource.Status.ERROR)
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 955a9c2d810e..121e745c60ef 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
@@ -1004,7 +1004,9 @@ class TestSlotInvalidationRecovery:
)
capture.adapter.is_slot_invalidation_error.return_value = True
capture.adapter.recreate_slot.return_value = {"cdc_consistent_point": "0/AA"}
- yield capture
+ with patch(f"{_ACTIVITIES}.clear_slot_loss_markers") as clear_markers:
+ capture.clear_markers = clear_markers
+ yield capture
def test_invalidated_slot_is_recreated_and_schemas_reset_to_snapshot(self):
source = _make_source()
@@ -1019,6 +1021,7 @@ class TestSlotInvalidationRecovery:
# failed after that point would never repeat and the schema would stream across the gap.
assert schema.sync_type_config["cdc_mode"] == "snapshot"
capture.purge.assert_called_once_with(schema.team_id, str(schema.id), ANY, strict=True)
+ capture.clear_markers.assert_not_called()
return {"cdc_consistent_point": "0/AA"}
capture.adapter.recreate_slot.side_effect = _recreate_slot
@@ -1028,6 +1031,7 @@ class TestSlotInvalidationRecovery:
capture.adapter.recreate_slot.assert_called_once_with(source, tables=["public.users"])
assert source.job_inputs["cdc_consistent_point"] == "0/AA"
source.save.assert_called()
+ capture.clear_markers.assert_called_once_with(source)
assert schema.sync_type_config["cdc_mode"] == "snapshot"
assert schema.sync_type_config["reset_pipeline"] is True
@@ -1068,6 +1072,7 @@ class TestSlotInvalidationRecovery:
# The raw recovery error stays in the logs; the user-facing column gets friendly copy.
assert schema.latest_error == cdc_error_info(CDCErrorCategory.UNKNOWN).friendly_message
assert "cannot recreate slot" not in schema.latest_error
+ capture.clear_markers.assert_not_called()
capture.reader.close.assert_called_once()
@parameterized.expand([("recreation_failed", True), ("recreation_succeeded", False)])