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(warehouse-sources): stop cdc after 14 days over the billing limit (#106952)

Daniel RC76d1c311b69a
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.md
index f25f53e560a5..f010926c39b3 100644
--- a/docs/internal/cdc-buffered-ingress-runbook.md
+++ b/docs/internal/cdc-buffered-ingress-runbook.md
@@ -368,6 +368,20 @@ and does not count.
Watch the age of the oldest unconsumed file per schema, not the file count. A schema with few files
that are all thirteen days old is in trouble; one with thousands of fresh files is fine.
+**The billing limit is the usual cause, and the sweeper stops it.** Capture has no billing check, so it
+keeps reading the slot and writing the buffer while the limit blocks every consume run. Once a table
+has been blocked by the billing limit for longer than the buffer keeps files, and the team is still
+over the limit, the slot sweeper (`cleanup_orphan_slots_activity`) marks the source broken with reason
+`billing_limit_expired`. A PostHog-managed slot with auto-drop on is dropped and the schedules are
+paused, on the same terms as the critical-lag safety net. If that drop is refused — an active slot,
+a missing grant — the source is left running and the next sweep retries it, because pausing capture
+behind a live slot is what makes WAL grow. Any other slot is left to its owner and capture keeps
+advancing it, so the customer's WAL does not grow. Once the team is back under the limit, a dropped
+slot needs Repair CDC, which recreates it and re-snapshots every table. A kept slot needs nothing: the
+sweeper lifts its marker, and each table's next sync finds its buffer expired and re-snapshots on its
+own. Only a table's own sync runs count toward the 14 days. Capture records a Failed job on every table
+when it fails, and those rows do not restart the count.
+
## Retried capture attempts
Temporal retries a capture attempt that dies, and the retry re-reads the WAL from the slot's
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index 9166b153a98d..1475903baa41 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -58,6 +58,11 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
enrich_delete_rows,
enrich_toast_omitted_rows,
)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.billing_expiry import (
+ blocked_past_buffer_retention,
+ clear_kept_slot_billing_expiry,
+ stop_cdc_past_billing_retention,
+)
from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import (
SELF_MANAGED_LAG_REASON,
clear_recovered_self_managed_lag,
@@ -2298,7 +2303,31 @@ def cleanup_orphan_slots_activity() -> None:
purge_buffer_prefix(source.team_id, str(schema_id), source_log)
continue
- # 2. Active sources — check WAL lag
+ # 2. Active sources over the billing limit for longer than the buffer keeps changes
+ try:
+ cleared = clear_kept_slot_billing_expiry(source)
+ if cleared:
+ source_log.info("cdc_billing_expiry_cleared_under_limit", schemas=cleared)
+ past_billing_retention = blocked_past_buffer_retention(source, sweep_started)
+ except Exception:
+ # The lag check below still runs for this source, and the next sweep retries this one.
+ source_log.exception("failed_to_check_billing_retention")
+ metrics.get_sweeper_source_errors_metric().add(1)
+ sources_errored += 1
+ past_billing_retention = False
+ if past_billing_retention:
+ source_log.warning("cdc_stopping_past_billing_retention")
+ try:
+ if stop_cdc_past_billing_retention(source, cdc_config, adapter):
+ slots_dropped += 1
+ continue
+ except Exception:
+ # The source keeps running, so the lag check below still covers it until a later sweep stops it.
+ source_log.exception("failed_to_stop_cdc_past_billing_retention")
+ metrics.get_sweeper_source_errors_metric().add(1)
+ sources_errored += 1
+
+ # 3. Active sources — check WAL lag
source_started = dt.datetime.now(tz=dt.UTC)
try:
with adapter.management_connection(source, connect_timeout=10) as conn:
@@ -2334,6 +2363,13 @@ def cleanup_orphan_slots_activity() -> None:
try:
with adapter.management_connection(source, connect_timeout=10) as conn:
adapter.drop_resources(conn, cdc_config.slot_name, cdc_config.publication_name)
+ # drop_resources is best-effort, so it logs a refused drop (an active slot, a missing
+ # grant) instead of raising. Pausing capture then would leave nothing to advance the
+ # slot, so the source keeps running and the next sweep retries the drop.
+ if adapter.slot_exists(conn, cdc_config.slot_name):
+ raise RuntimeError(
+ f"Replication slot {cdc_config.slot_name} still exists after the drop"
+ )
slots_dropped += 1
metrics.get_auto_drop_metric(source.team_id, str(source.id)).add(1)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
index 92fb3f027658..0e7a895cc24d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py
@@ -63,6 +63,11 @@ class CDCSourceAdapter(Protocol[CDCConfigT_co]):
def drop_resources(self, conn: Any, slot_name: str, pub_name: str) -> None: ...
+ def slot_exists(self, conn: Any, slot_name: str) -> bool:
+ """Whether the change-stream resource still exists on the source database. Callers use it to
+ confirm a best-effort drop actually removed it before acting as if it were gone."""
+ ...
+
def get_lag_bytes(self, conn: Any, slot_name: str) -> int | None: ...
def get_retention_cap_mb(self, conn: Any) -> int | None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/billing_expiry.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/billing_expiry.py
new file mode 100644
index 000000000000..6cc8d19d8a2c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/billing_expiry.py
@@ -0,0 +1,159 @@
+"""Stop CDC on a source whose team stays over the billing limit for longer than the buffer keeps changes.
+
+Capture has no billing check: it keeps reading the slot and writing the buffer while the limit blocks
+every load. Once a blocked table's oldest unread change is older than the buffer retention, the
+lifecycle rule starts deleting changes the table never loaded, so only a re-snapshot can make it
+correct again. From then on the slot costs the customer WAL and the buffer costs storage for data
+that will never load. The source moves to the broken state, and Repair CDC re-snapshots every table
+once the team is back under the limit.
+"""
+
+from __future__ import annotations
+
+import uuid
+import typing
+import datetime as dt
+
+from posthog.models.team.team import Team
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import clear_broken_markers, mark_cdc_broken
+from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import BUFFER_FILE_RETENTION
+from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import CDC_EXTRACTION_WORKFLOW_ID_PREFIX
+
+from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited
+
+if typing.TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters import CDCSourceAdapter
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.types import CDCConfig
+
+BILLING_LIMIT_EXPIRED_REASON = "billing_limit_expired"
+
+_SLOT_DROPPED_MESSAGE = (
+ "Change data capture stopped because this team has been over its data warehouse billing limit for "
+ "14 days, and PostHog keeps captured changes for 14 days. PostHog dropped the replication slot. "
+ "Once you're back under the limit, use Repair CDC to recreate it and re-sync your tables."
+)
+_SLOT_KEPT_MESSAGE = (
+ "Change data capture stopped loading because this team has been over its data warehouse billing "
+ "limit for 14 days, and PostHog keeps captured changes for 14 days. The replication slot was not "
+ "dropped. Once you're back under the limit, your tables re-sync on their own."
+)
+
+
+# Finished job outcomes other than a billing block. A running job has no outcome yet, so it neither
+# starts nor ends a billing-blocked run.
+_OTHER_OUTCOMES = (
+ ExternalDataJob.Status.COMPLETED,
+ ExternalDataJob.Status.FAILED,
+ ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW,
+)
+
+
+def blocked_past_buffer_retention(source: ExternalDataSource, now: dt.datetime) -> bool:
+ """Whether this source's CDC tables have been blocked by the billing limit longer than the buffer keeps changes.
+
+ The team must still be over the limit: once the limit lifts, the tables' next runs load what the
+ buffer still holds.
+ """
+ cdc_schemas = ExternalDataSchema.objects.filter(
+ team_id=source.team_id,
+ source=source,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ ).exclude(deleted=True)
+ # A source already marked broken is stopped, and its own recovery path owns the slot.
+ if cdc_schemas.filter(sync_type_config__has_key="cdc_broken").exists():
+ return False
+ cutoff = now - BUFFER_FILE_RETENTION
+ blocked = cdc_schemas.filter(status=ExternalDataSchema.Status.BILLING_LIMIT_REACHED)
+ # A table blocked that long has not loaded since the cutoff either, so this rules out most tables
+ # before any job history is read.
+ candidates = [schema for schema in blocked if (schema.last_synced_at or schema.created_at) < cutoff]
+ if not any(_blocked_past(source, schema.id, cutoff) for schema in candidates):
+ return False
+ return _team_over_limit(source)
+
+
+def _team_over_limit(source: ExternalDataSource) -> bool:
+ team = Team.objects.only("api_token").get(id=source.team_id)
+ return is_team_limited(team.api_token, QuotaResource.ROWS_SYNCED, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)
+
+
+def _blocked_past(source: ExternalDataSource, schema_id: uuid.UUID, cutoff: dt.datetime) -> bool:
+ """Whether this table's current run of billing-blocked jobs started before ``cutoff``."""
+ blocked_since = _billing_blocked_since(source, schema_id)
+ return blocked_since is not None and blocked_since < cutoff
+
+
+def _billing_blocked_since(source: ExternalDataSource, schema_id: uuid.UUID) -> dt.datetime | None:
+ """When this table's current run of billing-blocked jobs began.
+
+ That run starts at the table's first blocked job after its last job with another outcome. Only
+ this table's own jobs count — a sibling table can fail, and a non-billable run skips the billing
+ check and completes, while this table stays blocked. A table can also go longer without a load for
+ other reasons, which is why this is not the time since its last load.
+
+ Capture's rows are left out too. Capture has no billing check, and a failed capture run records a
+ Failed job on every CDC table, so a source whose capture fails now and then would never be stopped.
+ """
+ jobs = ExternalDataJob.objects.filter(team_id=source.team_id, pipeline_id=source.id, schema_id=schema_id).exclude(
+ workflow_id__startswith=CDC_EXTRACTION_WORKFLOW_ID_PREFIX
+ )
+ # One ordered lookup per status, because the (team, pipeline, status, created_at) index serves an
+ # equality on status and not an exclusion.
+ latest_by_outcome = [
+ jobs.filter(status=outcome).order_by("-created_at").values_list("created_at", flat=True).first()
+ for outcome in _OTHER_OUTCOMES
+ ]
+ last_other = max((created_at for created_at in latest_by_outcome if created_at is not None), default=None)
+ blocked = jobs.filter(status=ExternalDataJob.Status.BILLING_LIMIT_REACHED)
+ if last_other is not None:
+ blocked = blocked.filter(created_at__gt=last_other)
+ return blocked.order_by("created_at").values_list("created_at", flat=True).first()
+
+
+def stop_cdc_past_billing_retention(
+ source: ExternalDataSource, cdc_config: CDCConfig, adapter: CDCSourceAdapter[CDCConfig]
+) -> bool:
+ """Move the source to the broken state, and drop its slot where PostHog may. Returns whether it dropped the slot.
+
+ The slot is dropped on the terms of the lag safety net: only a PostHog-managed slot whose owner
+ left auto-drop on. Any other slot is left to its owner, and capture keeps advancing it so the
+ customer's WAL does not grow, which is why that case does not pause the schedules.
+
+ Raises when the slot survives the drop, which leaves the source running for the next sweep to
+ retry: pausing capture is only safe once nothing has to advance the slot any more.
+ """
+ if cdc_config.management_mode == "posthog" and cdc_config.auto_drop_slot:
+ with adapter.management_connection(source, connect_timeout=10) as conn:
+ adapter.drop_resources(conn, cdc_config.slot_name, cdc_config.publication_name)
+ # drop_resources is best-effort: it logs a refused drop (an active slot, a missing grant)
+ # instead of raising.
+ if adapter.slot_exists(conn, cdc_config.slot_name):
+ raise RuntimeError(f"Replication slot {cdc_config.slot_name} still exists after the drop")
+ mark_cdc_broken(source, BILLING_LIMIT_EXPIRED_REASON, _SLOT_DROPPED_MESSAGE)
+ return True
+ mark_cdc_broken(source, BILLING_LIMIT_EXPIRED_REASON, _SLOT_KEPT_MESSAGE, pause=False, slot_kept=True)
+ return False
+
+
+def clear_kept_slot_billing_expiry(source: ExternalDataSource) -> int:
+ """Lift a kept slot's ``billing_limit_expired`` marker once the team is back under the limit.
+
+ Nothing was dropped or paused, so each table's next sync finds its buffer expired and re-snapshots
+ on its own. Left in place, the marker keeps every table showing Failed while it loads, and points
+ the user at a Repair CDC that would re-snapshot every table a second time. Returns how many schemas
+ were cleared.
+ """
+ marked = ExternalDataSchema.objects.filter(
+ team_id=source.team_id,
+ source=source,
+ sync_type_config__cdc_broken__reason=BILLING_LIMIT_EXPIRED_REASON,
+ sync_type_config__cdc_broken__slot_kept=True,
+ )
+ if not marked.exists() or _team_over_limit(source):
+ return 0
+ return clear_broken_markers(source, reason=BILLING_LIMIT_EXPIRED_REASON, slot_kept=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
index 04738c5c2496..f9ed0d098f89 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
@@ -64,7 +64,7 @@ def mark_cdc_broken(
log = logger.bind(source_id=str(source.id), team_id=source.team_id, reason=reason)
broken_marker = {"reason": reason, "at": dt.datetime.now(tz=dt.UTC).isoformat(), **extra}
- # The source row lock serializes this with clear_recovered_self_managed_lag, which must not
+ # The source row lock serializes this with clear_broken_markers, which must not
# see the source status and the markers half-written.
with transaction.atomic():
ExternalDataSource.objects.select_for_update(of=("self",)).get(id=source.id, team_id=source.team_id)
@@ -123,23 +123,30 @@ def clear_recovered_self_managed_lag(source: ExternalDataSource) -> int:
Left in place it keeps absorbing every status update and makes resume refuse the source,
long after the customer has recovered. Returns how many schemas were cleared.
"""
+ return clear_broken_markers(source, reason=SELF_MANAGED_LAG_REASON)
+
+
+def clear_broken_markers(source: ExternalDataSource, **marker_fields: typing.Any) -> int:
+ """Remove each ``cdc_broken`` marker whose fields match ``marker_fields``, and set the source back to
+ Running once no schema is still marked. Returns how many schemas were cleared.
+ """
+ lookup = {f"sync_type_config__cdc_broken__{key}": value for key, value in marker_fields.items()}
def _clear(config: dict[str, typing.Any]) -> None:
- if (config.get("cdc_broken") or {}).get("reason") == SELF_MANAGED_LAG_REASON:
+ marker = config.get("cdc_broken") or {}
+ if marker and all(marker.get(key) == value for key, value in marker_fields.items()):
config.pop("cdc_broken")
- marked = ExternalDataSchema.objects.filter(
- team_id=source.team_id, source=source, sync_type_config__cdc_broken__reason=SELF_MANAGED_LAG_REASON
- )
+ marked = ExternalDataSchema.objects.filter(team_id=source.team_id, source=source, **lookup)
if not marked.exists():
return 0
# Source lock first, the order mark_cdc_broken takes, so a concurrent re-mark cannot interleave.
with transaction.atomic():
locked = ExternalDataSource.objects.select_for_update(of=("self",)).get(id=source.id, team_id=source.team_id)
schema_ids = list(
- ExternalDataSchema.objects.filter(
- team_id=source.team_id, source=source, sync_type_config__cdc_broken__reason=SELF_MANAGED_LAG_REASON
- ).values_list("id", flat=True)
+ ExternalDataSchema.objects.filter(team_id=source.team_id, source=source, **lookup).values_list(
+ "id", flat=True
+ )
)
for schema_id in schema_ids:
update_sync_type_config_keys(schema_id, source.team_id, mutate=_clear)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
index d371f6ef6f64..92002bc71830 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
@@ -1,9 +1,11 @@
import uuid
+import datetime as dt
from contextlib import contextmanager
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.cdc.activities import cleanup_orphan_slots_activity
@@ -11,6 +13,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.c
pytestmark = pytest.mark.django_db
+_ACTIVITIES = "products.warehouse_sources.backend.temporal.data_imports.cdc.activities"
+_BILLING_EXPIRY = "products.warehouse_sources.backend.temporal.data_imports.cdc.billing_expiry"
+
def _create_source(team, *, deleted=False, job_inputs=None):
return ExternalDataSource.objects.create(
@@ -45,7 +50,7 @@ def _cdc_job_inputs(*, enabled=True, management="posthog", auto_drop_slot=True,
}
-def _mock_adapter(*, lag_bytes=0, retention_cap_mb=None):
+def _mock_adapter(*, lag_bytes=0, retention_cap_mb=None, slot_survives_drop=False):
"""Adapter mock that decodes config for real (proving the encrypted-job_inputs path)
but stubs every database connection."""
adapter = MagicMock()
@@ -58,6 +63,7 @@ def _mock_adapter(*, lag_bytes=0, retention_cap_mb=None):
adapter.management_connection.side_effect = _conn
adapter.get_lag_bytes.return_value = lag_bytes
adapter.get_retention_cap_mb.return_value = retention_cap_mb
+ adapter.slot_exists.return_value = slot_survives_drop
return adapter
@@ -73,6 +79,7 @@ def _run(adapter):
patch("products.data_warehouse.backend.logic.data_load.service.delete_cdc_extraction_schedule") as mock_delete,
# mark_cdc_broken (critical-lag paths) reaches Temporal / Kafka / analytics — stub the boundaries.
patch("products.data_warehouse.backend.logic.data_load.service.pause_cdc_extraction_schedule") as mock_pause,
+ patch("products.data_warehouse.backend.logic.data_load.service.pause_external_data_schedule"),
patch("products.notifications.backend.facade.api.create_notification"),
patch("posthoganalytics.capture"),
):
@@ -147,20 +154,26 @@ def test_deleted_source_purges_shadow_buffer_prefixes(team):
assert [call.args[1] for call in mock_purge.call_args_list] == [str(schema.id)]
-def test_critical_lag_posthog_auto_drop_marks_broken_and_pauses(team):
[email protected]("slot_survives_drop, stopped", [(False, True), (True, False)])
+def test_critical_lag_posthog_auto_drop_stops_capture_once_the_slot_is_gone(team, slot_survives_drop, stopped):
source = _create_source(team, job_inputs=_cdc_job_inputs(auto_drop_slot=True))
schema = _create_cdc_schema(team, source)
- adapter = _mock_adapter(lag_bytes=5000 * 1024 * 1024) # 5000 MB > 2048 MB critical default
+ adapter = _mock_adapter(
+ lag_bytes=5000 * 1024 * 1024, # 5000 MB > 2048 MB critical default
+ slot_survives_drop=slot_survives_drop,
+ )
_, _, mock_pause = _run(adapter)
adapter.drop_resources.assert_called_once()
source.refresh_from_db()
- assert source.status == ExternalDataSource.Status.ERROR
+ assert (source.status == ExternalDataSource.Status.ERROR) is stopped
schema.refresh_from_db()
- assert schema.status == ExternalDataSchema.Status.FAILED
- assert schema.sync_type_config["cdc_broken"]["reason"] == "auto_dropped_critical_lag"
- mock_pause.assert_called_once_with(str(source.id))
+ assert (schema.status == ExternalDataSchema.Status.FAILED) is stopped
+ assert schema.sync_type_config.get("cdc_broken", {}).get("reason") == (
+ "auto_dropped_critical_lag" if stopped else None
+ )
+ assert mock_pause.call_args_list == ([call(str(source.id))] if stopped else [])
@pytest.mark.parametrize(
@@ -212,3 +225,157 @@ def test_critical_lag_self_managed_marks_broken_without_drop_or_pause(team):
assert source.status == ExternalDataSource.Status.ERROR
schema.refresh_from_db()
assert schema.sync_type_config["cdc_broken"]["reason"] == "critical_lag_self_managed"
+
+
+def _job(team, source, schema, status, age, workflow_id=None):
+ job = ExternalDataJob.objects.create(
+ team_id=team.pk, pipeline=source, schema=schema, status=status, rows_synced=0, workflow_id=workflow_id
+ )
+ ExternalDataJob.objects.filter(id=job.id).update(created_at=dt.datetime.now(tz=dt.UTC) - age)
+
+
+def _billing_blocked_schema(team, source, *, blocked_for, last_load_ago=None, other_outcome_ago=None, name="users"):
+ schema = _create_cdc_schema(team, source, name=name)
+ ExternalDataSchema.objects.filter(id=schema.id).update(
+ status=ExternalDataSchema.Status.BILLING_LIMIT_REACHED,
+ last_synced_at=dt.datetime.now(tz=dt.UTC) - (last_load_ago or blocked_for),
+ )
+ if other_outcome_ago is not None:
+ _job(team, source, schema, ExternalDataJob.Status.FAILED, other_outcome_ago)
+ _job(team, source, schema, ExternalDataJob.Status.BILLING_LIMIT_REACHED, blocked_for)
+ return schema
+
+
+ "job_inputs, dropped, paused",
+ [
+ (_cdc_job_inputs(), True, True),
+ (_cdc_job_inputs(auto_drop_slot=False), False, False),
+ (_cdc_job_inputs(management="self_managed"), False, False),
+ ],
+)
+def test_a_source_blocked_by_billing_past_buffer_retention_is_marked_broken(team, job_inputs, dropped, paused):
+ source = _create_source(team, job_inputs=job_inputs)
+ schema = _billing_blocked_schema(team, source, blocked_for=dt.timedelta(days=15))
+ adapter = _mock_adapter()
+
+ with patch(f"{_BILLING_EXPIRY}.is_team_limited", return_value=True):
+ _, _, mock_pause = _run(adapter)
+
+ assert adapter.drop_resources.called is dropped
+ assert mock_pause.called is paused
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_broken"]["reason"] == "billing_limit_expired"
+ adapter.get_lag_bytes.assert_not_called()
+
+
+ "blocked_for, other_outcome_ago, team_limited, already_broken",
+ [
+ (dt.timedelta(days=3), None, True, False),
+ (dt.timedelta(days=15), None, False, False),
+ (dt.timedelta(days=15), None, True, True),
+ (dt.timedelta(days=1), dt.timedelta(days=2), True, False),
+ ],
+)
+def test_a_source_is_left_running_unless_billing_blocks_it_past_buffer_retention(
+ team, blocked_for, other_outcome_ago, team_limited, already_broken
+):
+ source = _create_source(team, job_inputs=_cdc_job_inputs())
+ schema = _billing_blocked_schema(
+ team, source, blocked_for=blocked_for, last_load_ago=dt.timedelta(days=15), other_outcome_ago=other_outcome_ago
+ )
+ if already_broken:
+ ExternalDataSchema.objects.filter(id=schema.id).update(
+ sync_type_config={**schema.sync_type_config, "cdc_broken": {"reason": "auto_dropped_critical_lag"}}
+ )
+ adapter = _mock_adapter()
+
+ with patch(f"{_BILLING_EXPIRY}.is_team_limited", return_value=team_limited):
+ _run(adapter)
+
+ adapter.drop_resources.assert_not_called()
+ schema.refresh_from_db()
+ assert (schema.sync_type_config.get("cdc_broken") or {}).get("reason") != "billing_limit_expired"
+
+
+def test_a_slot_that_survives_the_drop_keeps_billing_capture_running(team):
+ # drop_resources only logs a refused drop, so pausing capture on the strength of the call alone
+ # would leave a live slot with nothing advancing it and the customer's WAL growing.
+ source = _create_source(team, job_inputs=_cdc_job_inputs())
+ schema = _billing_blocked_schema(team, source, blocked_for=dt.timedelta(days=15))
+ adapter = _mock_adapter(slot_survives_drop=True, lag_bytes=5000 * 1024 * 1024)
+
+ with patch(f"{_BILLING_EXPIRY}.is_team_limited", return_value=True):
+ _, _, mock_pause = _run(adapter)
+
+ adapter.drop_resources.assert_called()
+ mock_pause.assert_not_called()
+ adapter.get_lag_bytes.assert_called_once()
+ source.refresh_from_db()
+ assert source.status != ExternalDataSource.Status.ERROR
+ schema.refresh_from_db()
+ assert "cdc_broken" not in schema.sync_type_config
+
+
[email protected]("other_job", ["sibling_table_completed", "capture_failed"])
+def test_a_job_that_is_not_the_tables_own_sync_does_not_defer_the_billing_stop(team, other_job):
+ source = _create_source(team, job_inputs=_cdc_job_inputs())
+ schema = _billing_blocked_schema(team, source, blocked_for=dt.timedelta(days=15))
+ if other_job == "sibling_table_completed":
+ sibling = _billing_blocked_schema(team, source, blocked_for=dt.timedelta(hours=1), name="events")
+ _job(team, source, sibling, ExternalDataJob.Status.COMPLETED, dt.timedelta(hours=1))
+ else:
+ _job(
+ team,
+ source,
+ schema,
+ ExternalDataJob.Status.FAILED,
+ dt.timedelta(days=1),
+ workflow_id=f"cdc-extraction-{source.id}",
+ )
+ adapter = _mock_adapter()
+
+ with patch(f"{_BILLING_EXPIRY}.is_team_limited", return_value=True):
+ _run(adapter)
+
+ adapter.drop_resources.assert_called_once()
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_broken"]["reason"] == "billing_limit_expired"
+
+
+ "job_inputs, limited_after, cleared",
+ [
+ (_cdc_job_inputs(auto_drop_slot=False), False, True),
+ (_cdc_job_inputs(management="self_managed"), False, True),
+ (_cdc_job_inputs(auto_drop_slot=False), True, False),
+ (_cdc_job_inputs(), False, False),
+ ],
+)
+def test_a_kept_slot_is_no_longer_broken_once_the_team_is_under_the_limit(team, job_inputs, limited_after, cleared):
+ source = _create_source(team, job_inputs=job_inputs)
+ schema = _billing_blocked_schema(team, source, blocked_for=dt.timedelta(days=15))
+
+ with patch(f"{_BILLING_EXPIRY}.is_team_limited", return_value=True):
+ _run(_mock_adapter())
+ with patch(f"{_BILLING_EXPIRY}.is_team_limited", return_value=limited_after):
+ _run(_mock_adapter())
+
+ schema.refresh_from_db()
+ source.refresh_from_db()
+ assert ("cdc_broken" not in schema.sync_type_config) is cleared
+ assert (source.status == ExternalDataSource.Status.RUNNING) is cleared
+
+
+def test_a_failed_billing_check_still_checks_the_slots_lag(team):
+ source = _create_source(team, job_inputs=_cdc_job_inputs())
+ schema = _create_cdc_schema(team, source)
+ adapter = _mock_adapter(lag_bytes=5000 * 1024 * 1024)
+
+ with patch(f"{_ACTIVITIES}.blocked_past_buffer_retention", side_effect=RuntimeError("quota cache down")):
+ _run(adapter)
+
+ adapter.drop_resources.assert_called_once()
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_broken"]["reason"] == "auto_dropped_critical_lag"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
index 972143879e14..ac818e54985b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -2833,9 +2833,14 @@ class TestCleanupOrphanSlotsRetentionCap:
mock_adapter.parse_cdc_config.return_value = cdc_config
mock_adapter.get_lag_bytes.return_value = lag_mb * 1024 * 1024
mock_adapter.get_retention_cap_mb.return_value = cap_mb
+ mock_adapter.slot_exists.return_value = False
mock_get_adapter.return_value = mock_adapter
return source, mock_adapter
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.blocked_past_buffer_retention",
+ return_value=False,
+ )
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.HeartbeaterSync")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
@@ -2843,7 +2848,14 @@ class TestCleanupOrphanSlotsRetentionCap:
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_cdc_broken")
def test_retention_cap_lowers_critical_threshold(
- self, mock_mark_broken, mock_close_conns, MockSourceModel, mock_get_adapter, mock_activity, mock_heartbeater
+ self,
+ mock_mark_broken,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_adapter,
+ mock_activity,
+ mock_heartbeater,
+ _billing,
):
# Configured critical is 10240 MB, but the engine caps retention at 1000 MB:
# at 900 MB of lag (>= 80% of the cap) the sweeper must already act.
@@ -2855,6 +2867,10 @@ class TestCleanupOrphanSlotsRetentionCap:
mock_adapter.drop_resources.assert_called_once()
mock_mark_broken.assert_called_once()
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.blocked_past_buffer_retention",
+ return_value=False,
+ )
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.HeartbeaterSync")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
@@ -2862,7 +2878,14 @@ class TestCleanupOrphanSlotsRetentionCap:
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_cdc_broken")
def test_unlimited_retention_keeps_configured_threshold(
- self, mock_mark_broken, mock_close_conns, MockSourceModel, mock_get_adapter, mock_activity, mock_heartbeater
+ self,
+ mock_mark_broken,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_adapter,
+ mock_activity,
+ mock_heartbeater,
+ _billing,
):
source, mock_adapter = self._setup(mock_get_adapter, MockSourceModel, lag_mb=900, cap_mb=None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
index ee8decad8a79..4fc7fdfeef35 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
@@ -218,6 +218,7 @@ def _sweeper_adapter(*, lag_bytes=0, retention_cap_mb=None):
adapter.management_connection.side_effect = _conn
adapter.get_lag_bytes.return_value = lag_bytes
adapter.get_retention_cap_mb.return_value = retention_cap_mb
+ adapter.slot_exists.return_value = False
return adapter
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
index 3baef0e07467..7f7ed0bd5607 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
@@ -171,6 +171,9 @@ class PostgresCDCAdapter:
def drop_resources(self, conn: Any, slot_name: str, pub_name: str) -> None:
drop_slot_and_publication(conn, slot_name, pub_name)
+ def slot_exists(self, conn: Any, slot_name: str) -> bool:
+ return slot_exists(conn, slot_name)
+
def get_lag_bytes(self, conn: Any, slot_name: str) -> int | None:
return get_slot_lag_bytes(conn, slot_name)