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(data-warehouse): stop cdc firing for source types without an adapter (#104483)

Tom Owers45c9ce428bde
diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.py
index 1947abdea77c..ca44767c2f97 100644
--- a/products/data_warehouse/backend/logic/data_load/service.py
+++ b/products/data_warehouse/backend/logic/data_load/service.py
@@ -512,6 +512,19 @@ def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = Fals
schemas are active, deletes the schedule.
"""
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
+ from products.warehouse_sources.backend.facade.source_management import source_type_supports_cdc
+
+ if not source_type_supports_cdc(source.source_type):
+ # Nothing can read a change stream from this source type, so the schedule could only fire
+ # and fail on every interval. Drop any an earlier call left behind, because the extraction
+ # activity deletes its own schedule for the same reason and this must not recreate it.
+ logger.warning(
+ "Refusing a CDC extraction schedule — source type does not support CDC",
+ source_id=str(source.id),
+ source_type=source.source_type,
+ )
+ delete_cdc_extraction_schedule(str(source.id))
+ return
# `source__deleted=True` is excluded so a deleted source (whose schemas may have been
# left non-deleted by `soft_delete`) collapses to the "no active CDC schemas" branch below
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 7d2606eef1fa..3a472bd3429e 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
@@ -37,6 +37,7 @@ from products.data_warehouse.backend.logic.data_load.service import (
get_sync_schedule,
is_cdc_extraction_schedule_paused,
pause_external_data_schedule,
+ sync_cdc_extraction_schedule,
unpause_external_data_schedule,
)
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
@@ -459,6 +460,25 @@ def test_bulk_sync_cdc_reraises_non_not_found_rpc_errors():
assert create_mock.call_count == 0
+# --- sync_cdc_extraction_schedule (per-source upsert) ---
+
+
[email protected]("source_type", ["MySQL", "UnsupportedDB"])
+def test_sync_cdc_refuses_a_schedule_for_a_source_type_without_cdc(source_type: str) -> None:
+ source = MagicMock(id=uuid.uuid4(), source_type=source_type)
+
+ with (
+ patch(f"{SERVICE}.sync_connect") as connect_mock,
+ patch(f"{SERVICE}.delete_external_data_schedule") as delete_mock,
+ ):
+ sync_cdc_extraction_schedule(source, create=True)
+
+ # Creating it would fire an extraction run that can never read a change stream, once per
+ # interval for as long as the source lives.
+ connect_mock.assert_not_called()
+ delete_mock.assert_called_once_with(_get_cdc_extraction_schedule_id(str(source.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 cfe82175a164..946a664d6770 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -44,6 +44,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc import metrics
from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters import (
cdc_supported_source_types,
get_cdc_adapter,
+ source_type_supports_cdc,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
CDC_SEQ_COLUMN,
@@ -929,6 +930,14 @@ class CDCExtractActivity:
self._delete_own_schedule()
return False
+ if not source_type_supports_cdc(self.source.source_type):
+ # No adapter means no change stream to read, so every tick of this schedule can only
+ # fail. Delete it instead of reporting the same failure once per interval for as long
+ # as the source lives. `sync_cdc_extraction_schedule` refuses to create it again.
+ self.log.info("source_type_does_not_support_cdc_deleting_schedule", source_type=self.source.source_type)
+ self._delete_own_schedule()
+ return False
+
self.cdc_schemas = self._get_cdc_schemas()
if not self.cdc_schemas:
self.log.info("no_active_cdc_schemas_deleting_schedule")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
index 2dcd41b6908a..b0cda945378a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
@@ -157,19 +157,32 @@ def _cdc_adapters() -> dict[ExternalDataSourceType, CDCSourceAdapter[CDCConfig]]
}
+class CDCUnsupportedSourceTypeError(ValueError):
+ """The source's type has no entry in the adapter registry, so it has no change stream to read.
+
+ Non-retryable: the type is a property of the source, so every retry fails the same way. A
+ scheduled caller that hits this must stop being scheduled, because the alternative is one
+ report of the same failure per interval for as long as the source lives.
+
+ Subclasses ``ValueError`` because the API handlers that answer an unsupported type with a 400
+ catch that, while the name lets a caller tell this apart from any other bad value.
+ """
+
+
def get_cdc_adapter(source: ExternalDataSource) -> CDCSourceAdapter[CDCConfig]:
"""Return the CDC adapter for the given source's type.
- Raises ValueError if the source type doesn't support CDC.
+ Raises ``CDCUnsupportedSourceTypeError`` if the source type doesn't support CDC. Use
+ ``source_type_supports_cdc`` to ask the same question without an exception.
"""
try:
source_type = ExternalDataSourceType(source.source_type)
except ValueError as e:
- raise ValueError(f"CDC is not supported for source type: {source.source_type}") from e
+ raise CDCUnsupportedSourceTypeError(f"CDC is not supported for source type: {source.source_type}") from e
adapter = _cdc_adapters().get(source_type)
if adapter is None:
- raise ValueError(f"CDC is not supported for source type: {source.source_type}")
+ raise CDCUnsupportedSourceTypeError(f"CDC is not supported for source type: {source.source_type}")
return adapter
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 5d662c55ab91..d75de837f520 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
@@ -253,12 +253,16 @@ class TestGetCDCAdapter:
adapter = get_cdc_adapter(source)
assert isinstance(adapter, PostgresCDCAdapter)
- def test_raises_for_unsupported_source(self):
- from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters import get_cdc_adapter
+ @parameterized.expand([("no_adapter_for_the_type", "MySQL"), ("not_a_source_type_at_all", "UnsupportedDB")])
+ def test_raises_a_typed_error_for_an_unsupported_source(self, _name, source_type):
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters import (
+ CDCUnsupportedSourceTypeError,
+ get_cdc_adapter,
+ )
source = _make_source()
- source.source_type = "UnsupportedDB"
- with pytest.raises(ValueError, match="CDC is not supported"):
+ source.source_type = source_type
+ with pytest.raises(CDCUnsupportedSourceTypeError, match="CDC is not supported"):
get_cdc_adapter(source)
def test_create_reader_extracts_params(self):
@@ -358,6 +362,27 @@ def _make_extract_activity(source, log=None) -> CDCExtractActivity:
return activity_obj
+class TestSetupSelfCleansUnrunnableSchedules:
+ @parameterized.expand([("no_adapter_for_the_type", "MySQL"), ("not_a_source_type_at_all", "UnsupportedDB")])
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_a_source_type_without_cdc_deletes_the_schedule_instead_of_failing(
+ self, _name, source_type, _mock_close_conns, MockSourceModel, mock_get_adapter
+ ):
+ source = _make_source()
+ source.source_type = source_type
+ MockSourceModel.objects.get.return_value = source
+ MockSourceModel.DoesNotExist = ExternalDataSource.DoesNotExist
+
+ act = _make_extract_activity(source)
+ with patch.object(act, "_delete_own_schedule") as mock_delete:
+ assert act._setup() is False
+
+ mock_delete.assert_called_once()
+ mock_get_adapter.assert_not_called()
+
+
class TestBackpressureGuard:
def _activity(self) -> CDCExtractActivity:
source = _make_source()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py
index 022be0456b30..87054a1fc460 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py
@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager
served_lanes,
serves_buffered_lane,
)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import CDCJobInputsUnreadableError
_TEAM_ID = 7
_SCHEMA_ID = "3f7c1f4e-0000-0000-0000-000000000001"
@@ -347,13 +348,30 @@ class TestBufferedGating:
"unrecognized_table_mode",
{"job_inputs": {"cdc_ingest_mode": "buffered"}, "cdc_table_mode": "something_new"},
),
- ("job_inputs_not_a_mapping", {"job_inputs": "buffered"}),
("still_snapshotting", {"job_inputs": {"cdc_ingest_mode": "buffered"}, "cdc_mode": "snapshot"}),
]
)
def test_the_scheduled_sync_is_not_forced_off_the_flag_for(self, _name, overrides):
assert scheduled_sync_consumes_buffer(_schema(**overrides)) is False
+ @parameterized.expand(
+ [
+ ("mapping", {"cdc_ingest_mode": "buffered"}, True),
+ ("json_string", '{"cdc_ingest_mode": "buffered"}', True),
+ ("json_string_not_flipped", '{"cdc_ingest_mode": "legacy"}', False),
+ ("empty_string", "", False),
+ ]
+ )
+ def test_the_flip_is_read_through_whichever_shape_job_inputs_decrypted_to(self, _name, job_inputs, consumes):
+ # EncryptedJSONField hands back a value that was written as a string as that same string,
+ # so reading only the mapping shape leaves a flipped source's buffer unconsumed.
+ assert scheduled_sync_consumes_buffer(_schema(job_inputs=job_inputs)) is consumes
+
+ @parameterized.expand([("not_json", "buffered"), ("json_scalar", "12"), ("not_a_string_either", 7)])
+ def test_job_inputs_that_is_no_mapping_at_all_is_an_error(self, _name, job_inputs):
+ with pytest.raises(CDCJobInputsUnreadableError):
+ scheduled_sync_consumes_buffer(_schema(job_inputs=job_inputs))
+
@pytest.mark.asyncio
class TestBatchesInFlight:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
index c451c2f64ceb..ca40cc0e6ef5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import json
from collections.abc import Iterator, Mapping
from dataclasses import dataclass
from datetime import datetime
@@ -14,13 +15,44 @@ ManagementMode = Literal["posthog", "self_managed"]
IngestMode = Literal["legacy", "buffered"]
-def parse_ingest_mode(job_inputs: Mapping[str, Any] | None) -> IngestMode:
- """Anything unrecognized reads as legacy: an unknown value must not route a source onto a
- path it was never flipped to. `job_inputs` decrypts from EncryptedJSONField, so it is not
- always a mapping — a non-mapping value is unrecognized too, not an error."""
- if not isinstance(job_inputs, Mapping):
- return "legacy"
- return "buffered" if job_inputs.get("cdc_ingest_mode") == "buffered" else "legacy"
+class CDCJobInputsUnreadableError(Exception):
+ """`job_inputs` did not resolve to a mapping, so no CDC setting can be read from the source.
+
+ Non-retryable: the stored value replays identically on every read.
+
+ Raised instead of reading the settings as absent, because a source whose stored mode cannot be
+ read would then route onto the lane it was never flipped to, and a buffer nothing consumes
+ looks the same as an idle one.
+ """
+
+
+def decode_job_inputs(job_inputs: Mapping[str, Any] | str | None) -> Mapping[str, Any]:
+ """`job_inputs` as a mapping, whichever shape it decrypted to.
+
+ EncryptedJSONField encrypts each leaf of a mapping separately, but it encrypts a value that was
+ assigned as a string whole. A source written that way therefore reads back as one JSON string
+ rather than a mapping, so decode it.
+ """
+ if not job_inputs:
+ return {}
+ if isinstance(job_inputs, Mapping):
+ return job_inputs
+ if not isinstance(job_inputs, str):
+ raise CDCJobInputsUnreadableError(f"job_inputs is a {type(job_inputs).__name__}, expected a mapping")
+ try:
+ decoded = json.loads(job_inputs)
+ except ValueError as e:
+ # Never name the value in the message: job_inputs holds the source's connection credentials.
+ raise CDCJobInputsUnreadableError("job_inputs is a string that does not decode as JSON") from e
+ if not isinstance(decoded, Mapping):
+ raise CDCJobInputsUnreadableError(f"job_inputs decoded to a {type(decoded).__name__}, expected a mapping")
+ return decoded
+
+
+def parse_ingest_mode(job_inputs: Mapping[str, Any] | str | None) -> IngestMode:
+ """An unrecognized value reads as legacy: it must not route a source onto a path it was never
+ flipped to. Raises ``CDCJobInputsUnreadableError`` when there is no value to read at all."""
+ return "buffered" if decode_job_inputs(job_inputs).get("cdc_ingest_mode") == "buffered" else "legacy"
@dataclass(frozen=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
index 8ee9e4b099e3..e2f186e3beec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
@@ -9,13 +9,15 @@ provides a typed wrapper so consumers don't have to do dict access.
from __future__ import annotations
import dataclasses
-from typing import TYPE_CHECKING
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any
from posthog.utils import str_to_bool
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import (
CDCConfig,
ManagementMode,
+ decode_job_inputs,
parse_ingest_mode,
)
@@ -37,8 +39,8 @@ class PostgresCDCConfig(CDCConfig):
consistent_point: str | None
@classmethod
- def from_dict(cls, job_inputs: dict | None) -> PostgresCDCConfig:
- ji = job_inputs or {}
+ def from_dict(cls, job_inputs: Mapping[str, Any] | str | None) -> PostgresCDCConfig:
+ ji = decode_job_inputs(job_inputs)
management_mode: ManagementMode = (
"self_managed" if ji.get("cdc_management_mode") == "self_managed" else "posthog"
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_cdc_config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_cdc_config.py
index 39a2e867e9f6..bbf7aebca502 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_cdc_config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_cdc_config.py
@@ -56,6 +56,21 @@ def test_from_dict_defaults():
assert config.consistent_point is None
+ "job_inputs",
+ [
+ {"cdc_slot_name": "slot_a", "cdc_ingest_mode": "buffered"},
+ '{"cdc_slot_name": "slot_a", "cdc_ingest_mode": "buffered"}',
+ ],
+)
+def test_from_dict_reads_whichever_shape_job_inputs_decrypted_to(job_inputs):
+ # EncryptedJSONField hands back a value that was written as a string as that same string, and
+ # every field here is read off a mapping.
+ config = PostgresCDCConfig.from_dict(job_inputs)
+ assert config.slot_name == "slot_a"
+ assert config.ingest_mode == "buffered"
+
+
def test_from_dict_thresholds_coerce_stringified_ints():
config = PostgresCDCConfig.from_dict(
{"cdc_lag_warning_threshold_mb": "256", "cdc_lag_critical_threshold_mb": "1024"}