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.

feat(data-warehouse): add CDC extraction and sweeper metrics (#65589)

Daniel RCcc3a3177a0ac
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index b7aafc293dae..38de8be614a9 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -11,6 +11,7 @@ validate_cdc_prerequisites_activity: Wraps prerequisite validator for Temporal.
from __future__ import annotations
+import time
import uuid
import typing
import datetime as dt
@@ -27,6 +28,7 @@ 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.heartbeat_sync import HeartbeaterSync
+from posthog.temporal.data_imports.cdc import metrics
from posthog.temporal.data_imports.cdc.adapters import cdc_supported_source_types, get_cdc_adapter
from posthog.temporal.data_imports.cdc.batcher import (
ChangeEventBatcher,
@@ -146,6 +148,8 @@ class CDCExtractActivity:
self.last_complete_txn_end_lsn: str | None = None
self.event_count: int = 0
self.all_table_names: set[str] = set()
+ # Wall-clock start, set in run(); drives cdc_extraction_duration_seconds.
+ self._run_started_at: float | None = None
# ------------------------------------------------------------------
# Logger helpers
@@ -154,6 +158,36 @@ class CDCExtractActivity:
"""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))
+ # ------------------------------------------------------------------
+ # Metrics helpers
+ # ------------------------------------------------------------------
+ def _emit_run_duration(self, status: str) -> None:
+ if self._run_started_at is None:
+ return
+ metrics.get_extraction_duration_metric(self.inputs.team_id, str(self.inputs.source_id), status).record(
+ time.monotonic() - self._run_started_at
+ )
+
+ def _emit_deferred_runs_depth(self) -> None:
+ """Set the per-source deferred-runs gauge to the current depth across all CDC schemas.
+
+ A gauge re-exports its last value, so it must be refreshed whenever deferred runs are
+ stored OR drained — otherwise it reads stale-high after a flush. Summed across schemas
+ because the gauge is keyed by source, not schema.
+ """
+ depth = sum(len(s.sync_type_config.get("cdc_deferred_runs") or []) for s in self.cdc_schemas)
+ metrics.get_deferred_runs_depth_metric(self.inputs.team_id, str(self.inputs.source_id)).set(depth)
+
+ def _confirm_position(self, lsn: str) -> None:
+ """Advance the replication slot, recording success/failure metrics."""
+ source_id = str(self.inputs.source_id)
+ try:
+ self.reader.confirm_position(lsn)
+ except Exception:
+ metrics.get_slot_advance_failures_metric(self.inputs.team_id, source_id).add(1)
+ raise
+ metrics.get_slot_advance_metric(self.inputs.team_id, source_id).add(1)
+
# ------------------------------------------------------------------
# Schema fetching (kept as a method so tests can patch it on the class)
# ------------------------------------------------------------------
@@ -273,6 +307,7 @@ class CDCExtractActivity:
producer.close()
self._update_schema_sync_type_config(schema, updates={"cdc_deferred_runs": []})
+ self._emit_deferred_runs_depth()
log.info("deferred_runs_flushed", schema_id=str(schema.id))
@@ -426,6 +461,7 @@ class CDCExtractActivity:
entry["total_rows"] = tracker.total_rows
self._update_schema_sync_type_config(schema, mutate=_append_batch)
+ self._emit_deferred_runs_depth()
self._schema_log(schema).info(
"cdc_deferred_run_stored",
@@ -495,6 +531,7 @@ class CDCExtractActivity:
Returns the set of write_resource_names that received data.
"""
flushed: set[str] = set()
+ events_extracted = 0
for table_name, raw_table in tables.items():
schema = self.schema_by_name.get(table_name)
@@ -503,6 +540,9 @@ class CDCExtractActivity:
activity.heartbeat()
+ # raw_table has one row per source change event (before SCD2/dedup fan-out).
+ events_extracted += raw_table.num_rows
+
key_columns = self.pk_columns_by_table.get(table_name, [])
cdc_table_mode = schema.cdc_table_mode
@@ -559,6 +599,9 @@ class CDCExtractActivity:
elif schema.cdc_mode == "snapshot":
self._store_deferred_batch(tracker, batch_result, schema)
+ if events_extracted:
+ metrics.get_events_extracted_metric(self.inputs.team_id, str(self.inputs.source_id)).add(events_extracted)
+
return flushed
# ------------------------------------------------------------------
@@ -578,6 +621,7 @@ class CDCExtractActivity:
5. Update cdc_last_log_position per schema
"""
close_old_connections()
+ self._run_started_at = time.monotonic()
self.log.info("cdc_extract_started")
if not self._setup():
@@ -610,6 +654,7 @@ class CDCExtractActivity:
if self.adapter is not None and self.adapter.is_slot_invalidation_error(exc):
try:
self._recover_from_slot_invalidation(exc)
+ self._emit_run_duration("recovered")
return
except Exception as recovery_exc:
self.log.exception("cdc_slot_recovery_failed")
@@ -798,6 +843,7 @@ class CDCExtractActivity:
tables = self.batcher.flush()
self.all_table_names.update(tables.keys())
self._process_flush(tables, is_final=False)
+ metrics.get_micro_batches_flushed_metric(self.inputs.team_id, str(self.inputs.source_id)).add(1)
# Advance only to the end of the last FULLY-yielded transaction, never to
# last_end_lsn: a micro-flush can fire mid-transaction (the batcher
# threshold is checked per event), and every event of the in-flight
@@ -814,7 +860,7 @@ class CDCExtractActivity:
self.last_complete_txn_end_lsn is not None
and self.last_complete_txn_end_lsn != self.last_confirmed_lsn
):
- self.reader.confirm_position(self.last_complete_txn_end_lsn)
+ self._confirm_position(self.last_complete_txn_end_lsn)
self.last_confirmed_lsn = self.last_complete_txn_end_lsn
self.log.info(
"cdc_micro_batch_flushed",
@@ -873,6 +919,8 @@ class CDCExtractActivity:
removes=removes,
extra_model_fields={"initial_sync_complete": False},
)
+ if clear_deferred_runs:
+ self._emit_deferred_runs_depth()
def _unpause_schema_schedule(self, schema: ExternalDataSchema) -> None:
schema_log = self._schema_log(schema)
@@ -889,7 +937,7 @@ class CDCExtractActivity:
if truncated_tables:
truncate_end_lsn = self.reader.last_commit_end_lsn
if truncate_end_lsn is not None:
- self.reader.confirm_position(truncate_end_lsn)
+ self._confirm_position(truncate_end_lsn)
self.log.info("slot_advanced_past_truncate", position=truncate_end_lsn)
now = dt.datetime.now(tz=dt.UTC)
@@ -904,6 +952,7 @@ class CDCExtractActivity:
truncated_tables=truncated_tables,
)
self.log.info("no_wal_changes")
+ self._emit_run_duration("no_changes")
# ------------------------------------------------------------------
# Flush + finalization
@@ -967,7 +1016,7 @@ class CDCExtractActivity:
the last incremental advance.
"""
if self.last_end_lsn is not None and self.last_end_lsn != self.last_confirmed_lsn:
- self.reader.confirm_position(self.last_end_lsn)
+ self._confirm_position(self.last_end_lsn)
self.log.info("slot_advanced", position=self.last_end_lsn)
def _update_log_positions(self) -> None:
@@ -1058,6 +1107,7 @@ class CDCExtractActivity:
self._schema_log(schema).error(
"cdc_extract_schema_failed", error=str(exc), category=info.category, retryable=info.retryable
)
+ self._emit_run_duration("failed")
return info
def _capture_non_retryable(self, info: CDCErrorInfo) -> None:
@@ -1086,6 +1136,7 @@ class CDCExtractActivity:
# Breadcrumb for idle tables; _handle_no_changes only covers the whole-source-quiet case.
if schema.name not in synced_tables:
self._schema_log(schema).info("cdc_extract_no_changes")
+ self._emit_run_duration("completed")
@activity.defn
@@ -1131,6 +1182,8 @@ def cleanup_orphan_slots_activity() -> None:
log = logger.bind()
log.info("cleanup_orphan_slots_started")
+ sweep_started_mono = time.monotonic()
+ sweep_started = dt.datetime.now(tz=dt.UTC)
# The CDC fields live in `job_inputs`, an EncryptedJSONField: every leaf value is
# Fernet-encrypted at rest, so `job_inputs__cdc_enabled=True` (and the slot/publication
@@ -1142,7 +1195,6 @@ def cleanup_orphan_slots_activity() -> None:
sources_checked = 0
sources_errored = 0
slots_dropped = 0
- sweep_started = dt.datetime.now(tz=dt.UTC)
# A single source's management connection (10s connect_timeout × several ops) can stall the
# loop, so heartbeat from a background thread rather than once per iteration — otherwise a
# stalled source would starve heartbeats and Temporal would kill the whole sweep.
@@ -1157,6 +1209,7 @@ def cleanup_orphan_slots_activity() -> None:
cdc_config = adapter.parse_cdc_config(source)
except Exception:
log.exception("failed_to_parse_cdc_config", source_id=str(source.id))
+ metrics.get_sweeper_source_errors_metric().add(1)
sources_errored += 1
continue
@@ -1183,6 +1236,7 @@ def cleanup_orphan_slots_activity() -> None:
delete_cdc_extraction_schedule(str(source.id))
except Exception:
source_log.exception("failed_to_delete_cdc_extraction_schedule")
+ metrics.get_sweeper_source_errors_metric().add(1)
if cdc_config.management_mode == "posthog":
source_log.info("cleaning_up_deleted_source_slot")
@@ -1192,6 +1246,7 @@ def cleanup_orphan_slots_activity() -> None:
slots_dropped += 1
except Exception:
source_log.exception("failed_to_cleanup_deleted_source_slot")
+ metrics.get_sweeper_source_errors_metric().add(1)
sources_errored += 1
continue
@@ -1203,6 +1258,7 @@ def cleanup_orphan_slots_activity() -> None:
retention_cap_mb = adapter.get_retention_cap_mb(conn)
except Exception:
source_log.exception("failed_to_check_slot_lag")
+ metrics.get_sweeper_source_errors_metric().add(1)
sources_errored += 1
continue
@@ -1210,6 +1266,7 @@ def cleanup_orphan_slots_activity() -> None:
source_log.warning("slot_not_found_or_no_flush_lsn")
continue
+ metrics.get_wal_lag_metric(source.team_id, str(source.id)).set(lag_bytes)
lag_mb = lag_bytes / (1024 * 1024)
critical_threshold_mb = cdc_config.lag_critical_threshold_mb
@@ -1233,8 +1290,10 @@ def cleanup_orphan_slots_activity() -> None:
slots_dropped += 1
source.status = ExternalDataSource.Status.ERROR
source.save(update_fields=["status", "updated_at"])
+ metrics.get_auto_drop_metric(source.team_id, str(source.id)).add(1)
except Exception:
source_log.exception("failed_to_auto_drop_slot")
+ metrics.get_sweeper_source_errors_metric().add(1)
sources_errored += 1
elif cdc_config.management_mode == "self_managed":
try:
@@ -1257,6 +1316,8 @@ def cleanup_orphan_slots_activity() -> None:
duration_ms=round((dt.datetime.now(tz=dt.UTC) - source_started).total_seconds() * 1000),
)
+ metrics.get_sweeper_sources_checked_metric().add(sources_checked)
+ metrics.get_sweeper_duration_metric().record(time.monotonic() - sweep_started_mono)
log.info(
"cleanup_orphan_slots_completed",
sources_checked=sources_checked,
diff --git a/posthog/temporal/data_imports/cdc/metrics.py b/posthog/temporal/data_imports/cdc/metrics.py
new file mode 100644
index 000000000000..543e8fdd02cd
--- /dev/null
+++ b/posthog/temporal/data_imports/cdc/metrics.py
@@ -0,0 +1,94 @@
+"""CDC Temporal metrics.
+
+Factory functions over the temporalio activity metric meter, mirroring
+`pipeline_v3/metrics.py`. Both the extraction and the orphan-slot sweeper run as
+activities, so `activity.metric_meter()` is the right meter for either.
+
+Attribute cardinality is kept to team_id/source_id (sweeper-wide metrics carry no
+per-source attributes) to match the pipeline_v3 convention.
+
+CDC activity bodies are also unit-tested by direct instantiation, outside any
+activity context, where `activity.metric_meter()` raises. `_meter()` falls back to
+the no-op meter there so instrumented code stays safe to call from anywhere.
+"""
+
+from __future__ import annotations
+
+from temporalio import activity
+from temporalio.common import MetricCounter, MetricGauge, MetricHistogramFloat, MetricMeter
+
+
+def _meter() -> MetricMeter:
+ return activity.metric_meter() if activity.in_activity() else MetricMeter.noop
+
+
+def _source_meter(team_id: int, source_id: str) -> MetricMeter:
+ return _meter().with_additional_attributes({"team_id": str(team_id), "source_id": source_id})
+
+
+# ---------------------------------------------------------------------------
+# Extraction
+# ---------------------------------------------------------------------------
+
+
+def get_events_extracted_metric(team_id: int, source_id: str) -> MetricCounter:
+ return _source_meter(team_id, source_id).create_counter(
+ "cdc_events_extracted_total", "Total WAL change events extracted"
+ )
+
+
+def get_micro_batches_flushed_metric(team_id: int, source_id: str) -> MetricCounter:
+ return _source_meter(team_id, source_id).create_counter(
+ "cdc_micro_batches_flushed_total", "Total mid-run micro-batches flushed"
+ )
+
+
+def get_extraction_duration_metric(team_id: int, source_id: str, status: str) -> MetricHistogramFloat:
+ return (
+ _meter()
+ .with_additional_attributes({"team_id": str(team_id), "source_id": source_id, "status": status})
+ .create_histogram_float("cdc_extraction_duration_seconds", "Duration of CDC extraction runs", "s")
+ )
+
+
+def get_slot_advance_metric(team_id: int, source_id: str) -> MetricCounter:
+ return _source_meter(team_id, source_id).create_counter("cdc_slot_advance_total", "Total replication slot advances")
+
+
+def get_slot_advance_failures_metric(team_id: int, source_id: str) -> MetricCounter:
+ return _source_meter(team_id, source_id).create_counter(
+ "cdc_slot_advance_failures_total", "Total replication slot advance failures"
+ )
+
+
+def get_deferred_runs_depth_metric(team_id: int, source_id: str) -> MetricGauge:
+ return _source_meter(team_id, source_id).create_gauge(
+ "cdc_deferred_runs_depth", "Deferred CDC runs awaiting the snapshot→streaming flush"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Orphan-slot sweeper
+# ---------------------------------------------------------------------------
+
+
+def get_wal_lag_metric(team_id: int, source_id: str) -> MetricGauge:
+ return _source_meter(team_id, source_id).create_gauge("cdc_wal_lag_bytes", "Replication slot WAL lag", "By")
+
+
+def get_auto_drop_metric(team_id: int, source_id: str) -> MetricCounter:
+ return _source_meter(team_id, source_id).create_counter(
+ "cdc_auto_drop_total", "Total slots auto-dropped by the critical-lag safety net"
+ )
+
+
+def get_sweeper_sources_checked_metric() -> MetricCounter:
+ return _meter().create_counter("cdc_sweeper_sources_checked_total", "Total CDC sources checked by the sweeper")
+
+
+def get_sweeper_source_errors_metric() -> MetricCounter:
+ return _meter().create_counter("cdc_sweeper_source_errors_total", "Total per-source errors during the sweep")
+
+
+def get_sweeper_duration_metric() -> MetricHistogramFloat:
+ return _meter().create_histogram_float("cdc_sweeper_duration_seconds", "Duration of the orphan-slot sweep", "s")
diff --git a/posthog/temporal/data_imports/cdc/tests/test_metrics.py b/posthog/temporal/data_imports/cdc/tests/test_metrics.py
new file mode 100644
index 000000000000..1ddeed30836c
--- /dev/null
+++ b/posthog/temporal/data_imports/cdc/tests/test_metrics.py
@@ -0,0 +1,267 @@
+import uuid
+from contextlib import contextmanager
+from datetime import UTC, datetime
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from temporalio.common import MetricMeter
+from temporalio.runtime import MetricBuffer, Runtime, TelemetryConfig
+from temporalio.testing import ActivityEnvironment
+
+from posthog.temporal.data_imports.cdc import metrics
+from posthog.temporal.data_imports.cdc.activities import (
+ CDCExtractActivity,
+ CDCExtractInput,
+ cdc_extract_activity,
+ cleanup_orphan_slots_activity,
+)
+from posthog.temporal.data_imports.cdc.batcher import ChangeEventBatcher
+from posthog.temporal.data_imports.cdc.types import ChangeEvent
+from posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfig
+
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+_ACTIVITIES = "posthog.temporal.data_imports.cdc.activities"
+
+
+class TestMetricsOutsideActivityContext:
+ """Outside an activity context the meter is a no-op, so every factory must build a
+ usable metric and its emit call must not raise — this is the branch the direct-
+ instantiation activity tests rely on."""
+
+ def test_meter_falls_back_to_noop(self):
+ assert metrics._meter() is MetricMeter.noop
+
+ def test_counters_record_without_raising(self):
+ metrics.get_events_extracted_metric(1, "s").add(5)
+ metrics.get_micro_batches_flushed_metric(1, "s").add(1)
+ metrics.get_slot_advance_metric(1, "s").add(1)
+ metrics.get_slot_advance_failures_metric(1, "s").add(1)
+ metrics.get_auto_drop_metric(1, "s").add(1)
+ metrics.get_sweeper_sources_checked_metric().add(3)
+ metrics.get_sweeper_source_errors_metric().add(1)
+
+ def test_histograms_record_without_raising(self):
+ metrics.get_extraction_duration_metric(1, "s", "completed").record(1.5)
+ metrics.get_sweeper_duration_metric().record(2.0)
+
+ def test_gauges_set_without_raising(self):
+ metrics.get_deferred_runs_depth_metric(1, "s").set(2)
+ metrics.get_wal_lag_metric(1, "s").set(1024)
+
+
+# ---------------------------------------------------------------------------
+# ActivityEnvironment smoke tests — run instrumented paths against a real
+# (Rust-backed) meter so emission is exercised end-to-end. No value assertions.
+# ---------------------------------------------------------------------------
+
+
[email protected](scope="module")
+def _runtime_buffer():
+ buffer = MetricBuffer(10_000)
+ runtime = Runtime(telemetry=TelemetryConfig(metrics=buffer))
+ return runtime, buffer
+
+
+def metric_env(_runtime_buffer):
+ runtime, buffer = _runtime_buffer
+ buffer.retrieve_updates() # drop anything emitted by an earlier test
+ env = ActivityEnvironment()
+ env.metric_meter = runtime.metric_meter
+ return env, buffer
+
+
+def _emitted_names(buffer: MetricBuffer) -> set[str]:
+ return {update.metric.name for update in buffer.retrieve_updates()}
+
+
+def _make_event(op="I", table="public.users", position="0/100"):
+ return ChangeEvent(
+ operation=op,
+ table_name=table,
+ position_serialized=position,
+ timestamp=datetime(2025, 6, 15, 12, 0, 0, tzinfo=UTC),
+ columns={"id": 1, "name": "Alice"},
+ )
+
+
+def _make_source():
+ source = MagicMock()
+ source.id = uuid.uuid4()
+ source.team_id = 1
+ source.source_type = "Postgres"
+ source.deleted = False
+ source.job_inputs = {"schema": "public", "cdc_slot_name": "s", "cdc_publication_name": "p"}
+ return source
+
+
+def _make_schema(cdc_mode="streaming"):
+ schema = MagicMock()
+ schema.id = uuid.uuid4()
+ schema.name = "users"
+ schema.team_id = 1
+ schema.sync_type_config = {"cdc_mode": cdc_mode, "cdc_table_mode": "consolidated", "primary_key_columns": ["id"]}
+ schema.cdc_mode = cdc_mode
+ schema.cdc_table_mode = "consolidated"
+ schema.enabled_columns = None
+ schema.incremental_field = None
+ schema.resolved_s3_folder_name = None
+ schema.save = MagicMock()
+ return schema
+
+
+@contextmanager
+def _extract_patches(source, schemas, events):
+ reader = MagicMock()
+ reader.read_changes.return_value = iter(events)
+ reader.truncated_tables = []
+ reader.get_decoder_key_columns.return_value = []
+
+ adapter = MagicMock()
+ adapter.create_reader.return_value = reader
+ adapter.is_slot_invalidation_error.return_value = False
+
+ s3 = MagicMock()
+ batch_result = MagicMock(
+ s3_path="s3://b/p.parquet", row_count=len(events), byte_size=512, batch_index=0, timestamp_ns=1
+ )
+ s3.write_batch.return_value = batch_result
+ s3.write_schema.return_value = "s3://b/schema.json"
+ s3.get_data_folder.return_value = "s3://b/"
+
+ job = MagicMock()
+ job.id = uuid.uuid4()
+
+ with (
+ patch(f"{_ACTIVITIES}.close_old_connections"),
+ patch(f"{_ACTIVITIES}.ExternalDataSource") as MockSource,
+ patch.object(CDCExtractActivity, "_get_cdc_schemas", return_value=schemas),
+ patch.object(CDCExtractActivity, "_update_schema_sync_type_config"),
+ patch(f"{_ACTIVITIES}.get_cdc_adapter", return_value=adapter),
+ patch(f"{_ACTIVITIES}.S3BatchWriter", return_value=s3),
+ patch(f"{_ACTIVITIES}.PostgresProducer"),
+ patch(f"{_ACTIVITIES}.ExternalDataJob") as MockJob,
+ ):
+ MockSource.objects.get.return_value = source
+ MockJob.objects.create.return_value = job
+ yield adapter, reader, s3
+
+
+class TestExtractionMetricsSmoke:
+ def test_success_run_emits_events_advance_and_duration(self, metric_env):
+ env, buffer = metric_env
+ source = _make_source()
+ events = [_make_event(position="0/100"), _make_event(op="U", position="0/200")]
+ with _extract_patches(source, [_make_schema()], events):
+ env.run(cdc_extract_activity, CDCExtractInput(team_id=1, source_id=source.id))
+
+ names = _emitted_names(buffer)
+ assert "cdc_events_extracted_total" in names
+ assert "cdc_slot_advance_total" in names
+ assert "cdc_extraction_duration_seconds" in names
+
+ def test_no_changes_run_emits_duration(self, metric_env):
+ env, buffer = metric_env
+ source = _make_source()
+ with _extract_patches(source, [_make_schema()], []):
+ env.run(cdc_extract_activity, CDCExtractInput(team_id=1, source_id=source.id))
+
+ assert "cdc_extraction_duration_seconds" in _emitted_names(buffer)
+
+ def test_failure_run_emits_duration_and_reraises(self, metric_env):
+ env, buffer = metric_env
+ source = _make_source()
+ with _extract_patches(source, [_make_schema()], []) as (_, reader, _s3):
+ reader.read_changes.side_effect = RuntimeError("boom")
+ with pytest.raises(RuntimeError, match="boom"):
+ env.run(cdc_extract_activity, CDCExtractInput(team_id=1, source_id=source.id))
+
+ assert "cdc_extraction_duration_seconds" in _emitted_names(buffer)
+
+ def test_slot_advance_failure_emits_failure_metric(self, metric_env):
+ env, buffer = metric_env
+ source = _make_source()
+ events = [_make_event(position="0/100")]
+ with _extract_patches(source, [_make_schema()], events) as (_, reader, _s3):
+ reader.confirm_position.side_effect = RuntimeError("advance failed")
+ with pytest.raises(RuntimeError, match="advance failed"):
+ env.run(cdc_extract_activity, CDCExtractInput(team_id=1, source_id=source.id))
+
+ assert "cdc_slot_advance_failures_total" in _emitted_names(buffer)
+
+ def test_micro_flush_emits_micro_batch_metric(self, metric_env):
+ env, buffer = metric_env
+ source = _make_source()
+ events = [_make_event(position="0/100"), _make_event(op="U", position="0/200")]
+ # Force a mid-run flush so the read loop's micro-batch path runs.
+ with _extract_patches(source, [_make_schema()], events):
+ with patch.object(ChangeEventBatcher, "should_flush", property(lambda self: self.event_count > 0)):
+ env.run(cdc_extract_activity, CDCExtractInput(team_id=1, source_id=source.id))
+
+ assert "cdc_micro_batches_flushed_total" in _emitted_names(buffer)
+
+
+def _sweeper_adapter(*, lag_bytes=0, retention_cap_mb=None):
+ adapter = MagicMock()
+ adapter.parse_cdc_config.side_effect = lambda source: PostgresCDCConfig.from_source(source)
+
+ @contextmanager
+ def _conn(source, connect_timeout=15):
+ yield MagicMock()
+
+ adapter.management_connection.side_effect = _conn
+ adapter.get_lag_bytes.return_value = lag_bytes
+ adapter.get_retention_cap_mb.return_value = retention_cap_mb
+ return adapter
+
+
+def _create_cdc_source(team, *, auto_drop_slot=True):
+ return ExternalDataSource.objects.create(
+ team_id=team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ job_inputs={
+ "cdc_enabled": True,
+ "cdc_management_mode": "posthog",
+ "cdc_auto_drop_slot": auto_drop_slot,
+ "cdc_slot_name": "posthog_slot",
+ "cdc_publication_name": "posthog_pub",
+ },
+ )
+
+
+@contextmanager
+def _sweeper_patches(adapter):
+ with (
+ patch(f"{_ACTIVITIES}.HeartbeaterSync"),
+ patch(f"{_ACTIVITIES}.close_old_connections"),
+ patch(f"{_ACTIVITIES}.get_cdc_adapter", return_value=adapter),
+ patch("products.data_warehouse.backend.data_load.service.delete_cdc_extraction_schedule"),
+ ):
+ yield
+
+
+class TestSweeperMetricsSmoke:
+ def test_sweep_emits_lag_and_sweep_metrics(self, metric_env, team):
+ env, buffer = metric_env
+ _create_cdc_source(team)
+ with _sweeper_patches(_sweeper_adapter(lag_bytes=10 * 1024 * 1024)):
+ env.run(cleanup_orphan_slots_activity)
+
+ names = _emitted_names(buffer)
+ assert "cdc_wal_lag_bytes" in names
+ assert "cdc_sweeper_sources_checked_total" in names
+ assert "cdc_sweeper_duration_seconds" in names
+
+ def test_auto_drop_emits_metric(self, metric_env, team):
+ env, buffer = metric_env
+ _create_cdc_source(team, auto_drop_slot=True)
+ with _sweeper_patches(_sweeper_adapter(lag_bytes=5000 * 1024 * 1024)):
+ env.run(cleanup_orphan_slots_activity)
+
+ assert "cdc_auto_drop_total" in _emitted_names(buffer)