: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(data-warehouse): bulk-upsert cdc + sync schedules over one connection (#61215)
Marcus Hof0a21b88d621a
diff --git a/products/data_warehouse/backend/data_load/service.py b/products/data_warehouse/backend/data_load/service.pyindex 9da189a6d489..abd9b75c37f5 100644--- a/products/data_warehouse/backend/data_load/service.py+++ b/products/data_warehouse/backend/data_load/service.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport randomimport asyncio+from collections.abc import Iterablefrom dataclasses import asdictfrom datetime import UTC, datetime, time, timedeltafrom typing import TYPE_CHECKING@@ -326,6 +327,44 @@ async def bulk_delete_external_data_schedules(schedule_ids: list[str]) -> list[t]+@async_to_sync+async def bulk_update_external_data_job_schedules(+ schemas: list[ExternalDataSchema],+) -> tuple[list[str], list[tuple[str, BaseException]]]:+ """Update (re-issue) sync schedules for many schemas over a single shared connection.++ The update-only counterpart to `bulk_create_external_data_job_schedules`: it connects+ once and updates concurrently, but never triggers a run and never creates a missing+ schedule. Schemas whose schedule does not exist (never activated) are reported as+ skipped rather than failed — matching the per-schema `sync_external_data_job_workflow`+ `create=False` path. Returns ``(skipped_ids, failures)``.+ """+ if not schemas:+ return [], []++ temporal = await async_connect()+ semaphore = asyncio.Semaphore(_BULK_SCHEDULE_CONCURRENCY)+ _SKIPPED = "skipped"++ async def _update_one(external_data_schema: ExternalDataSchema) -> str | None:+ async with semaphore:+ schedule = get_sync_schedule(external_data_schema, should_sync=external_data_schema.should_sync)+ try:+ await a_update_schedule(temporal, id=str(external_data_schema.id), schedule=schedule)+ except temporalio.service.RPCError as e:+ # No schedule yet (schema never activated) — skip, don't create.+ if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:+ return _SKIPPED+ raise+ return None++ schema_ids = [str(schema.id) for schema in schemas]+ results = await asyncio.gather(*(_update_one(schema) for schema in schemas), return_exceptions=True)+ skipped = [sid for sid, result in zip(schema_ids, results) if result == _SKIPPED]+ failures = [(sid, result) for sid, result in zip(schema_ids, results) if isinstance(result, BaseException)]+ return skipped, failures++def cancel_external_data_workflow(workflow_id: str):temporal = sync_connect()cancel_workflow(temporal, workflow_id)@@ -367,6 +406,20 @@ def _get_cdc_extraction_schedule_id(source_id: str) -> str:return f"cdc-extraction-{source_id}"+CDC_DEFAULT_INTERVAL = timedelta(hours=1)+++def cdc_min_interval(sync_frequency_intervals: Iterable[timedelta | None]) -> timedelta:+ """CDC extraction interval for a source: the minimum sync frequency across its active CDC+ schemas, falling back to `CDC_DEFAULT_INTERVAL` when none declare one.++ Single source of truth shared by `sync_cdc_extraction_schedule` (per source) and the+ `backfill_cdc_extraction_schedules` command (batched), so the rule can't drift.+ """+ intervals = [interval for interval in sync_frequency_intervals if interval is not None]+ return min(intervals) if intervals else CDC_DEFAULT_INTERVAL++def get_cdc_extraction_schedule(source: ExternalDataSource,min_interval: timedelta,@@ -417,12 +470,17 @@ def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = Fals"""from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+ # `source__deleted=True` is excluded so a deleted source (whose schemas may have been+ # left non-deleted by `soft_delete`) collapses to the "no active CDC schemas" branch below+ # and deletes its schedule rather than re-creating it.cdc_schemas = list(ExternalDataSchema.objects.filter(source=source,sync_type=ExternalDataSchema.SyncType.CDC,should_sync=True,- ).exclude(deleted=True)+ )+ .exclude(deleted=True)+ .exclude(source__deleted=True))schedule_id = _get_cdc_extraction_schedule_id(str(source.id))@@ -434,8 +492,7 @@ def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = Falspassreturn- intervals = [s.sync_frequency_interval for s in cdc_schemas if s.sync_frequency_interval is not None]- min_interval = min(intervals) if intervals else timedelta(hours=1)+ min_interval = cdc_min_interval(schema.sync_frequency_interval for schema in cdc_schemas)temporal = sync_connect()schedule = get_cdc_extraction_schedule(source, min_interval)@@ -461,6 +518,44 @@ def delete_cdc_extraction_schedule(source_id: str) -> None:pass+@async_to_sync+async def bulk_sync_cdc_extraction_schedules(+ source_intervals: list[tuple[ExternalDataSource, timedelta]],+) -> list[tuple[str, BaseException]]:+ """Upsert CDC extraction schedules for many sources over a single shared connection.++ The bulk counterpart to `sync_cdc_extraction_schedule`: connects once and upserts+ concurrently. The caller must compute each ``(source, min_interval)`` pair synchronously+ (the per-source interval needs a DB query that can't run in this async context). Returns+ ``(source_id, exception)`` pairs for any that failed — a partial failure does not abort+ the rest.+ """+ if not source_intervals:+ return []++ temporal = await async_connect()+ semaphore = asyncio.Semaphore(_BULK_SCHEDULE_CONCURRENCY)++ async def _sync_one(source: ExternalDataSource, min_interval: timedelta) -> None:+ async with semaphore:+ schedule_id = _get_cdc_extraction_schedule_id(str(source.id))+ schedule = get_cdc_extraction_schedule(source, min_interval)+ try:+ await a_update_schedule(temporal, id=schedule_id, schedule=schedule)+ except temporalio.service.RPCError as e:+ if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:+ await a_create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=True)+ else:+ raise++ source_ids = [str(source.id) for source, _ in source_intervals]+ results = await asyncio.gather(+ *(_sync_one(source, interval) for source, interval in source_intervals),+ return_exceptions=True,+ )+ return [(source_id, result) for source_id, result in zip(source_ids, results) if isinstance(result, BaseException)]++# ---------------------------------------------------------------------------# Schema discovery scheduling (source-level)# ---------------------------------------------------------------------------diff --git a/products/data_warehouse/backend/data_load/test/test_service.py b/products/data_warehouse/backend/data_load/test/test_service.pyindex b228c42320ba..6b359e4fadbb 100644--- a/products/data_warehouse/backend/data_load/test/test_service.py+++ b/products/data_warehouse/backend/data_load/test/test_service.py@@ -4,6 +4,7 @@ import loggingimport datetime as dtimport pytest+from unittest.mock import AsyncMock, MagicMock, patchimport pytest_asynciofrom asgiref.sync import async_to_sync, sync_to_async@@ -11,15 +12,22 @@ from temporalio.client import (Client as TemporalClient,ScheduleActionStartWorkflow,)-from temporalio.service import RPCError+from temporalio.service import RPCError, RPCStatusCode+from posthog.api.test.test_organization import create_organization+from posthog.api.test.test_team import create_teamfrom posthog.models import Organization, Teamfrom posthog.temporal.common.client import sync_connectfrom products.data_warehouse.backend.data_load.service import (+ CDC_DEFAULT_INTERVAL,DISCOVER_SCHEMAS_INTERVAL,+ _get_cdc_extraction_schedule_id,_get_discover_schemas_schedule_id,_jitter_timedelta,+ bulk_sync_cdc_extraction_schedules,+ bulk_update_external_data_job_schedules,+ cdc_min_interval,get_discover_schemas_schedule,get_sync_schedule,)@@ -275,3 +283,176 @@ def test_jitter_timedelta():hours, minutes = _jitter_timedelta(max_jitter, random.Random())assert hours == 0assert 0 <= minutes <= 5+++# ---------------------------------------------------------------------------+# Bulk schedule helpers — Temporal client mocked so the update/create/skip/+# failure-isolation branches are covered directly (the command tests mock these+# helpers out, so this is the only place those branches are exercised).+# ---------------------------------------------------------------------------++SERVICE = "products.data_warehouse.backend.data_load.service"+++def _sync_team():+ return create_team(organization=create_organization("test org"))+++def _make_source(team, source_type="Postgres"):+ return ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ team=team,+ status="Completed",+ source_type=source_type,+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,+ job_inputs={},+ )+++def _make_schema(team, source, sync_type=ExternalDataSchema.SyncType.FULL_REFRESH, should_sync=True):+ return ExternalDataSchema.objects.create(+ name="TestSchema",+ team_id=team.pk,+ source_id=source.pk,+ sync_type=sync_type,+ sync_type_config={},+ should_sync=should_sync,+ sync_frequency_interval=dt.timedelta(hours=6),+ sync_time_of_day="00:00:00",+ )+++def _not_found() -> RPCError:+ return RPCError("schedule not found", RPCStatusCode.NOT_FOUND, b"")+++def _patch_temporal(update_side=None, create_side=None):+ """Patch the Temporal client + async schedule calls in the service module."""+ return (+ patch(f"{SERVICE}.async_connect", AsyncMock(return_value=MagicMock())),+ patch(f"{SERVICE}.a_update_schedule", AsyncMock(side_effect=update_side)),+ patch(f"{SERVICE}.a_create_schedule", AsyncMock(side_effect=create_side)),+ )+++ "intervals,expected",+ [+ ([], CDC_DEFAULT_INTERVAL),+ ([None, None], CDC_DEFAULT_INTERVAL),+ ([dt.timedelta(hours=6)], dt.timedelta(hours=6)),+ ([dt.timedelta(hours=6), dt.timedelta(hours=1)], dt.timedelta(hours=1)),+ ([dt.timedelta(hours=6), None, dt.timedelta(hours=2)], dt.timedelta(hours=2)),+ ],+)+def test_cdc_min_interval(intervals, expected):+ assert cdc_min_interval(intervals) == expected+++# --- bulk_sync_cdc_extraction_schedules (upsert: update, else create+trigger) ---+++def test_bulk_sync_cdc_existing_updates_only():+ source = _make_source(_sync_team())+ conn, upd, crt = _patch_temporal()+ with conn, upd as update_mock, crt as create_mock:+ failures = bulk_sync_cdc_extraction_schedules([(source, dt.timedelta(hours=1))])++ assert failures == []+ assert update_mock.call_count == 1+ assert create_mock.call_count == 0+++def test_bulk_sync_cdc_missing_creates_and_triggers():+ source = _make_source(_sync_team())+ conn, upd, crt = _patch_temporal(update_side=_not_found())+ with conn, upd, crt as create_mock:+ failures = bulk_sync_cdc_extraction_schedules([(source, dt.timedelta(hours=1))])++ assert failures == []+ assert create_mock.call_count == 1+ assert create_mock.call_args.kwargs.get("trigger_immediately") is True+++def test_bulk_sync_cdc_isolates_failures_and_aligns_ids():+ team = _sync_team()+ s1, s2, s3 = _make_source(team), _make_source(team), _make_source(team)+ bad_id = _get_cdc_extraction_schedule_id(str(s2.id))++ def update_side(temporal, id, schedule, **kwargs):+ if id == bad_id:+ raise Exception("boom")++ conn, upd, crt = _patch_temporal(update_side=update_side)+ with conn, upd as update_mock, crt:+ failures = bulk_sync_cdc_extraction_schedules(+ [(s1, dt.timedelta(hours=1)), (s2, dt.timedelta(hours=1)), (s3, dt.timedelta(hours=1))]+ )++ # one failure, attributed to the right source; the other two still ran+ assert [sid for sid, _ in failures] == [str(s2.id)]+ assert isinstance(failures[0][1], Exception)+ assert update_mock.call_count == 3+++def test_bulk_sync_cdc_reraises_non_not_found_rpc_errors():+ source = _make_source(_sync_team())+ other_rpc = RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b"")+ conn, upd, crt = _patch_temporal(update_side=other_rpc)+ with conn, upd, crt as create_mock:+ failures = bulk_sync_cdc_extraction_schedules([(source, dt.timedelta(hours=1))])++ # a non-NOT_FOUND error is a failure, not a silent create+ assert [sid for sid, _ in failures] == [str(source.id)]+ assert create_mock.call_count == 0+++# --- bulk_update_external_data_job_schedules (update-only; missing => skipped) ---+++def test_bulk_update_edj_existing_updates_only():+ team = _sync_team()+ schema = _make_schema(team, _make_source(team))+ conn, upd, crt = _patch_temporal()+ with conn, upd as update_mock, crt as create_mock:+ skipped, failures = bulk_update_external_data_job_schedules([schema])++ assert skipped == []+ assert failures == []+ assert update_mock.call_count == 1+ assert create_mock.call_count == 0 # update-only contract: never creates+++def test_bulk_update_edj_missing_is_skipped_not_created():+ team = _sync_team()+ schema = _make_schema(team, _make_source(team))+ conn, upd, crt = _patch_temporal(update_side=_not_found())+ with conn, upd, crt as create_mock:+ skipped, failures = bulk_update_external_data_job_schedules([schema])++ assert skipped == [str(schema.id)]+ assert failures == []+ assert create_mock.call_count == 0+++def test_bulk_update_edj_mixed_skip_fail_and_success():+ team = _sync_team()+ source = _make_source(team)+ ok, missing, broken = (_make_schema(team, source) for _ in range(3))++ def update_side(temporal, id, schedule, **kwargs):+ if id == str(missing.id):+ raise _not_found()+ if id == str(broken.id):+ raise Exception("boom")++ conn, upd, crt = _patch_temporal(update_side=update_side)+ with conn, upd as update_mock, crt as create_mock:+ skipped, failures = bulk_update_external_data_job_schedules([ok, missing, broken])++ assert skipped == [str(missing.id)]+ assert [sid for sid, _ in failures] == [str(broken.id)]+ assert create_mock.call_count == 0+ assert update_mock.call_count == 3diff --git a/products/data_warehouse/backend/management/commands/backfill_cdc_extraction_schedules.py b/products/data_warehouse/backend/management/commands/backfill_cdc_extraction_schedules.pynew file mode 100644index 000000000000..b475e2999fee--- /dev/null+++ b/products/data_warehouse/backend/management/commands/backfill_cdc_extraction_schedules.py@@ -0,0 +1,111 @@+"""Backfill / re-issue per-source CDC extraction Temporal schedules.++Re-creates each source's ``cdc-extraction-{source_id}`` schedule from the Postgres source+of truth, which re-encrypts its workflow input under the current key. Idempotent: the+update path re-issues existing schedules; a missing schedule is created.++Only sources that currently have at least one active CDC schema (``sync_type=CDC``,+``should_sync=True``, not deleted) are processed — the per-source interval is the minimum+sync frequency across those schemas, matching ``sync_cdc_extraction_schedule``. Sources+that have lost all active CDC schemas are left untouched (the live deletion path handles+those at write time).++Usage:+ # Dry-run (default) — counts sources, upserts nothing+ python manage.py backfill_cdc_extraction_schedules++ # Live run+ python manage.py backfill_cdc_extraction_schedules --live-run++ # Restrict to a specific source type+ python manage.py backfill_cdc_extraction_schedules --live-run --source-type Postgres++ # Restrict to a specific team+ python manage.py backfill_cdc_extraction_schedules --live-run --team-id 2+"""++from __future__ import annotations++from collections import defaultdict+from datetime import timedelta+from typing import Any++from django.core.management.base import BaseCommand++import structlog++from products.data_warehouse.backend.data_load.service import bulk_sync_cdc_extraction_schedules, cdc_min_interval+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++logger = structlog.get_logger(__name__)+++class Command(BaseCommand):+ help = "Backfill / re-issue per-source CDC extraction Temporal schedules."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument(+ "--live-run",+ action="store_true",+ help="Actually upsert schedules (default is dry-run).",+ )+ parser.add_argument(+ "--source-type",+ type=str,+ default=None,+ help="Restrict to a specific source type (e.g. Postgres, MySQL).",+ )+ parser.add_argument(+ "--team-id",+ type=int,+ default=None,+ help="Restrict to sources belonging to this team.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ live_run: bool = options["live_run"]+ source_type_filter: str | None = options["source_type"]+ team_id_filter: int | None = options["team_id"]++ # Excluding `source__deleted=True` guards against deleted sources whose schemas were+ # left non-deleted: `ExternalDataSource.soft_delete()` tears down the CDC schedule but+ # does not cascade to schemas, so a fleet-wide sweep keyed only on schema state could+ # otherwise resurrect the schedule for a deleted source. Mirrors `sync_cdc_extraction_schedule`.+ schema_qs = (+ ExternalDataSchema.objects.filter(+ sync_type=ExternalDataSchema.SyncType.CDC,+ should_sync=True,+ )+ .exclude(deleted=True)+ .exclude(source__deleted=True)+ .exclude(source__access_method=ExternalDataSource.AccessMethod.DIRECT)+ .select_related("source")+ )+ if source_type_filter is not None:+ schema_qs = schema_qs.filter(source__source_type=source_type_filter)+ if team_id_filter is not None:+ schema_qs = schema_qs.filter(team_id=team_id_filter)++ # One schedule per source; `cdc_min_interval` collapses each source's schema+ # intervals to the value `sync_cdc_extraction_schedule` would compute per source.+ sources: dict[Any, ExternalDataSource] = {}+ intervals: dict[Any, list[timedelta | None]] = defaultdict(list)+ for schema in schema_qs.iterator(chunk_size=500):+ sources[schema.source_id] = schema.source+ intervals[schema.source_id].append(schema.sync_frequency_interval)++ source_intervals = [(source, cdc_min_interval(intervals[source_id])) for source_id, source in sources.items()]++ self.stdout.write(f"Found {len(source_intervals)} CDC sources to process (live_run={live_run}).")++ if not live_run:+ self.stdout.write(f"Done. processed={len(source_intervals)} failed=0")+ return++ failures = bulk_sync_cdc_extraction_schedules(source_intervals)+ for source_id, exc in failures:+ logger.exception("Failed to backfill CDC extraction schedule", source_id=source_id, exc_info=exc)++ processed = len(source_intervals) - len(failures)+ self.stdout.write(f"Done. processed={processed} failed={len(failures)}")diff --git a/posthog/management/commands/update_data_import_schedules.py b/products/data_warehouse/backend/management/commands/update_data_import_schedules.pysimilarity index 83%rename from posthog/management/commands/update_data_import_schedules.pyrename to products/data_warehouse/backend/management/commands/update_data_import_schedules.pyindex bf8cc9cda98a..39fece813374 100644--- a/posthog/management/commands/update_data_import_schedules.py+++ b/products/data_warehouse/backend/management/commands/update_data_import_schedules.py@@ -5,9 +5,8 @@ from django.conf import settingsfrom django.core.management.base import BaseCommand, CommandErrorimport structlog-import temporalio-from products.data_warehouse.backend.data_load.service import sync_external_data_job_workflow+from products.data_warehouse.backend.data_load.service import bulk_update_external_data_job_schedulesfrom products.warehouse_sources.backend.models.external_data_schema import (ExternalDataSchema,sync_frequency_to_sync_frequency_interval,@@ -16,27 +15,6 @@ from products.warehouse_sources.backend.models.external_data_schema import (logger = structlog.get_logger(__name__)-def _update_external_data_schema_schedule(external_data_schema: ExternalDataSchema):- logger.info("Updating external data schema schedule...", external_data_schema_id=str(external_data_schema.id))-- try:- sync_external_data_job_workflow(- external_data_schema, create=False, should_sync=external_data_schema.should_sync- )- except temporalio.service.RPCError as e:- if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:- # if the schema was never activated, then there won't be a schedule- pass- else:- logger.exception(- "Error updating external data schema schedule", external_data_schema_id=str(external_data_schema.id)- )- except Exception:- logger.exception(- "Error updating external data schema schedule", external_data_schema_id=str(external_data_schema.id)- )--def _get_external_data_schemas(**options) -> list[ExternalDataSchema]:filters_applied = Falsequeryset = ExternalDataSchema.objects.filter(deleted=False)@@ -171,8 +149,15 @@ class Command(BaseCommand):logger.info("Aborting")return- for num, external_data_schema in enumerate(external_data_schemas):- _update_external_data_schema_schedule(external_data_schema)- logger.info(f"Updated schedule {num + 1} of {len(external_data_schemas)}")+ # `bulk_update_external_data_job_schedules` re-issues each schedule over a single+ # shared Temporal connection and runs the updates concurrently — far faster than+ # reconnecting per schema. It returns skipped (never-activated) schemas and failures+ # instead of raising, so one bad schema doesn't abort the rest.+ skipped, failures = bulk_update_external_data_job_schedules(external_data_schemas)+ for schema_id, exc in failures:+ logger.exception(+ "Error updating external data schema schedule", external_data_schema_id=schema_id, exc_info=exc+ )- logger.info("Done!")+ updated = len(external_data_schemas) - len(skipped) - len(failures)+ logger.info("Done!", updated=updated, skipped=len(skipped), failed=len(failures))diff --git a/products/data_warehouse/backend/management/test/test_backfill_cdc_extraction_schedules.py b/products/data_warehouse/backend/management/test/test_backfill_cdc_extraction_schedules.pynew file mode 100644index 000000000000..87f027576385--- /dev/null+++ b/products/data_warehouse/backend/management/test/test_backfill_cdc_extraction_schedules.py@@ -0,0 +1,187 @@+import uuid+from datetime import timedelta+from io import StringIO++import pytest+from unittest.mock import patch++from django.core.management import call_command++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++BULK_HELPER_PATH = (+ "products.data_warehouse.backend.management.commands.backfill_cdc_extraction_schedules."+ "bulk_sync_cdc_extraction_schedules"+)+++def _create_source(+ team,+ source_type: str = "Postgres",+ access_method: str = ExternalDataSource.AccessMethod.WAREHOUSE,+ deleted: bool = False,+) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type=source_type,+ status="Completed",+ access_method=access_method,+ job_inputs={},+ deleted=deleted,+ )+++def _create_schema(+ source,+ sync_type: str = ExternalDataSchema.SyncType.CDC,+ should_sync: bool = True,+ deleted: bool = False,+ interval: timedelta = timedelta(hours=6),+) -> ExternalDataSchema:+ schema = ExternalDataSchema.objects.create(+ name="TestSchema",+ team=source.team,+ source=source,+ should_sync=should_sync,+ sync_type=sync_type,+ sync_frequency_interval=interval,+ sync_time_of_day="00:00:00",+ )+ if deleted:+ schema.soft_delete()+ return schema+++class TestBackfillCdcExtractionSchedules:+ def test_dry_run_does_not_call_helper(self, team):+ source = _create_source(team)+ _create_schema(source)++ with patch(BULK_HELPER_PATH) as mock_bulk:+ out = StringIO()+ call_command("backfill_cdc_extraction_schedules", stdout=out)++ assert mock_bulk.call_count == 0+ assert "Found 1 CDC sources to process (live_run=False)" in out.getvalue()+ assert "processed=1" in out.getvalue()++ def test_live_run_calls_bulk_helper_once(self, team):+ source = _create_source(team)+ _create_schema(source)++ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:+ out = StringIO()+ call_command("backfill_cdc_extraction_schedules", "--live-run", stdout=out)++ assert mock_bulk.call_count == 1+ pairs = mock_bulk.call_args.args[0]+ assert len(pairs) == 1+ assert pairs[0][0].id == source.id+ assert "processed=1 failed=0" in out.getvalue()++ def test_interval_is_minimum_across_cdc_schemas(self, team):+ source = _create_source(team)+ _create_schema(source, interval=timedelta(hours=6))+ _create_schema(source, interval=timedelta(hours=1))++ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:+ call_command("backfill_cdc_extraction_schedules", "--live-run")++ pairs = mock_bulk.call_args.args[0]+ # one source, deduped, with the minimum interval+ assert len(pairs) == 1+ assert pairs[0][1] == timedelta(hours=1)++ def test_skips_non_cdc_schemas(self, team):+ source = _create_source(team)+ _create_schema(source, sync_type=ExternalDataSchema.SyncType.FULL_REFRESH)++ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:+ out = StringIO()+ call_command("backfill_cdc_extraction_schedules", "--live-run", stdout=out)++ assert mock_bulk.call_args.args[0] == []+ assert "Found 0 CDC sources" in out.getvalue()++ def test_skips_paused_and_deleted_cdc_schemas(self, team):+ source = _create_source(team)+ _create_schema(source, should_sync=False)+ _create_schema(source, deleted=True)++ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:+ out = StringIO()+ call_command("backfill_cdc_extraction_schedules", "--live-run", stdout=out)++ assert mock_bulk.call_args.args[0] == []+ assert "Found 0 CDC sources" in out.getvalue()++ def test_skips_deleted_sources(self, team):+ # A soft-deleted source whose CDC schema was left non-deleted must not have its+ # schedule resurrected by the fleet-wide backfill.+ source = _create_source(team, deleted=True)+ _create_schema(source)++ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:+ out = StringIO()+ call_command("backfill_cdc_extraction_schedules", "--live-run", stdout=out)++ assert mock_bulk.call_args.args[0] == []+ assert "Found 0 CDC sources" in out.getvalue()++ def test_skips_direct_query_sources(self, team):+ source = _create_source(team, access_method=ExternalDataSource.AccessMethod.DIRECT)+ _create_schema(source)++ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:+ out = StringIO()+ call_command("backfill_cdc_extraction_schedules", "--live-run", stdout=out)++ assert mock_bulk.call_args.args[0] == []+ assert "Found 0 CDC sources" in out.getvalue()++ def test_team_id_filter(self, team):+ from posthog.models import Team++ other_team = Team.objects.create(organization=team.organization, name="other")+ source = _create_source(team)+ _create_schema(source)+ other_source = _create_source(other_team)+ _create_schema(other_source)++ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:+ call_command("backfill_cdc_extraction_schedules", "--live-run", "--team-id", str(team.id))++ pairs = mock_bulk.call_args.args[0]+ assert len(pairs) == 1+ assert pairs[0][0].team_id == team.id++ def test_source_type_filter(self, team):+ pg = _create_source(team, source_type="Postgres")+ _create_schema(pg)+ mysql = _create_source(team, source_type="MySQL")+ _create_schema(mysql)++ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:+ call_command("backfill_cdc_extraction_schedules", "--live-run", "--source-type", "Postgres")++ pairs = mock_bulk.call_args.args[0]+ assert len(pairs) == 1+ assert pairs[0][0].source_type == "Postgres"++ def test_reports_failures_from_bulk_helper(self, team):+ source = _create_source(team)+ _create_schema(source)++ with patch(BULK_HELPER_PATH, return_value=[(str(source.id), Exception("boom"))]) as mock_bulk:+ out = StringIO()+ call_command("backfill_cdc_extraction_schedules", "--live-run", stdout=out)++ assert mock_bulk.call_count == 1+ assert "processed=0" in out.getvalue()+ assert "failed=1" in out.getvalue()diff --git a/posthog/management/commands/test/test_update_data_import_schedules.py b/products/data_warehouse/backend/management/test/test_update_data_import_schedules.pysimilarity index 99%rename from posthog/management/commands/test/test_update_data_import_schedules.pyrename to products/data_warehouse/backend/management/test/test_update_data_import_schedules.pyindex a049a838d576..5034989ebcf6 100644--- a/posthog/management/commands/test/test_update_data_import_schedules.py+++ b/products/data_warehouse/backend/management/test/test_update_data_import_schedules.py@@ -11,11 +11,11 @@ from temporalio.service import RPCErrorfrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_team-from posthog.management.commands.update_data_import_schedules import _get_external_data_schemasfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.common.schedule import describe_schedule, update_schedulefrom products.data_warehouse.backend.data_load.service import sync_external_data_job_workflow+from products.data_warehouse.backend.management.commands.update_data_import_schedules import _get_external_data_schemasfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource