: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 discovery schedules over one connection (#61201)
Marcus Hoff7affaa2f909
diff --git a/products/data_warehouse/backend/data_load/service.py b/products/data_warehouse/backend/data_load/service.pyindex 7b04ed6f1084..9da189a6d489 100644--- a/products/data_warehouse/backend/data_load/service.py+++ b/products/data_warehouse/backend/data_load/service.py@@ -539,6 +539,41 @@ def sync_discover_schemas_schedule(source: ExternalDataSource, create: bool = Faraise+@async_to_sync+async def bulk_sync_discover_schemas_schedules(+ sources: list[ExternalDataSource],+) -> list[tuple[str, BaseException]]:+ """Upsert discover-schemas schedules for many sources over a single shared connection.++ `sync_discover_schemas_schedule` opens a fresh Temporal connection on every call, so+ looping it over thousands of sources (e.g. a backfill) spends almost all of its time+ reconnecting. This connects once and runs the upserts concurrently. Returns+ ``(source_id, exception)`` pairs for any schedules that failed — a partial failure does+ not abort the rest, so the caller can attribute each failure to a specific source.+ """+ if not sources:+ return []++ temporal = await async_connect()+ semaphore = asyncio.Semaphore(_BULK_SCHEDULE_CONCURRENCY)++ async def _sync_one(source: ExternalDataSource) -> None:+ async with semaphore:+ schedule_id = _get_discover_schemas_schedule_id(str(source.id))+ schedule = get_discover_schemas_schedule(source)+ 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 sources]+ results = await asyncio.gather(*(_sync_one(source) for source in sources), return_exceptions=True)+ return [(source_id, result) for source_id, result in zip(source_ids, results) if isinstance(result, BaseException)]++def delete_discover_schemas_schedule(source_id: str) -> None:schedule_id = _get_discover_schemas_schedule_id(source_id)try:diff --git a/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.py b/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.pyindex cc624a6a11b8..2d067cabb293 100644--- a/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.py+++ b/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.py@@ -6,8 +6,9 @@ Temporal schedule (``discover-schemas-{source_id}``) created at source-creationthis command ensures the schedule exists for sources that were created before thatwiring landed.-Idempotent: safe to re-run. ``sync_discover_schemas_schedule`` upserts the schedule-(creates if missing, updates otherwise).+Idempotent: safe to re-run. ``bulk_sync_discover_schemas_schedules`` upserts each+schedule (creates if missing, updates otherwise) over a single shared Temporal+connection, running the per-source upserts concurrently.Usage:# Dry-run (default) — counts sources, creates nothing@@ -33,7 +34,7 @@ import structlogfrom posthog.temporal.data_imports.sources import SourceRegistry-from products.data_warehouse.backend.data_load.service import sync_discover_schemas_schedule+from products.data_warehouse.backend.data_load.service import bulk_sync_discover_schemas_schedulesfrom products.data_warehouse.backend.types import ExternalDataSourceTypefrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -77,12 +78,8 @@ class Command(BaseCommand):if team_id_filter is not None:queryset = queryset.filter(team_id=team_id_filter)- total = queryset.count()- self.stdout.write(f"Found {total} sources to process (live_run={live_run}).")-- processed = 0+ eligible: list[ExternalDataSource] = []skipped_unregistered = 0- failed = 0for source in queryset.iterator(chunk_size=200):try:@@ -95,23 +92,23 @@ class Command(BaseCommand):skipped_unregistered += 1continue- if not live_run:- processed += 1- continue+ eligible.append(source)- try:- # `create=False` upserts: updates if the schedule exists, creates if not.- # This makes the command idempotent under partial failures and re-runs.- sync_discover_schemas_schedule(source, create=False)- processed += 1- except Exception as e:- logger.exception(- "Failed to backfill discovery schedule",- source_id=str(source.id),- team_id=source.team_id,- source_type=source.source_type,- exc_info=e,- )- failed += 1-- self.stdout.write(f"Done. processed={processed} skipped_unregistered={skipped_unregistered} failed={failed}")+ self.stdout.write(f"Found {len(eligible)} sources to process (live_run={live_run}).")++ if not live_run:+ self.stdout.write(f"Done. processed={len(eligible)} skipped_unregistered={skipped_unregistered} failed=0")+ return++ # `bulk_sync_discover_schemas_schedules` upserts over a single shared Temporal+ # connection and runs the per-source upserts concurrently — far faster than+ # reconnecting per source. It returns failures instead of raising, so a single bad+ # source doesn't abort the backfill.+ failures = bulk_sync_discover_schemas_schedules(eligible)+ for source_id, exc in failures:+ logger.exception("Failed to backfill discovery schedule", source_id=source_id, exc_info=exc)++ processed = len(eligible) - len(failures)+ self.stdout.write(+ f"Done. processed={processed} skipped_unregistered={skipped_unregistered} failed={len(failures)}"+ )diff --git a/products/data_warehouse/backend/management/test/test_backfill_discovery_schedules.py b/products/data_warehouse/backend/management/test/test_backfill_discovery_schedules.pyindex bba9a151adee..b5003251d9cb 100644--- a/products/data_warehouse/backend/management/test/test_backfill_discovery_schedules.py+++ b/products/data_warehouse/backend/management/test/test_backfill_discovery_schedules.py@@ -10,6 +10,11 @@ from products.warehouse_sources.backend.models.external_data_source import Exterpytestmark = pytest.mark.django_db+BULK_HELPER_PATH = (+ "products.data_warehouse.backend.management.commands.backfill_discovery_schedules."+ "bulk_sync_discover_schemas_schedules"+)+def _create_source(team,@@ -37,69 +42,59 @@ class TestBackfillDiscoverySchedules:_create_source(team)_create_source(team)- with patch(- "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule"- ) as mock_sync:+ with patch(BULK_HELPER_PATH) as mock_bulk:out = StringIO()call_command("backfill_discovery_schedules", stdout=out)- assert mock_sync.call_count == 0+ assert mock_bulk.call_count == 0assert "Found 2 sources to process (live_run=False)" in out.getvalue()assert "processed=2" in out.getvalue()- def test_live_run_calls_helper_per_source(self, team):+ def test_live_run_calls_bulk_helper_once(self, team):_create_source(team)_create_source(team)- with patch(- "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule"- ) as mock_sync:+ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:out = StringIO()call_command("backfill_discovery_schedules", "--live-run", stdout=out)- assert mock_sync.call_count == 2- # Helper is called with create=False (idempotent upsert path)- for call in mock_sync.call_args_list:- assert call.kwargs == {"create": False}+ # Single bulk call over a shared connection, with both eligible sources.+ assert mock_bulk.call_count == 1+ assert len(mock_bulk.call_args.args[0]) == 2assert "processed=2 skipped_unregistered=0 failed=0" in out.getvalue()def test_skips_direct_query_sources(self, team):_create_source(team)_create_source(team, source_type="Postgres", access_method=ExternalDataSource.AccessMethod.DIRECT)- with patch(- "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule"- ) as mock_sync:+ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:out = StringIO()call_command("backfill_discovery_schedules", "--live-run", stdout=out)- assert mock_sync.call_count == 1+ assert len(mock_bulk.call_args.args[0]) == 1assert "Found 1 sources to process" in out.getvalue()def test_skips_soft_deleted_sources(self, team):_create_source(team)_create_source(team, deleted=True)- with patch(- "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule"- ) as mock_sync:+ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:out = StringIO()call_command("backfill_discovery_schedules", "--live-run", stdout=out)- assert mock_sync.call_count == 1+ assert len(mock_bulk.call_args.args[0]) == 1assert "Found 1 sources to process" in out.getvalue()def test_source_type_filter(self, team):_create_source(team, source_type="Stripe")_create_source(team, source_type="Hubspot")- with patch(- "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule"- ) as mock_sync:+ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:call_command("backfill_discovery_schedules", "--live-run", "--source-type", "Stripe")- assert mock_sync.call_count == 1- assert mock_sync.call_args.args[0].source_type == "Stripe"+ eligible = mock_bulk.call_args.args[0]+ assert len(eligible) == 1+ assert eligible[0].source_type == "Stripe"def test_team_id_filter(self, team):from posthog.models import Team@@ -108,40 +103,34 @@ class TestBackfillDiscoverySchedules:_create_source(team)_create_source(other_team)- with patch(- "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule"- ) as mock_sync:+ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:call_command("backfill_discovery_schedules", "--live-run", "--team-id", str(team.id))- assert mock_sync.call_count == 1- assert mock_sync.call_args.args[0].team_id == team.id+ eligible = mock_bulk.call_args.args[0]+ assert len(eligible) == 1+ assert eligible[0].team_id == team.iddef test_skips_unregistered_source_types(self, team):_create_source(team, source_type="Stripe")_create_source(team, source_type="NotARealSourceType")- with patch(- "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule"- ) as mock_sync:+ with patch(BULK_HELPER_PATH, return_value=[]) as mock_bulk:out = StringIO()call_command("backfill_discovery_schedules", "--live-run", stdout=out)- assert mock_sync.call_count == 1+ assert len(mock_bulk.call_args.args[0]) == 1assert "skipped_unregistered=1" in out.getvalue()- def test_continues_after_per_source_failure(self, team):- _create_source(team)+ def test_reports_failures_from_bulk_helper(self, team):+ source = _create_source(team)_create_source(team)_create_source(team)- # First call raises, the rest succeed — command must keep going and report failed=1.- with patch(- "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule",- side_effect=[Exception("boom"), None, None],- ) as mock_sync:+ # One source fails inside the bulk helper — command must report failed=1 and not raise.+ with patch(BULK_HELPER_PATH, return_value=[(str(source.id), Exception("boom"))]) as mock_bulk:out = StringIO()call_command("backfill_discovery_schedules", "--live-run", stdout=out)- assert mock_sync.call_count == 3+ assert mock_bulk.call_count == 1assert "processed=2" in out.getvalue()assert "failed=1" in out.getvalue()