: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
feat(data-warehouse): add per-source schema discovery schedule (#57968)
Marcus Hof971c498bf282
diff --git a/posthog/temporal/data_imports/discover_schemas_workflow.py b/posthog/temporal/data_imports/discover_schemas_workflow.pynew file mode 100644index 000000000000..07c133854755--- /dev/null+++ b/posthog/temporal/data_imports/discover_schemas_workflow.py@@ -0,0 +1,42 @@+import json+import datetime as dt++from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.data_imports.workflow_activities.sync_new_schemas import (+ SyncNewSchemasActivityInputs,+ sync_new_schemas_activity,+)++[email protected](name="discover-schemas")+class DiscoverSchemasWorkflow(PostHogWorkflow):+ """Per-source schema discovery workflow.++ Runs `sync_new_schemas_activity` for a single `ExternalDataSource` on a slow+ cadence (every 6h), independently of per-schema sync schedules. This+ keeps the expensive schema-discovery pass out of the per-schema sync hot+ path — see `external_data_job.ExternalDataJobWorkflow.run`, which used to+ fire it on every individual schema sync.+ """++ @staticmethod+ def parse_inputs(inputs: list[str]) -> SyncNewSchemasActivityInputs:+ loaded = json.loads(inputs[0])+ return SyncNewSchemasActivityInputs(**loaded)++ @workflow.run+ async def run(self, inputs: SyncNewSchemasActivityInputs) -> None:+ await workflow.execute_activity(+ sync_new_schemas_activity,+ inputs,+ start_to_close_timeout=dt.timedelta(minutes=10),+ retry_policy=RetryPolicy(+ initial_interval=dt.timedelta(seconds=10),+ maximum_interval=dt.timedelta(seconds=60),+ maximum_attempts=3,+ non_retryable_error_types=["NotNullViolation", "IntegrityError", "BaseSSHTunnelForwarderError"],+ ),+ )diff --git a/posthog/temporal/data_imports/settings.py b/posthog/temporal/data_imports/settings.pyindex 754092e519d1..c42b3ec83566 100644--- a/posthog/temporal/data_imports/settings.py+++ b/posthog/temporal/data_imports/settings.py@@ -5,6 +5,7 @@ from posthog.temporal.data_imports.cdc.activities import ()from posthog.temporal.data_imports.cdc.workflows import CDCExtractionWorkflow, CDCSlotCleanupWorkflowfrom posthog.temporal.data_imports.cdp_producer_job import CDPProducerJobWorkflow, produce_to_cdp_kafka_activity+from posthog.temporal.data_imports.discover_schemas_workflow import DiscoverSchemasWorkflowfrom posthog.temporal.data_imports.external_data_job import (ExternalDataJobWorkflow,calculate_table_size_activity,@@ -27,7 +28,13 @@ from posthog.temporal.data_imports.workflow_activities.emit_signals import (emit_data_import_signals_activity,)-WORKFLOWS = [ExternalDataJobWorkflow, CDPProducerJobWorkflow, CDCExtractionWorkflow, CDCSlotCleanupWorkflow]+WORKFLOWS = [+ ExternalDataJobWorkflow,+ CDPProducerJobWorkflow,+ CDCExtractionWorkflow,+ CDCSlotCleanupWorkflow,+ DiscoverSchemasWorkflow,+]ACTIVITIES = [create_external_data_job_model_activity,diff --git a/posthog/temporal/data_imports/workflow_activities/sync_new_schemas.py b/posthog/temporal/data_imports/workflow_activities/sync_new_schemas.pyindex 50d74044c5a3..4ea0c1e8405e 100644--- a/posthog/temporal/data_imports/workflow_activities/sync_new_schemas.py+++ b/posthog/temporal/data_imports/workflow_activities/sync_new_schemas.py@@ -9,6 +9,7 @@ from temporalio import activityfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.data_imports.sources import SourceRegistry+from products.data_warehouse.backend.data_load.service import delete_discover_schemas_schedulefrom products.data_warehouse.backend.models import ExternalDataSource, sync_old_schemas_with_new_schemasfrom products.data_warehouse.backend.types import ExternalDataSourceType@@ -37,6 +38,16 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:logger.info("Syncing new -> old schemas")+ # Self-destruct: if the source has been deleted (or hard-removed) since the schedule+ # was created, drop the discovery schedule so we stop firing zombie workflows. Mirrors+ # the existing per-schema pattern in `create_external_data_job_model_activity`.+ source_exists = (+ ExternalDataSource.objects.filter(team_id=inputs.team_id, id=inputs.source_id).exclude(deleted=True).exists()+ )+ if not source_exists:+ delete_discover_schemas_schedule(str(inputs.source_id))+ raise Exception("Source no longer exists - deleted discover-schemas temporal schedule")+source = ExternalDataSource.objects.get(team_id=inputs.team_id, id=inputs.source_id)source_type_enum = ExternalDataSourceType(source.source_type)diff --git a/posthog/temporal/tests/external_data/test_external_data_job.py b/posthog/temporal/tests/external_data/test_external_data_job.pyindex 8df8e1678159..cd60b4254694 100644--- a/posthog/temporal/tests/external_data/test_external_data_job.py+++ b/posthog/temporal/tests/external_data/test_external_data_job.py@@ -286,6 +286,40 @@ def test_create_external_job_activity_update_schemas(activity_environment, team,assert len(all_schemas) == len(STRIPE_ENDPOINTS)[email protected]("source_state", ["never_existed", "soft_deleted"])[email protected]_db(transaction=True)+def test_sync_new_schemas_activity_self_destructs_when_source_unavailable(+ activity_environment, team, source_state, **kwargs+):+ if source_state == "never_existed":+ source_id = str(uuid.uuid4())+ else:+ source = ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ team=team,+ status="running",+ source_type="Stripe",+ job_inputs={+ "auth_method": {"selection": "api_key", "stripe_secret_key": "test-key"},+ "stripe_account_id": "acct_id",+ },+ )+ source.soft_delete()+ source_id = str(source.pk)++ inputs = SyncNewSchemasActivityInputs(source_id=source_id, team_id=team.id)++ with mock.patch(+ "posthog.temporal.data_imports.workflow_activities.sync_new_schemas.delete_discover_schemas_schedule"+ ) as mock_delete_schedule:+ with pytest.raises(Exception, match="Source no longer exists"):+ activity_environment.run(sync_new_schemas_activity, inputs)++ mock_delete_schedule.assert_called_once_with(source_id)++@pytest.mark.django_db(transaction=True)@pytest.mark.asyncioasync def test_update_external_job_activity(activity_environment, team, **kwargs):diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 93e29533c167..2d40bfbd0d67 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -58,9 +58,11 @@ from products.data_warehouse.backend.api.external_data_schema import ()from products.data_warehouse.backend.data_load.service import (cancel_external_data_workflow,+ delete_discover_schemas_schedule,delete_external_data_schedule,is_any_external_data_schema_paused,is_cdc_enabled_for_team,+ sync_discover_schemas_schedule,sync_external_data_job_workflow,trigger_external_data_source_workflow,)@@ -1156,6 +1158,17 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi# Log error but don't fail because the source model was already createdlogger.exception("Could not trigger external data job", exc_info=e)+ # Per-source schema discovery schedule. Runs every 6h so newly added+ # upstream resources (Slack channels, Postgres tables, …) get picked up+ # without re-discovering on every per-schema sync tick. Direct-query+ # sources resolve schemas at query time, so they opt out of all+ # background sync — including this discovery cadence.+ if new_source_model.supports_scheduled_sync:+ try:+ sync_discover_schemas_schedule(new_source_model, create=True)+ except Exception as e:+ logger.exception("Could not create schema discovery schedule", exc_info=e)+# Start CDC extraction schedule if any CDC schemas are activeif cdc_enabled:try:@@ -1369,6 +1382,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiexcept Exception as e:capture_exception(e)+ try:+ delete_discover_schemas_schedule(str(instance.id))+ except Exception as e:+ capture_exception(e)+return Response(status=status.HTTP_204_NO_CONTENT)@action(methods=["POST"], detail=True)diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex 88d3b137afac..03123b992220 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -138,6 +138,90 @@ class TestExternalDataSource(APIBaseTest):len(STRIPE_ENDPOINTS),)+ @patch("products.data_warehouse.backend.api.external_data_source.sync_discover_schemas_schedule")+ @patch(+ "posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",+ return_value=(True, None),+ )+ def test_create_external_data_source_creates_discovery_schedule(self, _mock_validate, mock_sync_discover):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Stripe",+ "created_via": "web",+ "payload": {+ "auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"},+ "schemas": [+ {"name": STRIPE_SUBSCRIPTION_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},+ ],+ },+ },+ )++ assert response.status_code == 201, response.json()+ mock_sync_discover.assert_called_once()+ assert mock_sync_discover.call_args.kwargs == {"create": True}+ # First positional arg is the freshly created ExternalDataSource model+ created_source = mock_sync_discover.call_args.args[0]+ assert str(created_source.id) == response.json()["id"]++ @patch("products.data_warehouse.backend.api.external_data_source.sync_discover_schemas_schedule")+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")+ def test_create_direct_query_source_skips_discovery_schedule(self, mock_get_source, mock_sync_discover):+ # Direct-query sources resolve schemas at query time and opt out of all+ # background sync — no discovery schedule should be created.+ source_mock = mock_get_source.return_value+ source_mock.validate_config.return_value = (True, [])+ parsed_config = Mock()+ parsed_config.to_dict.return_value = {+ "host": "localhost",+ "port": 5432,+ "database": "app",+ "user": "user",+ "password": "pass",+ "schema": "public",+ }+ source_mock.parse_config.return_value = parsed_config+ source_mock.validate_credentials.return_value = (True, None)+ source_mock.get_connection_metadata.return_value = {+ "database": "app",+ "version": "Duckgres/DuckDB",+ "engine": "duckdb",+ "function_source": "duckdb_functions",+ "available_functions": ["duckdb_functions", "date_bin"],+ }+ source_mock.get_schemas.return_value = [+ SourceSchema(+ name="accounts",+ supports_incremental=False,+ supports_append=False,+ columns=[("id", "integer", False)],+ foreign_keys=[],+ ),+ ]++ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Postgres",+ "created_via": "web",+ "access_method": "direct",+ "prefix": "Primary database",+ "payload": {+ "host": "localhost",+ "port": 5432,+ "database": "app",+ "user": "user",+ "password": "pass",+ "schema": "public",+ "schemas": [{"name": "accounts", "should_sync": True, "sync_type": None}],+ },+ },+ )++ assert response.status_code == 201, response.json()+ mock_sync_discover.assert_not_called()+@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",return_value=(True, None),@@ -1117,6 +1201,16 @@ class TestExternalDataSource(APIBaseTest):assert ExternalDataSource.objects.filter(pk=source.pk, deleted=True).exists()assert ExternalDataSchema.objects.filter(pk=schema.pk, deleted=True).exists()+ @patch("products.data_warehouse.backend.api.external_data_source.delete_discover_schemas_schedule")+ def test_delete_external_data_source_tears_down_discovery_schedule(self, mock_delete_discover):+ source = self._create_external_data_source()+ self._create_external_data_schema(source.pk)++ response = self.client.delete(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}")++ assert response.status_code == 204+ mock_delete_discover.assert_called_once_with(str(source.pk))+@patch("products.data_warehouse.backend.api.external_data_source.capture_exception")@patch("products.data_warehouse.backend.api.external_data_source.delete_external_data_schedule",diff --git a/products/data_warehouse/backend/data_load/service.py b/products/data_warehouse/backend/data_load/service.pyindex ee06bc28d93d..dce97ad2b778 100644--- a/products/data_warehouse/backend/data_load/service.py+++ b/products/data_warehouse/backend/data_load/service.py@@ -389,6 +389,94 @@ def delete_cdc_extraction_schedule(source_id: str) -> None:pass+# ---------------------------------------------------------------------------+# Schema discovery scheduling (source-level)+# ---------------------------------------------------------------------------++DISCOVER_SCHEMAS_INTERVAL = timedelta(hours=6)+++def _get_discover_schemas_schedule_id(source_id: str) -> str:+ return f"discover-schemas-{source_id}"+++def get_discover_schemas_schedule(source: ExternalDataSource) -> Schedule:+ """Build a Temporal Schedule for the per-source schema-discovery workflow."""+ # Inline import breaks a circular dependency: `sync_new_schemas` needs+ # `delete_external_data_schedule` and `_get_discover_schemas_schedule_id` from this+ # module for self-cleanup when the source vanishes, so it imports from us at module+ # load time. Hoisting this import would deadlock the loader.+ from posthog.temporal.data_imports.workflow_activities.sync_new_schemas import SyncNewSchemasActivityInputs++ inputs = SyncNewSchemasActivityInputs(source_id=str(source.id), team_id=source.team_id)++ action = ScheduleActionStartWorkflow(+ "discover-schemas",+ asdict(inputs),+ id=_get_discover_schemas_schedule_id(str(source.id)),+ task_queue=str(settings.DATA_WAREHOUSE_TASK_QUEUE),+ retry_policy=RetryPolicy(+ initial_interval=timedelta(seconds=10),+ maximum_interval=timedelta(seconds=60),+ maximum_attempts=3,+ non_retryable_error_types=["NondeterminismError"],+ ),+ )++ # Deterministic per-source offset so sources sharing a cadence don't dogpile.+ offset_hours, offset_minutes = _jitter_timedelta(DISCOVER_SCHEMAS_INTERVAL, random.Random(str(source.id)))+ spec = ScheduleSpec(+ intervals=[+ ScheduleIntervalSpec(+ every=DISCOVER_SCHEMAS_INTERVAL,+ offset=timedelta(hours=offset_hours, minutes=offset_minutes),+ )+ ],+ )++ return Schedule(+ action=action,+ spec=spec,+ state=ScheduleState(note=f"Discover schemas schedule for source: {source.id}"),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )+++def sync_discover_schemas_schedule(source: ExternalDataSource, create: bool = False) -> None:+ """Create or update the per-source schema-discovery Temporal schedule.++ On ``create=True`` triggers an immediate run so a brand-new source picks up+ its initial schema list right away. On ``create=False`` (or when the+ schedule turns out not to exist), upserts idempotently — this makes the+ helper safe for both fresh deploys and the backfill management command.+ """+ temporal = sync_connect()+ schedule_id = _get_discover_schemas_schedule_id(str(source.id))+ schedule = get_discover_schemas_schedule(source)++ if create:+ create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=True)+ return++ try:+ update_schedule(temporal, id=schedule_id, schedule=schedule)+ except temporalio.service.RPCError as e:+ if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:+ create_schedule(temporal, id=schedule_id, schedule=schedule, trigger_immediately=True)+ else:+ raise+++def delete_discover_schemas_schedule(source_id: str) -> None:+ schedule_id = _get_discover_schemas_schedule_id(source_id)+ try:+ delete_external_data_schedule(schedule_id)+ except Exception:+ # delete_external_data_schedule already swallows NOT_FOUND; defensively+ # ignore other races (e.g. schedule deleted between fetch and delete).+ pass++_CDC_SLOT_CLEANUP_SCHEDULE_ID = "cdc-slot-cleanup-global"diff --git a/products/data_warehouse/backend/data_load/test/test_service.py b/products/data_warehouse/backend/data_load/test/test_service.pyindex 2aa68c41deb8..ae94b58041b8 100644--- a/products/data_warehouse/backend/data_load/test/test_service.py+++ b/products/data_warehouse/backend/data_load/test/test_service.py@@ -7,13 +7,22 @@ import pytestimport pytest_asynciofrom asgiref.sync import async_to_sync, sync_to_async-from temporalio.client import Client as TemporalClient+from temporalio.client import (+ Client as TemporalClient,+ ScheduleActionStartWorkflow,+)from temporalio.service import RPCErrorfrom posthog.models import Organization, Teamfrom posthog.temporal.common.client import sync_connect-from products.data_warehouse.backend.data_load.service import _jitter_timedelta, get_sync_schedule+from products.data_warehouse.backend.data_load.service import (+ DISCOVER_SCHEMAS_INTERVAL,+ _get_discover_schemas_schedule_id,+ _jitter_timedelta,+ get_discover_schemas_schedule,+ get_sync_schedule,+)from products.data_warehouse.backend.models import ExternalDataSchema, ExternalDataSourcepytestmark = [@@ -201,6 +210,22 @@ async def test_get_sync_schedule(external_data_source, team, sync_frequency_inteassert actual == expected+class TestDiscoverSchemasSchedule:+ @pytest.mark.asyncio+ async def test_schedule_targets_discover_schemas_workflow(self, external_data_source) -> None:+ schedule = get_discover_schemas_schedule(external_data_source)+ action = schedule.action+ assert isinstance(action, ScheduleActionStartWorkflow)+ assert action.workflow == "discover-schemas"+ assert action.id == _get_discover_schemas_schedule_id(str(external_data_source.id))+ # Inputs are passed as a single positional dict matching SyncNewSchemasActivityInputs.+ assert action.args[0] == {+ "source_id": str(external_data_source.id),+ "team_id": external_data_source.team_id,+ }+ assert schedule.spec.intervals[0].every == DISCOVER_SCHEMAS_INTERVAL++def test_jitter_timedelta():max_jitter = dt.timedelta(days=1)for _ in range(100):diff --git a/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.py b/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.pynew file mode 100644index 000000000000..4f6eacf54d6c--- /dev/null+++ b/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.py@@ -0,0 +1,117 @@+"""Backfill per-source schema-discovery schedules for existing ExternalDataSource rows.++Schema discovery used to run inline on every per-schema sync workflow, which scaled+disastrously for sources with thousands of schemas. It now runs on its own per-source+Temporal schedule (``discover-schemas-{source_id}``) created at source-creation time —+this command ensures the schedule exists for sources that were created before that+wiring landed.++Idempotent: safe to re-run. ``sync_discover_schemas_schedule`` upserts the schedule+(creates if missing, updates otherwise).++Usage:+ # Dry-run (default) — counts sources, creates nothing+ python manage.py backfill_discovery_schedules++ # Live run+ python manage.py backfill_discovery_schedules --live-run++ # Restrict to a specific source type+ python manage.py backfill_discovery_schedules --live-run --source-type Slack++ # Restrict to a specific team+ python manage.py backfill_discovery_schedules --live-run --team-id 2+"""++from __future__ import annotations++from typing import Any++from django.core.management.base import BaseCommand++import structlog++from 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.models import ExternalDataSource+from products.data_warehouse.backend.types import ExternalDataSourceType++logger = structlog.get_logger(__name__)+++class Command(BaseCommand):+ help = "Backfill per-source schema-discovery Temporal schedules for existing ExternalDataSource rows."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument(+ "--live-run",+ action="store_true",+ help="Actually create schedules (default is dry-run).",+ )+ parser.add_argument(+ "--source-type",+ type=str,+ default=None,+ help="Restrict to a specific source type (e.g. Slack, Stripe).",+ )+ 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"]++ # Direct-query sources resolve schemas at query time and opt out of all+ # background sync — they should not get a discovery schedule.+ queryset = ExternalDataSource.objects.exclude(deleted=True).exclude(+ access_method=ExternalDataSource.AccessMethod.DIRECT+ )+ if source_type_filter is not None:+ queryset = queryset.filter(source_type=source_type_filter)+ 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+ skipped_unregistered = 0+ failed = 0++ for source in queryset.iterator(chunk_size=200):+ try:+ source_type_enum = ExternalDataSourceType(source.source_type)+ except ValueError:+ skipped_unregistered += 1+ continue++ if not SourceRegistry.is_registered(source_type_enum):+ skipped_unregistered += 1+ continue++ if not live_run:+ processed += 1+ continue++ 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}")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.pynew file mode 100644index 000000000000..f581b790f7c5--- /dev/null+++ b/products/data_warehouse/backend/management/test/test_backfill_discovery_schedules.py@@ -0,0 +1,147 @@+import uuid+from io import StringIO++import pytest+from unittest.mock import patch++from django.core.management import call_command++from products.data_warehouse.backend.models import ExternalDataSource++pytestmark = pytest.mark.django_db+++def _create_source(+ team,+ source_type: str = "Stripe",+ deleted: bool = False,+ access_method: str = ExternalDataSource.AccessMethod.WAREHOUSE,+) -> ExternalDataSource:+ src = 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={"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test"}},+ )+ if deleted:+ src.soft_delete()+ return src+++class TestBackfillDiscoverySchedules:+ def test_dry_run_does_not_call_helper(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:+ out = StringIO()+ call_command("backfill_discovery_schedules", stdout=out)++ assert mock_sync.call_count == 0+ assert "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):+ _create_source(team)+ _create_source(team)++ with patch(+ "products.data_warehouse.backend.management.commands.backfill_discovery_schedules.sync_discover_schemas_schedule"+ ) as mock_sync:+ 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}+ assert "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:+ out = StringIO()+ call_command("backfill_discovery_schedules", "--live-run", stdout=out)++ assert mock_sync.call_count == 1+ assert "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:+ out = StringIO()+ call_command("backfill_discovery_schedules", "--live-run", stdout=out)++ assert mock_sync.call_count == 1+ assert "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:+ 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"++ def test_team_id_filter(self, team):+ from posthog.models import Team++ other_team = Team.objects.create(organization=team.organization, name="other")+ _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:+ 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++ def 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:+ out = StringIO()+ call_command("backfill_discovery_schedules", "--live-run", stdout=out)++ assert mock_sync.call_count == 1+ assert "skipped_unregistered=1" in out.getvalue()++ def test_continues_after_per_source_failure(self, team):+ _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:+ out = StringIO()+ call_command("backfill_discovery_schedules", "--live-run", stdout=out)++ assert mock_sync.call_count == 3+ assert "processed=2" in out.getvalue()+ assert "failed=1" in out.getvalue()