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): unstick cdc syncs and surface their logs in the ui (#58162)

Daniel RC7f790d536e42
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index ff7885fc8152..73fa80a063e1 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5966,6 +5966,12 @@ export interface ExternalDataJob {
rows_synced: number
latest_error: string
workflow_run_id?: string
+ /**
+ * For CDC syncs with `cdc_table_mode='both'`, distinguishes the two ExternalDataJob rows
+ * produced for the same schema: `incremental_merge` (consolidated table) vs `scd2_append`
+ * (cdc-only history table). `null` for non-CDC syncs.
+ */
+ cdc_write_mode?: 'incremental_merge' | 'scd2_append' | null
}
export interface SimpleDataWarehouseTable {
diff --git a/posthog/management/commands/run_warehouse_sources_load.py b/posthog/management/commands/run_warehouse_sources_load.py
index 7f4436eb92cf..8e64738f271a 100644
--- a/posthog/management/commands/run_warehouse_sources_load.py
+++ b/posthog/management/commands/run_warehouse_sources_load.py
@@ -5,6 +5,7 @@ from django.core.management.base import BaseCommand
import structlog
from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+from posthog.temporal.common.logger import configure_logger
from posthog.temporal.data_imports.pipelines.pipeline_v3.load.health import HealthState, start_health_server
from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import BatchConsumer, ConsumerConfig
from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load import process_batch
@@ -12,6 +13,20 @@ from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load imp
logger = structlog.get_logger(__name__)
+async def _run_consumer(config: ConsumerConfig, health_reporter) -> None:
+ """Configure the Temporal-style produce path then run the consumer.
+
+ `configure_logger` plumbs structlog into a Kafka producer that feeds ClickHouse `log_entries`.
+ Calling it from the consumer's own asyncio loop is the same pattern `start_temporal_worker` uses;
+ `merge_temporal_context` no-ops outside an actual workflow/activity, and the per-batch contextvars
+ set in `BatchConsumer._process_single` carry the keys `LogMessagesRenderer` needs (`workflow_type`,
+ `workflow_id`, `workflow_run_id`, `team_id`, plus the event-level `log_source_id` override).
+ """
+ configure_logger(loop=asyncio.get_running_loop())
+ consumer = BatchConsumer(config=config, process_batch=process_batch, health_reporter=health_reporter)
+ await consumer.run()
+
+
class Command(BaseCommand):
help = "Run the warehouse sources batch consumer"
@@ -79,7 +94,4 @@ class Command(BaseCommand):
health_state = HealthState(timeout_seconds=health_timeout)
start_health_server(port=health_port, health_state=health_state)
- consumer = BatchConsumer(
- config=config, process_batch=process_batch, health_reporter=health_state.report_healthy
- )
- asyncio.run(consumer.run())
+ asyncio.run(_run_consumer(config, health_state.report_healthy))
diff --git a/posthog/temporal/common/activity_context.py b/posthog/temporal/common/activity_context.py
new file mode 100644
index 000000000000..879c2115beaa
--- /dev/null
+++ b/posthog/temporal/common/activity_context.py
@@ -0,0 +1,27 @@
+"""Helpers for safely accessing Temporal activity context from code that may
+also run outside an activity (e.g. tests, deferred-run replay, local CLI tools).
+
+`activity.info()` raises `RuntimeError` when called outside an activity worker
+thread. These wrappers translate that into `None` so callers can pass the value
+through to downstream APIs that accept it as optional metadata.
+"""
+
+from __future__ import annotations
+
+from temporalio import activity
+
+
+def current_workflow_id() -> str | None:
+ """Return the current Temporal workflow id, or None if not inside an activity."""
+ try:
+ return activity.info().workflow_id
+ except RuntimeError:
+ return None
+
+
+def current_workflow_run_id() -> str | None:
+ """Return the current Temporal workflow run id, or None if not inside an activity."""
+ try:
+ return activity.info().workflow_run_id
+ except RuntimeError:
+ return None
diff --git a/posthog/temporal/common/logger.py b/posthog/temporal/common/logger.py
index 1880ba93b840..a70e81e0cb90 100644
--- a/posthog/temporal/common/logger.py
+++ b/posthog/temporal/common/logger.py
@@ -24,6 +24,7 @@ Temporal context, like activity ID, workflow type, attempt number, and others, w
automatically included.
"""
+import os
import sys
import json
import typing
@@ -160,12 +161,28 @@ class LogMessagesRenderer:
try:
log_source, log_source_id = resolve_log_source(event_dict["workflow_type"], event_dict["workflow_id"])
+ # Event-level overrides let one workflow_type route to multiple schemas.
+ log_source = event_dict.pop("log_source", log_source)
+ log_source_id = event_dict.pop("log_source_id", log_source_id)
+
+ # Append resource + batch_index so the Syncs UI distinguishes parallel batches
+ # of the same CDC sync. Scoped to `external_data_jobs` so we don't reshape
+ # message text for batch exports / data modeling / other temporal workflows.
+ message_text = event_dict[self.event_key]
+ if log_source == "external_data_jobs":
+ resource_marker = event_dict.get("resource_name") or event_dict.get("resource")
+ if resource_marker:
+ message_text = f"{message_text} [{resource_marker}]"
+ batch_index = event_dict.get("batch_index")
+ if batch_index is not None:
+ message_text = f"{message_text} #{batch_index}"
+
message_dict = {
"instance_id": event_dict["workflow_run_id"],
"level": event_dict["level"],
"log_source": log_source,
"log_source_id": log_source_id,
- "message": event_dict[self.event_key],
+ "message": message_text,
"team_id": event_dict["team_id"],
"timestamp": event_dict["timestamp"],
}
@@ -527,7 +544,10 @@ def configure_logger(
log_producer = None
log_producer_error = None
- is_test_or_tty = sys.stderr.isatty() or settings.TEST
+ # `TEMPORAL_LOGS_TO_KAFKA=true` forces produce path on a TTY (local dev). No effect in prod
+ # (no TTY anyway) or tests (settings.TEST always wins).
+ force_produce = os.getenv("TEMPORAL_LOGS_TO_KAFKA", "").strip().lower() in ("1", "true", "yes", "on")
+ is_test_or_tty = settings.TEST or (sys.stderr.isatty() and not force_produce)
if is_test_or_tty:
logger_factory = LoggerFactory(file=file, is_test_or_tty=is_test_or_tty)
@@ -862,6 +882,12 @@ def resolve_log_source(workflow_type: str, workflow_id: str) -> tuple[str | None
# This works because the WorkflowID is made up like f"{external_data_schema_id}-{data_interval_end}"
log_source_id = workflow_id.rsplit("-", maxsplit=3)[0]
log_source = "external_data_jobs"
+ elif workflow_type == "cdc-extraction":
+ # WorkflowID is f"cdc-extraction-{source_id}-{iso_ts}". Per-schema lines override
+ # log_source_id at emit time; default here is the source id.
+ without_prefix = workflow_id.removeprefix("cdc-extraction-")
+ log_source_id = without_prefix[:36] if len(without_prefix) >= 36 else without_prefix
+ log_source = "external_data_jobs"
elif workflow_type == "data-modeling-run":
# This works because the WorkflowID is made up like f"{saved_query_id}-{data_interval_end}"
log_source_id = workflow_id.rsplit("-", maxsplit=3)[0]
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index 29d5ed844dc3..54d4cf402356 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -1,8 +1,10 @@
"""CDC Temporal activities.
cdc_extract_activity: Core extraction — reads WAL, decodes, batches, writes to
-S3 via pipeline, and sends Kafka notifications for streaming schemas. Defers
-Kafka for snapshot schemas.
+S3 via pipeline, and inserts batch notifications into the warehouse-sources
+Postgres queue for streaming schemas. Snapshot schemas defer their batch
+notifications to `sync_type_config["cdc_deferred_runs"]` until the schema
+transitions to streaming.
validate_cdc_prerequisites_activity: Wraps prerequisite validator for Temporal.
"""
@@ -20,6 +22,8 @@ import pyarrow as pa
import structlog
from temporalio import activity
+from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+from posthog.temporal.common.activity_context import current_workflow_id, current_workflow_run_id
from posthog.temporal.data_imports.cdc.adapters import get_cdc_adapter
from posthog.temporal.data_imports.cdc.batcher import (
ChangeEventBatcher,
@@ -29,7 +33,7 @@ from posthog.temporal.data_imports.cdc.batcher import (
)
from posthog.temporal.data_imports.cdc.types import ChangeEvent
from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral
-from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka.producer import KafkaBatchProducer
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import PostgresProducer
from posthog.temporal.data_imports.pipelines.pipeline_v3.s3.writer import S3BatchWriter
from posthog.temporal.data_imports.workflow_activities.create_job_model import _build_schema_snapshot
@@ -115,6 +119,13 @@ class CDCExtractActivity:
self.event_count: int = 0
self.all_table_names: set[str] = set()
+ # ------------------------------------------------------------------
+ # Logger helpers
+ # ------------------------------------------------------------------
+ def _schema_log(self, schema: ExternalDataSchema) -> structlog.types.FilteringBoundLogger:
+ """Logger bound with per-schema `log_source_id` so lines route under the schema in the Syncs UI."""
+ return self.log.bind(log_source_id=str(schema.id))
+
# ------------------------------------------------------------------
# Schema fetching (kept as a method so tests can patch it on the class)
# ------------------------------------------------------------------
@@ -132,7 +143,7 @@ class CDCExtractActivity:
# Deferred run flushing
# ------------------------------------------------------------------
def _flush_deferred_runs(self, schema: ExternalDataSchema) -> None:
- """Send Kafka messages for deferred CDC runs from the snapshot phase.
+ """Insert deferred-run batch notifications into the warehouse-sources Postgres queue.
Called when a schema has just transitioned to cdc_mode="streaming" and has
entries in sync_type_config["cdc_deferred_runs"].
@@ -143,7 +154,7 @@ class CDCExtractActivity:
assert self.source is not None
source = self.source
- log = self.log
+ log = self._schema_log(schema)
log.info(
"flushing_deferred_cdc_runs",
@@ -158,7 +169,8 @@ class CDCExtractActivity:
total_batches = run_meta.get("total_batches", len(batch_results))
total_rows = run_meta.get("total_rows", 0)
- producer = KafkaBatchProducer(
+ producer = PostgresProducer(
+ database_url=WAREHOUSE_SOURCES_DATABASE_URL,
team_id=schema.team_id,
job_id=job_id,
schema_id=str(schema.id),
@@ -170,6 +182,8 @@ class CDCExtractActivity:
primary_keys=run_meta.get("primary_keys"),
cdc_write_mode=run_meta.get("cdc_write_mode", "incremental_merge"),
cdc_table_mode=run_meta.get("cdc_table_mode"),
+ workflow_id=current_workflow_id(),
+ workflow_run_id=current_workflow_run_id(),
)
from posthog.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult
@@ -192,7 +206,10 @@ class CDCExtractActivity:
schema_path=run_meta.get("schema_path"),
)
- producer.flush()
+ try:
+ producer.flush()
+ finally:
+ producer.close()
schema.sync_type_config["cdc_deferred_runs"] = []
schema.save(update_fields=["sync_type_config", "updated_at"])
@@ -215,6 +232,11 @@ class CDCExtractActivity:
if tracker is not None:
return tracker
+ # Stash `cdc_write_mode` alongside the schema snapshot so the Syncs UI can distinguish
+ # the two ExternalDataJob rows produced when `cdc_table_mode='both'` — no extra column.
+ schema_snapshot = _build_schema_snapshot(schema)
+ schema_snapshot["cdc_write_mode"] = cdc_write_mode
+
job = ExternalDataJob.objects.create(
team_id=self.inputs.team_id,
pipeline_id=self.inputs.source_id,
@@ -224,7 +246,7 @@ class CDCExtractActivity:
workflow_id=activity.info().workflow_id,
workflow_run_id=activity.info().workflow_run_id,
pipeline_version=ExternalDataJob.PipelineVersion.V3,
- schema_snapshot=_build_schema_snapshot(schema),
+ schema_snapshot=schema_snapshot,
)
self.created_jobs.append(job)
@@ -251,18 +273,19 @@ class CDCExtractActivity:
return tracker
# ------------------------------------------------------------------
- # Kafka dispatch & deferred persistence
+ # Batch notification dispatch & deferred persistence
# ------------------------------------------------------------------
- def _send_kafka_batch(
+ def _send_batch_notification(
self,
tracker: _WriteTracker,
batch_result: typing.Any,
is_final_batch: bool,
) -> None:
- """Send a single Kafka notification for a streaming tracker."""
+ """Insert a batch notification into the warehouse-sources Postgres queue for a streaming tracker."""
assert self.source is not None
schema = self.schema_by_name[tracker.table_name]
- producer = KafkaBatchProducer(
+ producer = PostgresProducer(
+ database_url=WAREHOUSE_SOURCES_DATABASE_URL,
team_id=self.inputs.team_id,
job_id=str(tracker.job.id),
schema_id=str(schema.id),
@@ -270,20 +293,26 @@ class CDCExtractActivity:
resource_name=tracker.write_resource_name,
sync_type=typing.cast(SyncTypeLiteral, "cdc"),
run_uuid=tracker.run_uuid,
- logger=self.log,
+ logger=self._schema_log(schema),
primary_keys=tracker.key_columns or None,
cdc_write_mode=tracker.cdc_write_mode,
cdc_table_mode=tracker.cdc_table_mode,
+ workflow_id=current_workflow_id(),
+ workflow_run_id=current_workflow_run_id(),
)
- producer.send_batch_notification(
- batch_result=batch_result,
- is_final_batch=is_final_batch,
- total_batches=tracker.batch_index if is_final_batch else None,
- total_rows=tracker.total_rows if is_final_batch else None,
- data_folder=tracker.s3_writer.get_data_folder() if is_final_batch else None,
- schema_path=tracker.s3_writer.write_schema() if is_final_batch else None,
- )
- producer.flush()
+ try:
+ producer.send_batch_notification(
+ batch_result=batch_result,
+ is_final_batch=is_final_batch,
+ total_batches=tracker.batch_index if is_final_batch else None,
+ total_rows=tracker.total_rows if is_final_batch else None,
+ data_folder=tracker.s3_writer.get_data_folder() if is_final_batch else None,
+ schema_path=tracker.s3_writer.write_schema() if is_final_batch else None,
+ )
+ producer.flush()
+ finally:
+ # PostgresProducer holds an open psycopg connection — close per call so we don't leak.
+ producer.close()
def _store_deferred_batch(
self,
@@ -338,6 +367,15 @@ class CDCExtractActivity:
schema.save(update_fields=["sync_type_config", "updated_at"])
+ self._schema_log(schema).info(
+ "cdc_deferred_run_stored",
+ resource=tracker.write_resource_name,
+ run_uuid=tracker.run_uuid,
+ batch_index=batch_result.batch_index,
+ total_batches=tracker.batch_index,
+ total_rows=tracker.total_rows,
+ )
+
# ------------------------------------------------------------------
# Per-flush processing
# ------------------------------------------------------------------
@@ -348,7 +386,7 @@ class CDCExtractActivity:
) -> set[str]:
"""Enrich, transform, write to S3, and dispatch one micro-batch.
- Streaming schemas: Kafka sent immediately after each S3 write.
+ Streaming schemas: batch notification inserted into the Postgres queue immediately after each S3 write.
Snapshot schemas: batch result persisted to sync_type_config immediately.
Returns the set of write_resource_names that received data.
@@ -395,7 +433,7 @@ class CDCExtractActivity:
tracker.total_rows += write_table.num_rows
flushed.add(write_resource_name)
- self.log.info(
+ self._schema_log(schema).info(
"cdc_batch_written",
table=table_name,
resource=write_resource_name,
@@ -406,7 +444,7 @@ class CDCExtractActivity:
# Dispatch immediately so progress survives process failures.
if schema.cdc_mode == "streaming":
- self._send_kafka_batch(tracker, batch_result, is_final_batch=is_final)
+ self._send_batch_notification(tracker, batch_result, is_final_batch=is_final)
elif schema.cdc_mode == "snapshot":
self._store_deferred_batch(tracker, batch_result, schema)
@@ -423,7 +461,8 @@ class CDCExtractActivity:
3. For each CDC schema:
- Flush deferred runs if transitioning from snapshot → streaming
- Write new events to S3
- - Send Kafka notification (streaming) or defer (snapshot)
+ - Insert batch notification into the warehouse-sources Postgres queue (streaming)
+ or persist into sync_type_config (snapshot)
4. Advance slot position
5. Update cdc_last_log_position per schema
"""
@@ -626,9 +665,10 @@ class CDCExtractActivity:
decoder_pks = self.reader.get_decoder_key_columns(table_name)
stored_pks = self.pk_columns_by_table.get(table_name, [])
if decoder_pks and decoder_pks != stored_pks:
- self.log.warning("pk_columns_changed", table=table_name, old=stored_pks, new=decoder_pks)
- self.pk_columns_by_table[table_name] = decoder_pks
pk_schema = self.schema_by_name.get(table_name)
+ pk_log = self._schema_log(pk_schema) if pk_schema is not None else self.log
+ pk_log.warning("pk_columns_changed", table=table_name, old=stored_pks, new=decoder_pks)
+ self.pk_columns_by_table[table_name] = decoder_pks
if pk_schema is not None:
pk_schema.sync_type_config["primary_key_columns"] = decoder_pks
pk_schema.save(update_fields=["sync_type_config", "updated_at"])
@@ -645,7 +685,8 @@ class CDCExtractActivity:
trunc_schema = self.schema_by_name.get(table_name)
if trunc_schema is None:
continue
- self.log.warning("truncate_detected", table=table_name, schema_id=str(trunc_schema.id))
+ trunc_log = self._schema_log(trunc_schema)
+ trunc_log.warning("truncate_detected", table=table_name, schema_id=str(trunc_schema.id))
trunc_schema.sync_type_config["cdc_mode"] = "snapshot"
trunc_schema.sync_type_config.pop("cdc_last_log_position", None)
trunc_schema.initial_sync_complete = False
@@ -654,9 +695,9 @@ class CDCExtractActivity:
from products.data_warehouse.backend.data_load.service import unpause_external_data_schedule
unpause_external_data_schedule(str(trunc_schema.id))
- self.log.info("unpaused_schema_schedule_for_resnapshot", schema_id=str(trunc_schema.id))
+ trunc_log.info("unpaused_schema_schedule_for_resnapshot", schema_id=str(trunc_schema.id))
except Exception:
- self.log.warning("failed_to_unpause_schema_schedule", schema_id=str(trunc_schema.id))
+ trunc_log.warning("failed_to_unpause_schema_schedule", schema_id=str(trunc_schema.id))
return truncated_tables
def _handle_no_changes(self, truncated_tables: list[str]) -> None:
@@ -673,6 +714,11 @@ class CDCExtractActivity:
schema.latest_error = None
schema.last_synced_at = now
schema.save(update_fields=["status", "latest_error", "last_synced_at", "updated_at"])
+ # Per-schema breadcrumb so the Syncs UI shows _why_ the latest run produced no rows.
+ self._schema_log(schema).info(
+ "cdc_extract_no_changes",
+ truncated_tables=truncated_tables,
+ )
self.log.info("no_wal_changes")
# ------------------------------------------------------------------
@@ -713,7 +759,7 @@ class CDCExtractActivity:
empty = pa.table({"_empty": pa.array([], type=pa.int8())})
finalize_result = tracker.s3_writer.write_batch(empty, batch_index=tracker.batch_index)
tracker.batch_index += 1
- self._send_kafka_batch(tracker, finalize_result, is_final_batch=True)
+ self._send_batch_notification(tracker, finalize_result, is_final_batch=True)
tracker.job.rows_synced = tracker.total_rows
tracker.job.save(update_fields=["rows_synced", "updated_at"])
@@ -773,6 +819,8 @@ class CDCExtractActivity:
# NOTE: may need to truncate if stack traces grow unwieldy
schema.latest_error = str(exc)
schema.save(update_fields=["status", "latest_error", "updated_at"])
+ # Mirror the failure as a per-schema log line so it shows up in the Syncs panel.
+ self._schema_log(schema).error("cdc_extract_schema_failed", error=str(exc))
def _finalize_success(self) -> None:
now = dt.datetime.now(tz=dt.UTC)
diff --git a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
index 605c234833c9..a5317dc0b256 100644
--- a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -71,7 +71,7 @@ _CDC_ACTIVITY_PATCHES = [
"posthog.temporal.data_imports.cdc.activities.CDCExtractActivity._get_cdc_schemas",
"posthog.temporal.data_imports.cdc.activities.get_cdc_adapter",
"posthog.temporal.data_imports.cdc.activities.S3BatchWriter",
- "posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer",
+ "posthog.temporal.data_imports.cdc.activities.PostgresProducer",
"posthog.temporal.data_imports.cdc.activities.activity",
]
@@ -186,7 +186,7 @@ def _make_extract_activity(source, log=None) -> CDCExtractActivity:
class TestFlushDeferredRuns:
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
def test_sends_kafka_messages_for_deferred_runs(self, MockProducer):
mock_producer = MagicMock()
MockProducer.return_value = mock_producer
@@ -221,7 +221,7 @@ class TestFlushDeferredRuns:
assert schema.sync_type_config["cdc_deferred_runs"] == []
schema.save.assert_called()
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
def test_no_op_when_no_deferred_runs(self, MockProducer):
source = _make_source()
schema = _make_schema("users", cdc_mode="streaming", source=source)
@@ -232,7 +232,7 @@ class TestFlushDeferredRuns:
MockProducer.assert_not_called()
schema.save.assert_not_called()
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
def test_multiple_deferred_runs(self, MockProducer):
mock_producer = MagicMock()
MockProducer.return_value = mock_producer
@@ -271,7 +271,7 @@ class TestCDCExtractActivity:
"""Integration tests for cdc_extract_activity with mocked external deps."""
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -321,7 +321,7 @@ class TestCDCExtractActivity:
mock_reader.close.assert_called_once()
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -368,7 +368,7 @@ class TestCDCExtractActivity:
assert "status" not in call.kwargs.get("update_fields", [])
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -485,7 +485,7 @@ class TestCDCExtractActivity:
mock_get_adapter.assert_not_called()
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -567,7 +567,7 @@ class TestCDCExtractActivity:
mock_reader.close.assert_called_once()
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -619,7 +619,7 @@ class TestCDCExtractActivity:
mock_reader.confirm_position.assert_not_called()
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -706,7 +706,7 @@ class TestCDCExtractActivity:
@patch("posthog.temporal.data_imports.cdc.activities.unpause_external_data_schedule", create=True)
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -755,7 +755,7 @@ class TestCDCExtractActivity:
assert "cdc_last_log_position" not in schema.sync_type_config
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -810,7 +810,7 @@ class TestCDCExtractActivity:
@patch("posthog.temporal.data_imports.cdc.activities.unpause_external_data_schedule", create=True)
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -858,7 +858,7 @@ class TestCDCExtractActivity:
assert schema.sync_type_config.get("cdc_last_log_position") is None
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -925,7 +925,7 @@ class TestCDCExtractActivity:
assert resource_names == {"users", "users_cdc"}
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -981,7 +981,7 @@ class TestCDCExtractActivity:
@patch("posthog.temporal.data_imports.cdc.activities.ChangeEventBatcher")
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
@@ -1043,7 +1043,7 @@ class TestCDCExtractActivity:
assert send_calls[1].kwargs["is_final_batch"] is True
@patch("posthog.temporal.data_imports.cdc.activities.activity")
- @patch("posthog.temporal.data_imports.cdc.activities.KafkaBatchProducer")
+ @patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
@patch("posthog.temporal.data_imports.cdc.activities.S3BatchWriter")
@patch("posthog.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch.object(CDCExtractActivity, "_get_cdc_schemas")
diff --git a/posthog/temporal/data_imports/cdc/workflows.py b/posthog/temporal/data_imports/cdc/workflows.py
index af70a109113a..b6edbb6fb34f 100644
--- a/posthog/temporal/data_imports/cdc/workflows.py
+++ b/posthog/temporal/data_imports/cdc/workflows.py
@@ -2,7 +2,7 @@
CDCExtractionWorkflow: source-level scheduled workflow that reads all WAL changes
from the replication slot, groups them by table, and writes them through the
-pipeline (S3BatchWriter → KafkaBatchProducer → Kafka consumer → DeltaLake).
+pipeline (S3BatchWriter → PostgresProducer → warehouse-sources-load consumer → DeltaLake).
"""
from __future__ import annotations
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index c02ad4da1268..9b76bc60d9a1 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -501,7 +501,7 @@ def process_message(message: Any, progress_callback: Callable[[], None] | None =
)
if export_signal.is_final_batch:
- logger.debug(
+ logger.info(
"final_batch_received",
total_batches=export_signal.total_batches,
total_rows=export_signal.total_rows,
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 7fa4b87ad251..2fa097be280c 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -8,6 +8,7 @@ from structlog.types import FilteringBoundLogger
from temporalio import activity
from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+from posthog.temporal.common.activity_context import current_workflow_id, current_workflow_run_id
from posthog.temporal.common.shutdown import ShutdownMonitor
from posthog.temporal.data_imports.pipelines.common.extract import (
cdp_producer_clear_chunks,
@@ -149,6 +150,8 @@ class PipelineV3(Generic[ResumableData]):
partition_format=partition_format,
partition_mode=partition_mode,
is_first_ever_sync=is_first_ever_sync,
+ workflow_id=current_workflow_id(),
+ workflow_run_id=current_workflow_run_id(),
)
self._resumable_source_manager = resumable_source_manager
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 043e84b0bb3f..8cc2114da52c 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -37,6 +37,7 @@ from products.warehouse_sources_queue.backend.models import SourceBatchStatus
logger = structlog.get_logger(__name__)
+
MAX_ATTEMPTS = 3
POLL_INTERVAL_SECONDS = 2.0
@@ -171,13 +172,64 @@ class BatchConsumer:
await BatchQueue.unlock_for_batches(self._conn, batches=batches)
async def _process_single(self, batch: PendingBatch) -> None:
- """Increment attempt, check max retries, then process the batch."""
+ """Increment attempt, check max retries, then process the batch.
+
+ Binds per-batch contextvars so every downstream log line (including loader calls)
+ routes to log_entries under the right schema/workflow.
+ """
assert self._conn is not None
team_id = str(batch.team_id)
schema_id = batch.schema_id
attempt = batch.latest_attempt + 1
+ # Producer (running inside a Temporal activity) stamps workflow ids into batch metadata,
+ # so no DB round-trip is needed here.
+ workflow_id = batch.metadata.get("workflow_id") or ""
+ workflow_run_id = batch.metadata.get("workflow_run_id") or ""
+
+ # Derive workflow_type from the workflow_id prefix so non-CDC syncs (regular
+ # `external-data-job`) route to the right `log_entries` source too.
+ workflow_type = "cdc-extraction" if workflow_id.startswith("cdc-extraction-") else "external-data-job"
+
+ # LogMessagesRenderer needs workflow_type/id/run_id + team_id; log_source_id routes the line.
+ bound_keys = (
+ "team_id",
+ "schema_id",
+ "source_id",
+ "job_id",
+ "run_uuid",
+ "batch_id",
+ "resource_name",
+ "workflow_type",
+ "workflow_id",
+ "workflow_run_id",
+ "log_source_id",
+ "attempt",
+ )
+ structlog.contextvars.bind_contextvars(
+ team_id=batch.team_id,
+ schema_id=batch.schema_id,
+ source_id=batch.source_id,
+ job_id=batch.job_id,
+ run_uuid=batch.run_uuid,
+ batch_id=batch.id,
+ resource_name=batch.resource_name,
+ workflow_type=workflow_type,
+ workflow_id=workflow_id,
+ workflow_run_id=workflow_run_id,
+ log_source_id=batch.schema_id,
+ attempt=attempt,
+ )
+ try:
+ await self._process_single_inner(batch, attempt, team_id, schema_id)
+ finally:
+ # Unbind only the keys we set so any ambient context (parent logger, test setup) survives.
+ structlog.contextvars.unbind_contextvars(*bound_keys)
+
+ async def _process_single_inner(self, batch: PendingBatch, attempt: int, team_id: str, schema_id: str) -> None:
+ assert self._conn is not None
+
# Check before we even try — if already at max, fail the whole run.
if attempt > self._config.max_attempts:
logger.error(
@@ -189,6 +241,16 @@ class BatchConsumer:
await self._fail_run(batch, reason=f"max retries exceeded (attempt {attempt})")
return
+ logger.info(
+ "batch_picked_up",
+ batch_id=batch.id,
+ run_uuid=batch.run_uuid,
+ batch_index=batch.batch_index,
+ is_final_batch=batch.is_final_batch,
+ attempt=attempt,
+ resource_name=batch.resource_name,
+ )
+
# Pre-increment: if we OOM here, recovery sees attempt=N+1
# and knows this attempt was consumed.
await BatchQueue.update_status(
@@ -201,9 +263,8 @@ class BatchConsumer:
try:
start = time.monotonic()
await self._process_batch(batch)
- BATCH_PROCESSING_DURATION_SECONDS.labels(team_id=team_id, schema_id=schema_id).observe(
- time.monotonic() - start
- )
+ duration = time.monotonic() - start
+ BATCH_PROCESSING_DURATION_SECONDS.labels(team_id=team_id, schema_id=schema_id).observe(duration)
await BatchQueue.update_status(
self._conn,
@@ -212,6 +273,14 @@ class BatchConsumer:
attempt=attempt,
)
BATCHES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="success").inc()
+ logger.info(
+ "batch_processed_ok",
+ batch_id=batch.id,
+ run_uuid=batch.run_uuid,
+ batch_index=batch.batch_index,
+ is_final_batch=batch.is_final_batch,
+ duration_seconds=round(duration, 3),
+ )
except Exception as e:
BATCHES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="error").inc()
BATCH_RETRY_TOTAL.labels(attempt=str(attempt), error_type=type(e).__name__).inc()
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
index 0549fccaaaf9..6e59a33b160b 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
@@ -47,6 +47,8 @@ class PostgresProducer:
is_first_ever_sync: bool = False,
cdc_write_mode: str | None = None,
cdc_table_mode: str | None = None,
+ workflow_id: str | None = None,
+ workflow_run_id: str | None = None,
) -> None:
self._team_id = team_id
self._job_id = job_id
@@ -66,6 +68,8 @@ class PostgresProducer:
self._is_first_ever_sync = is_first_ever_sync
self._cdc_write_mode = cdc_write_mode
self._cdc_table_mode = cdc_table_mode
+ self._workflow_id = workflow_id
+ self._workflow_run_id = workflow_run_id
self._conn = psycopg.Connection.connect(database_url, autocommit=True)
self._batches_sent = 0
@@ -114,6 +118,12 @@ class PostgresProducer:
metadata["cdc_write_mode"] = self._cdc_write_mode
if self._cdc_table_mode is not None:
metadata["cdc_table_mode"] = self._cdc_table_mode
+ # Producer runs inside a Temporal activity; pass ids through so the consumer
+ # can bind log context without re-querying ExternalDataJob.
+ if self._workflow_id is not None:
+ metadata["workflow_id"] = self._workflow_id
+ if self._workflow_run_id is not None:
+ metadata["workflow_run_id"] = self._workflow_run_id
metadata["timestamp_ns"] = batch_result.timestamp_ns
self._conn.execute(
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index f779f41342f1..47a61819b38d 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -3,6 +3,8 @@ from typing import Any
import pytest
from unittest.mock import AsyncMock, patch
+import structlog
+
from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (
BatchConsumer,
ConsumerConfig,
@@ -272,3 +274,98 @@ class TestGroupByKey:
def test_empty_input(self):
assert _group_by_key([]) == {}
+
+
+class TestLogContextBinding:
+ """Verify the consumer binds the structlog contextvars `LogMessagesRenderer` needs.
+
+ The CDC Syncs UI panel queries log_entries by `(log_source='external_data_jobs',
+ log_source_id=schema_id, instance_id=workflow_run_id)`. The renderer in
+ `posthog.temporal.common.logger` reads these from the structlog event_dict, so they
+ must be bound via contextvars BEFORE downstream loggers fire.
+ """
+
+ @pytest.mark.asyncio
+ async def test_process_single_binds_log_context_for_syncs_panel(self):
+ consumer = _make_consumer()
+ batch = _make_batch(
+ latest_attempt=0,
+ metadata={"workflow_id": "cdc-extraction-source-123", "workflow_run_id": "wf-run-id-456"},
+ )
+ seen: dict[str, Any] = {}
+
+ async def capture_context(b):
+ seen.update(structlog.contextvars.get_contextvars())
+
+ consumer._process_batch = capture_context
+
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ):
+ await consumer._process_single(batch)
+
+ assert seen.get("workflow_type") == "cdc-extraction"
+ assert seen.get("workflow_id") == "cdc-extraction-source-123"
+ assert seen.get("workflow_run_id") == "wf-run-id-456"
+ assert seen.get("team_id") == batch.team_id
+ assert seen.get("log_source_id") == batch.schema_id
+ assert seen.get("schema_id") == batch.schema_id
+ assert seen.get("attempt") == 1
+
+ # Cleared after the batch returns so context doesn't leak across batches.
+ assert structlog.contextvars.get_contextvars().get("batch_id") is None
+
+ @pytest.mark.asyncio
+ async def test_process_single_binds_external_data_job_workflow_type_for_non_cdc(self):
+ """Consumer also runs non-CDC syncs (`external-data-job` workflow_id prefix)."""
+ consumer = _make_consumer()
+ batch = _make_batch(
+ latest_attempt=0,
+ metadata={
+ "workflow_id": "019df430-765a-0000-0523-040f9c48be64-2026-05-21T00:00:00",
+ "workflow_run_id": "wf-run",
+ },
+ )
+ seen: dict[str, Any] = {}
+
+ async def capture_context(b):
+ seen.update(structlog.contextvars.get_contextvars())
+
+ consumer._process_batch = capture_context
+
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ):
+ await consumer._process_single(batch)
+
+ assert seen.get("workflow_type") == "external-data-job"
+
+ @pytest.mark.asyncio
+ async def test_process_single_handles_missing_workflow_ids_in_metadata(self):
+ """Old batches enqueued before this change have no workflow ids in metadata — must not crash."""
+ consumer = _make_consumer()
+ consumer._process_batch = AsyncMock()
+
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ):
+ await consumer._process_single(_make_batch(latest_attempt=0, metadata={}))
+
+ consumer._process_batch.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_process_single_clears_context_on_error(self):
+ consumer = _make_consumer(max_attempts=3)
+ consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))
+
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ):
+ await consumer._process_single(_make_batch(latest_attempt=0))
+
+ assert "batch_id" not in structlog.contextvars.get_contextvars()
+ assert "workflow_run_id" not in structlog.contextvars.get_contextvars()
diff --git a/posthog/temporal/tests/common/test_logger.py b/posthog/temporal/tests/common/test_logger.py
index 51aea3a8fc42..cc77015bbcc9 100644
--- a/posthog/temporal/tests/common/test_logger.py
+++ b/posthog/temporal/tests/common/test_logger.py
@@ -5,6 +5,7 @@ import asyncio
import datetime as dt
import operator
import dataclasses
+from typing import cast
import pytest
import freezegun
@@ -775,3 +776,144 @@ def test_resolve_log_source_dwh_cdp_producer_job():
assert source == "dwh_cdp_producer_job"
assert source_id == "019bdc25-3569-0000-9f32-e7d02775304b"
+
+
+def test_log_messages_renderer_event_level_log_source_override():
+ """Per-event log_source_id (and log_source) overrides feed into the produce message.
+
+ CDC extraction relies on this so per-schema log lines can route under each schema
+ even though the workflow is source-scoped.
+ """
+ from posthog.temporal.common.logger import LogMessagesRenderer
+
+ renderer = LogMessagesRenderer(event_key="msg")
+ event_dict = {
+ "msg": "per-schema line",
+ "level": "info",
+ "team_id": 2,
+ "timestamp": "2024-01-01 00:00:00.000000",
+ "workflow_type": "cdc-extraction",
+ "workflow_id": "cdc-extraction-019bdc25-3569-0000-9f32-e7d02775304b-2026-05-06T18:40:00Z",
+ "workflow_run_id": "abc-run-id",
+ "log_source_id": "019df430-79ff-0000-4434-e9fc02f7216b", # per-schema override
+ }
+
+ # `LogMessagesRenderer.__call__` ignores the logger arg in this branch; cast to satisfy mypy.
+ from posthog.temporal.common.logger import Logger
+
+ rendered = renderer(logger=cast(Logger, None), name="info", event_dict=event_dict)
+ assert rendered["produce_message"] is not None
+
+ payload = json.loads(rendered["produce_message"].decode("utf-8"))
+ assert payload["log_source"] == "external_data_jobs"
+ assert payload["log_source_id"] == "019df430-79ff-0000-4434-e9fc02f7216b"
+ assert payload["instance_id"] == "abc-run-id"
+
+
+def test_log_messages_renderer_appends_resource_to_message():
+ """`resource_name` / `resource` in the event dict gets appended to the produce message text.
+
+ CDC schemas with `cdc_table_mode='both'` produce two parallel batches per logical event
+ (one per write target). Without the inline marker the Syncs UI shows two identical-looking
+ rows; the marker keeps them distinguishable.
+ """
+ from posthog.temporal.common.logger import Logger, LogMessagesRenderer
+
+ renderer = LogMessagesRenderer(event_key="msg")
+ event_dict = {
+ "msg": "cdc_batch_written",
+ "level": "info",
+ "team_id": 2,
+ "timestamp": "2024-01-01 00:00:00.000000",
+ "workflow_type": "cdc-extraction",
+ "workflow_id": "cdc-extraction-019bdc25-3569-0000-9f32-e7d02775304b-2026-05-06T18:40:00Z",
+ "workflow_run_id": "abc-run-id",
+ "log_source_id": "019df430-79ff-0000-4434-e9fc02f7216b",
+ "resource": "example_table_cdc",
+ }
+
+ rendered = renderer(logger=cast(Logger, None), name="info", event_dict=event_dict)
+ produced = rendered["produce_message"]
+ assert produced is not None
+ payload = json.loads(produced.decode("utf-8"))
+ assert payload["message"] == "cdc_batch_written [example_table_cdc]"
+
+ # `resource_name` (consumer-side contextvar) works too.
+ event_dict2 = dict(event_dict)
+ event_dict2.pop("resource")
+ event_dict2["resource_name"] = "example_table"
+ event_dict2["msg"] = "batch_picked_up"
+ rendered2 = renderer(logger=cast(Logger, None), name="info", event_dict=event_dict2)
+ produced2 = rendered2["produce_message"]
+ assert produced2 is not None
+ payload2 = json.loads(produced2.decode("utf-8"))
+ assert payload2["message"] == "batch_picked_up [example_table]"
+
+ # Lines without a resource marker render unchanged.
+ event_dict3 = dict(event_dict)
+ event_dict3.pop("resource")
+ event_dict3["msg"] = "cdc_extract_completed"
+ rendered3 = renderer(logger=cast(Logger, None), name="info", event_dict=event_dict3)
+ produced3 = rendered3["produce_message"]
+ assert produced3 is not None
+ payload3 = json.loads(produced3.decode("utf-8"))
+ assert payload3["message"] == "cdc_extract_completed"
+
+ # `batch_index` appends after the resource marker so consecutive batches are distinct.
+ event_dict4 = dict(event_dict)
+ event_dict4["msg"] = "batch_picked_up"
+ event_dict4["batch_index"] = 2
+ rendered4 = renderer(logger=cast(Logger, None), name="info", event_dict=event_dict4)
+ produced4 = rendered4["produce_message"]
+ assert produced4 is not None
+ payload4 = json.loads(produced4.decode("utf-8"))
+ assert payload4["message"] == "batch_picked_up [example_table_cdc] #2"
+
+ # `batch_index` alone (no resource) still appends.
+ event_dict5 = dict(event_dict)
+ event_dict5.pop("resource")
+ event_dict5["msg"] = "batch_failed_will_retry"
+ event_dict5["batch_index"] = 0
+ rendered5 = renderer(logger=cast(Logger, None), name="info", event_dict=event_dict5)
+ produced5 = rendered5["produce_message"]
+ assert produced5 is not None
+ payload5 = json.loads(produced5.decode("utf-8"))
+ assert payload5["message"] == "batch_failed_will_retry #0"
+
+
+def test_log_messages_renderer_does_not_append_for_non_data_warehouse_log_sources():
+ """Other Temporal workflows (batch exports, data modeling, etc.) must not see their
+ message text reshaped by the CDC-targeted resource/batch_index appender."""
+ from posthog.temporal.common.logger import Logger, LogMessagesRenderer
+
+ renderer = LogMessagesRenderer(event_key="msg")
+ event_dict = {
+ "msg": "batch_export_started",
+ "level": "info",
+ "team_id": 2,
+ "timestamp": "2024-01-01 00:00:00.000000",
+ "workflow_type": "s3-batch-export",
+ "workflow_id": "019bdc25-3569-0000-9f32-e7d02775304b-2024-01-01T00:00:00",
+ "workflow_run_id": "run-id",
+ # Even if a batch_export happens to log these fields, message must be unchanged.
+ "resource_name": "should_not_appear",
+ "batch_index": 42,
+ }
+
+ rendered = renderer(logger=cast(Logger, None), name="info", event_dict=event_dict)
+ produced = rendered["produce_message"]
+ assert produced is not None
+ payload = json.loads(produced.decode("utf-8"))
+ assert payload["message"] == "batch_export_started"
+
+
+def test_resolve_log_source_cdc_extraction():
+ # CDC schedule fires workflows with id `cdc-extraction-{source_uuid}-{iso_ts}`. The renderer
+ # uses the source uuid as the default log_source_id; per-schema log lines override it at emit time.
+ source, source_id = resolve_log_source(
+ "cdc-extraction",
+ "cdc-extraction-019bdc25-3569-0000-9f32-e7d02775304b-2026-05-06T18:40:00Z",
+ )
+
+ assert source == "external_data_jobs"
+ assert source_id == "019bdc25-3569-0000-9f32-e7d02775304b"
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.py
index 921a4ed9ae9b..f18ff9be525d 100644
--- a/products/data_warehouse/backend/api/external_data_schema.py
+++ b/products/data_warehouse/backend/api/external_data_schema.py
@@ -55,6 +55,63 @@ from products.warehouse_sources.backend.models.external_data_source import Exter
logger = structlog.get_logger(__name__)
+_CDC_WRITE_TARGETS_BY_TABLE_MODE: dict[str, frozenset[str]] = {
+ "consolidated": frozenset({"consolidated"}),
+ "cdc_only": frozenset({"cdc_history"}),
+ "both": frozenset({"consolidated", "cdc_history"}),
+}
+
+
+def _cdc_table_mode_change_needs_resnapshot(old_mode: str | None, new_mode: str | None) -> bool:
+ """True when the new mode adds a physical write target (consolidated and/or cdc history table)."""
+ if old_mode == new_mode:
+ return False
+ old_targets = _CDC_WRITE_TARGETS_BY_TABLE_MODE.get(old_mode or "", frozenset())
+ new_targets = _CDC_WRITE_TARGETS_BY_TABLE_MODE.get(new_mode or "", frozenset())
+ return bool(new_targets - old_targets)
+
+
+def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:
+ """Cancel any running workflow and reset schema state so the next run does a full snapshot.
+
+ Must save before triggering: the workflow reloads the schema and bails via
+ `CDCHandledExternally` if it sees `cdc_mode='streaming'`.
+ """
+ latest_running_job = (
+ ExternalDataJob.objects.filter(schema_id=instance.pk, team_id=instance.team_id).order_by("-created_at").first()
+ )
+ if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":
+ try:
+ cancel_external_data_workflow(latest_running_job.workflow_id)
+ except temporalio.service.RPCError as e:
+ logger.exception(
+ "Could not cancel running workflow before re-snapshot",
+ schema_id=str(instance.id),
+ exc_info=e,
+ )
+
+ instance.sync_type_config["reset_pipeline"] = True
+ instance.sync_type_config["cdc_mode"] = "snapshot"
+ instance.sync_type_config.pop("cdc_last_log_position", None)
+ instance.sync_type_config.pop("cdc_deferred_runs", None)
+ instance.initial_sync_complete = False
+ instance.status = ExternalDataSchema.Status.RUNNING
+ instance.save()
+
+ try:
+ trigger_external_data_workflow(instance)
+ except temporalio.service.RPCError as e:
+ logger.exception(
+ "Could not trigger external data workflow after re-snapshot reset",
+ schema_id=str(instance.id),
+ exc_info=e,
+ )
+ # Roll the status back so the Syncs UI doesn't show RUNNING for a workflow that never started.
+ # The sync_type_config mutations stay — the schema's intent is still "do a re-snapshot next run".
+ instance.status = ExternalDataSchema.Status.FAILED
+ instance.save(update_fields=["status"])
+
+
class ExternalDataSchemaSerializer(serializers.ModelSerializer):
table = serializers.SerializerMethodField(read_only=True)
incremental = serializers.SerializerMethodField(read_only=True)
@@ -243,6 +300,24 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
def update(self, instance: ExternalDataSchema, validated_data: dict[str, Any]) -> ExternalDataSchema:
data = self.initial_data if isinstance(self.initial_data, dict) else {}
+ # Capture the previous cdc_table_mode before any mutation so the post-save hook below can decide
+ # whether the change adds a new physical write target (and therefore needs a re-snapshot).
+ previous_cdc_table_mode = instance.cdc_table_mode
+
+ # Refuse cdc_table_mode transitions that would kick a re-snapshot when the team is over its
+ # monthly sync billing limit. Checked here (pre-save) so we don't end up with the new mode
+ # persisted but no resnapshot triggered. Mirrors the gate in `resync` / `reload`.
+ if (
+ instance.sync_type == ExternalDataSchema.SyncType.CDC
+ and "cdc_table_mode" in data
+ and _cdc_table_mode_change_needs_resnapshot(previous_cdc_table_mode, data.get("cdc_table_mode"))
+ and is_any_external_data_schema_paused(instance.team_id)
+ ):
+ raise ValidationError(
+ "Monthly sync limit reached. Please increase your billing limit before changing "
+ "the CDC table mode — a full re-snapshot would be required."
+ )
+
# Pop non-model fields from validated_data so super().update() doesn't try to set them
validated_data.pop("sync_type", None)
validated_data.pop("sync_frequency", None)
@@ -483,6 +558,20 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
self._run_temporal_side_effect(sync_cdc_schedule)
+ # If the cdc_table_mode change added a new physical write target, kick a full re-snapshot so the
+ # new table is seeded from the current source state. `_seed_cdc_companion_from_snapshot` runs
+ # automatically once the snapshot completes via `run_post_load_operations`.
+ if is_cdc and "cdc_table_mode" in data:
+ new_cdc_table_mode = data.get("cdc_table_mode")
+ if _cdc_table_mode_change_needs_resnapshot(previous_cdc_table_mode, new_cdc_table_mode):
+ logger.info(
+ "cdc_table_mode_changed_resnapshot_triggered",
+ schema_id=str(updated_instance.id),
+ old_cdc_table_mode=previous_cdc_table_mode,
+ new_cdc_table_mode=new_cdc_table_mode,
+ )
+ self._run_temporal_side_effect(lambda: _reset_cdc_for_full_resnapshot(updated_instance))
+
return updated_instance
def _maybe_create_webhook(self, schema: ExternalDataSchema) -> None:
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 891ff6064c58..469fee7ef933 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -395,6 +395,14 @@ class ExternalDataSourceBulkUpdateSchemasSerializer(serializers.Serializer):
class ExternalDataJobSerializers(serializers.ModelSerializer):
schema = serializers.SerializerMethodField(read_only=True)
status = serializers.SerializerMethodField(read_only=True)
+ cdc_write_mode = serializers.SerializerMethodField(
+ read_only=True,
+ help_text=(
+ "For CDC syncs with `cdc_table_mode='both'`, distinguishes the two ExternalDataJob "
+ "rows produced per sync: `incremental_merge` (consolidated table) vs `scd2_append` "
+ "(cdc-only history table). `null` for non-CDC syncs. Read from `schema_snapshot`."
+ ),
+ )
class Meta:
model = ExternalDataJob
@@ -408,6 +416,7 @@ class ExternalDataJobSerializers(serializers.ModelSerializer):
"rows_synced",
"latest_error",
"workflow_run_id",
+ "cdc_write_mode",
]
read_only_fields = [
"id",
@@ -419,8 +428,12 @@ class ExternalDataJobSerializers(serializers.ModelSerializer):
"rows_synced",
"latest_error",
"workflow_run_id",
+ "cdc_write_mode",
]
+ def get_cdc_write_mode(self, instance: ExternalDataJob) -> str | None:
+ return (instance.schema_snapshot or {}).get("cdc_write_mode")
+
def get_status(self, instance: ExternalDataJob):
if instance.status == ExternalDataJob.Status.BILLING_LIMIT_REACHED:
return "Billing limits"
@@ -1306,7 +1319,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
management_mode = payload.get("cdc_management_mode", "posthog")
slot_name = payload.get("cdc_slot_name") or f"posthog_{source_model.id.hex[:12]}"
- pub_name = payload.get("cdc_publication_name") or f"posthog_pub_{source_model.id.hex[:12]}"
+ default_pub_name = (
+ "posthog_pub" if management_mode == "self_managed" else f"posthog_pub_{source_model.id.hex[:12]}"
+ )
+ pub_name = payload.get("cdc_publication_name") or default_pub_name
# Store CDC config in job_inputs
job_inputs = source_model.job_inputs or {}
diff --git a/products/data_warehouse/backend/api/test/test_cdc_table_mode_patch.py b/products/data_warehouse/backend/api/test/test_cdc_table_mode_patch.py
new file mode 100644
index 000000000000..ce8cd2a61fe2
--- /dev/null
+++ b/products/data_warehouse/backend/api/test/test_cdc_table_mode_patch.py
@@ -0,0 +1,292 @@
+"""Tests for PATCH `cdc_table_mode` semantics on the ExternalDataSchema viewset.
+
+Uses pytest function-scoped fixtures (rather than `APIBaseTest`) to avoid mixing
+TransactionTestCase semantics into the same module/process as the existing pytest
+fixture-based tests in `test_external_data_schema.py` — that mix causes pytest-django
+to behave inconsistently with the live `temporal` fixture used there.
+
+Every external dependency (workflow trigger/cancel, schedule sync, CDC publication
+mutation) is mocked. These tests only exercise the serializer + helper logic.
+"""
+
+import pytest
+from unittest import mock
+
+from django.test.client import Client as HttpClient
+
+from posthog.api.test.test_organization import create_organization
+from posthog.api.test.test_team import create_team
+from posthog.api.test.test_user import create_user
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+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
+
+pytestmark = [pytest.mark.django_db]
+
+
+_PATCH_TARGETS = {
+ "is_cdc_enabled_for_team": "products.data_warehouse.backend.api.external_data_schema.is_cdc_enabled_for_team",
+ "alter_cdc_publication": (
+ "products.data_warehouse.backend.api.external_data_schema.ExternalDataSchemaSerializer._alter_cdc_publication"
+ ),
+ "external_data_workflow_exists": (
+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists"
+ ),
+ "sync_external_data_job_workflow": (
+ "products.data_warehouse.backend.api.external_data_schema.sync_external_data_job_workflow"
+ ),
+ "sync_cdc_extraction_schedule": (
+ "products.data_warehouse.backend.api.external_data_schema.sync_cdc_extraction_schedule"
+ ),
+ "cancel_external_data_workflow": (
+ "products.data_warehouse.backend.api.external_data_schema.cancel_external_data_workflow"
+ ),
+ "trigger_external_data_workflow": (
+ "products.data_warehouse.backend.api.external_data_schema.trigger_external_data_workflow"
+ ),
+ "is_any_external_data_schema_paused": (
+ "products.data_warehouse.backend.api.external_data_schema.is_any_external_data_schema_paused"
+ ),
+}
+
+
+def organization():
+ org = create_organization("Test Org")
+ yield org
+ org.delete()
+
+
+def team(organization):
+ t = create_team(organization)
+ yield t
+ t.delete()
+
+
+def user(team):
+ u = create_user("[email protected]", "Test User", team.organization)
+ yield u
+ u.delete()
+
+
+def _make_cdc_source_and_schema(
+ team,
+ cdc_table_mode: str,
+ cdc_last_log_position: str | None = "0/12345",
+ cdc_deferred_runs: list[dict] | None = None,
+ initial_sync_complete: bool = True,
+) -> tuple[ExternalDataSource, ExternalDataSchema]:
+ source = ExternalDataSource.objects.create(
+ team=team,
+ source_type=ExternalDataSourceType.POSTGRES,
+ job_inputs={
+ "schema": "public",
+ "cdc_enabled": True,
+ "cdc_management_mode": "posthog",
+ "cdc_slot_name": "test_slot",
+ "cdc_publication_name": "test_pub",
+ },
+ )
+ sync_type_config: dict = {
+ "cdc_mode": "streaming",
+ "cdc_table_mode": cdc_table_mode,
+ "primary_key_columns": ["id"],
+ }
+ if cdc_last_log_position is not None:
+ sync_type_config["cdc_last_log_position"] = cdc_last_log_position
+ if cdc_deferred_runs is not None:
+ sync_type_config["cdc_deferred_runs"] = cdc_deferred_runs
+
+ schema = ExternalDataSchema.objects.create(
+ team=team,
+ source=source,
+ name="orders",
+ should_sync=True,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ initial_sync_complete=initial_sync_complete,
+ sync_type_config=sync_type_config,
+ )
+ return source, schema
+
+
+ ("old_mode", "new_mode"),
+ [
+ ("consolidated", "cdc_only"),
+ ("consolidated", "both"),
+ ("cdc_only", "consolidated"),
+ ("cdc_only", "both"),
+ ],
+)
+def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(team, user, client: HttpClient, old_mode, new_mode):
+ source, schema = _make_cdc_source_and_schema(
+ team,
+ cdc_table_mode=old_mode,
+ cdc_deferred_runs=[{"job_id": "stale", "run_uuid": "stale", "batch_results": []}],
+ )
+ running_job = ExternalDataJob.objects.create(
+ team=team,
+ pipeline=source,
+ schema=schema,
+ status=ExternalDataJob.Status.RUNNING,
+ workflow_id="running-workflow-id",
+ )
+ client.force_login(user)
+
+ with (
+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),
+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]),
+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),
+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),
+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),
+ mock.patch(_PATCH_TARGETS["cancel_external_data_workflow"]) as mock_cancel,
+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as mock_trigger,
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"cdc_table_mode": new_mode},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+
+ schema.refresh_from_db()
+ assert schema.cdc_table_mode == new_mode
+ assert schema.sync_type_config.get("cdc_mode") == "snapshot"
+ assert schema.sync_type_config.get("cdc_last_log_position") is None
+ assert schema.sync_type_config.get("cdc_deferred_runs") is None
+ assert schema.initial_sync_complete is False
+ assert schema.sync_type_config.get("reset_pipeline") is True
+ mock_cancel.assert_called_once_with(running_job.workflow_id)
+ mock_trigger.assert_called_once()
+
+
+ ("old_mode", "new_mode"),
+ [
+ ("both", "consolidated"),
+ ("both", "cdc_only"),
+ ],
+)
+def test_patch_cdc_table_mode_dropping_target_skips_resnapshot(team, user, client: HttpClient, old_mode, new_mode):
+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode=old_mode)
+ client.force_login(user)
+
+ with (
+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),
+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]),
+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),
+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),
+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),
+ mock.patch(_PATCH_TARGETS["cancel_external_data_workflow"]) as mock_cancel,
+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as mock_trigger,
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"cdc_table_mode": new_mode},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+
+ schema.refresh_from_db()
+ assert schema.cdc_table_mode == new_mode
+ # Streaming state preserved — the remaining target table still holds current data.
+ assert schema.sync_type_config.get("cdc_mode") == "streaming"
+ assert schema.sync_type_config.get("cdc_last_log_position") == "0/12345"
+ assert schema.initial_sync_complete is True
+ mock_cancel.assert_not_called()
+ mock_trigger.assert_not_called()
+
+
+def test_patch_cdc_table_mode_idempotent_skips_resnapshot(team, user, client: HttpClient):
+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode="both", cdc_last_log_position="0/9999")
+ client.force_login(user)
+
+ with (
+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),
+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]),
+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),
+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),
+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),
+ mock.patch(_PATCH_TARGETS["cancel_external_data_workflow"]) as mock_cancel,
+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as mock_trigger,
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"cdc_table_mode": "both"},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+
+ schema.refresh_from_db()
+ assert schema.sync_type_config.get("cdc_mode") == "streaming"
+ assert schema.initial_sync_complete is True
+ mock_cancel.assert_not_called()
+ mock_trigger.assert_not_called()
+
+
+def test_patch_cdc_table_mode_rejected_when_team_over_billing_limit(team, user, client: HttpClient):
+ """Re-snapshot-triggering transitions are gated on the team being under their sync billing limit
+ — otherwise the new job would land immediately in BillingLimit state. Pre-save check so the new
+ mode doesn't get persisted without an actual resnapshot."""
+ source, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated")
+ client.force_login(user)
+
+ with (
+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),
+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]),
+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),
+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),
+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),
+ mock.patch(_PATCH_TARGETS["cancel_external_data_workflow"]) as mock_cancel,
+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as mock_trigger,
+ mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=True),
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"cdc_table_mode": "both"},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 400, response.content
+ assert b"Monthly sync limit reached" in response.content
+
+ schema.refresh_from_db()
+ # Mode unchanged; no workflow side-effects fired.
+ assert schema.cdc_table_mode == "consolidated"
+ assert schema.sync_type_config.get("cdc_mode") == "streaming"
+ mock_cancel.assert_not_called()
+ mock_trigger.assert_not_called()
+
+
+def test_patch_cdc_table_mode_drop_target_allowed_when_team_over_billing_limit(team, user, client: HttpClient):
+ """Drop-target transitions don't kick a re-snapshot, so the billing gate doesn't apply — the
+ schema's existing tables already hold current data."""
+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode="both")
+ client.force_login(user)
+
+ with (
+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),
+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]),
+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),
+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),
+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),
+ mock.patch(_PATCH_TARGETS["cancel_external_data_workflow"]),
+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),
+ mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=True),
+ ):
+ response = client.patch(
+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",
+ data={"cdc_table_mode": "consolidated"},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200, response.content
+ schema.refresh_from_db()
+ assert schema.cdc_table_mode == "consolidated"
diff --git a/products/data_warehouse/backend/data_load/service.py b/products/data_warehouse/backend/data_load/service.py
index 26b03545977e..e6b3cb6b38e4 100644
--- a/products/data_warehouse/backend/data_load/service.py
+++ b/products/data_warehouse/backend/data_load/service.py
@@ -270,12 +270,6 @@ def is_any_external_data_schema_paused(team_id: int) -> bool:
def is_cdc_enabled_for_team(team: Team) -> bool:
- """Check if the CDC feature flag is enabled for a team."""
- from django.conf import settings
-
- if settings.DEBUG:
- return True
-
import posthoganalytics
return posthoganalytics.feature_enabled(
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
index 31e0e89120d0..7e9601cfce3f 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
@@ -84,6 +84,15 @@ export const SyncsTab = ({ id }: SyncsTabProps): JSX.Element => {
title: 'Schema',
render: (_, job) => {
const name = job.schema.label ?? job.schema.name
+ // CDC `cdc_table_mode='both'` produces two ExternalDataJob rows per sync —
+ // one for the consolidated table, one for the cdc-only history table.
+ // Show a badge so they're distinguishable in the UI.
+ const cdcWriteModeLabel =
+ job.cdc_write_mode === 'scd2_append'
+ ? 'CDC history'
+ : job.cdc_write_mode === 'incremental_merge'
+ ? 'consolidated'
+ : null
return (
<span className="flex items-center gap-1">
{name}
@@ -92,6 +101,11 @@ export const SyncsTab = ({ id }: SyncsTabProps): JSX.Element => {
CDC
</LemonTag>
)}
+ {cdcWriteModeLabel && (
+ <LemonTag type="muted" size="small">
+ {cdcWriteModeLabel}
+ </LemonTag>
+ )}
</span>
)
},
diff --git a/products/warehouse_sources/backend/models/external_data_job.py b/products/warehouse_sources/backend/models/external_data_job.py
index aad164851e02..eb4945a24ac3 100644
--- a/products/warehouse_sources/backend/models/external_data_job.py
+++ b/products/warehouse_sources/backend/models/external_data_job.py
@@ -35,6 +35,8 @@ class ExternalDataJob(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
billable = models.BooleanField(default=True, null=True, blank=True)
finished_at = models.DateTimeField(null=True, blank=True)
storage_delta_mib = models.FloatField(null=True, blank=True, default=0)
+ # Also stores `cdc_write_mode` (`incremental_merge` | `scd2_append`) so the Syncs UI can
+ # distinguish the two ExternalDataJob rows produced when `cdc_table_mode='both'`.
schema_snapshot = models.JSONField(
null=True,
blank=True,