: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
fix(data-warehouse): stop reporting expected import schedule conditions (#104480)
Tom Owerse114236f8f47
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.pyindex ffebbfccc2db..35a441002392 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py@@ -355,8 +355,7 @@ def test_sync_new_schemas_activity_self_destructs_when_source_unavailable(with mock.patch("products.warehouse_sources.backend.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)+ activity_environment.run(sync_new_schemas_activity, inputs)mock_delete_schedule.assert_called_once_with(source_id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex d698ed2c550c..bd9f6670f6f4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -15,6 +15,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Team+from posthog.temporal.common.errors import NonReportableErrorfrom posthog.temporal.common.logger import get_loggerfrom products.data_warehouse.backend.facade.api import delete_external_data_schedule@@ -75,6 +76,16 @@ def is_pipeline_v3_enabled(team_id: int, source_type: str) -> bool:LOGGER = get_logger(__name__)+class SourceOrSchemaDeletedError(NonReportableError):+ """The source or schema was deleted while its sync schedule was still live.++ Deletion cancels the schedule, but a run Temporal already started keeps going, so this+ activity can find the rows gone. The run must still fail, because there is no schema left+ to create a job for. It is not a defect either, so subclassing ``NonReportableError`` keeps+ the race out of error tracking instead of opening an issue per orphaned run.+ """++def _statistics_stale(team_id: int, table: DataWarehouseTable | None) -> bool:"""Whether column statistics need recomputing: no stats yet, or the freshest column row is olderthan the recompute interval. Mirrors compute_table_statistics' own skip check so we don't spawn a@@ -312,14 +323,16 @@ def create_external_data_job_model_activity(close_old_connections()- try:- source_exists = ExternalDataSource.objects.filter(id=inputs.source_id).exclude(deleted=True).exists()- schema_exists = ExternalDataSchema.objects.filter(id=inputs.schema_id).exclude(deleted=True).exists()-- if not source_exists or not schema_exists:- delete_external_data_schedule(str(inputs.schema_id))- raise Exception("Source or schema no longer exists - deleted temporal schedule")+ # Kept out of the try below so the generic handler does not log a stack trace for a+ # deletion race that the activity handles.+ source_exists = ExternalDataSource.objects.filter(id=inputs.source_id).exclude(deleted=True).exists()+ schema_exists = ExternalDataSchema.objects.filter(id=inputs.schema_id).exclude(deleted=True).exists()+ if not source_exists or not schema_exists:+ delete_external_data_schedule(str(inputs.schema_id))+ logger.info("Source or schema no longer exists, deleted the sync schedule")+ raise SourceOrSchemaDeletedError("Source or schema no longer exists - deleted temporal schedule")+ try:schema = ExternalDataSchema.objects.get(team_id=inputs.team_id, id=inputs.schema_id)source: ExternalDataSource = schema.sourcediff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.pyindex 3af482e0628b..d48b8f44c729 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py@@ -59,11 +59,26 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:)if not source_exists:delete_discover_schemas_schedule(str(inputs.source_id))- raise Exception("Source no longer exists - deleted discover-schemas temporal schedule")+ logger.info("Source no longer exists, deleted the discover-schemas schedule")+ returnsource = ExternalDataSource.objects.get(team_id=inputs.team_id, id=inputs.source_id)- source_type_enum = ExternalDataSourceType(source.source_type)+ try:+ source_type_enum = ExternalDataSourceType(source.source_type)+ except ValueError:+ # A stored source type that this build's enum does not carry cannot be synced by any+ # code path here, so every discovery run repeats the same failure. Two situations reach+ # this: a source type that was dropped from the enum while rows still referenced it, and+ # a source type that web code creates before every worker carries it. The second one+ # recovers on its own once the worker catches up, so the schedule stays in place instead+ # of self-destructing.+ logger.warning(+ "Skipping schema discovery: stored source type is not a known ExternalDataSourceType",+ source_type=source.source_type,+ )+ return+if SourceRegistry.is_registered(source_type_enum):if not source.job_inputs:returndiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.pyindex f907192d72e5..c0afce3025c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py@@ -11,6 +11,7 @@ from parameterized import parameterizedfrom temporalio.exceptions import ApplicationErrorfrom posthog.models import Organization, Team+from posthog.temporal.common.posthog_client import is_expected_activity_failurefrom products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotationfrom products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatistics@@ -21,6 +22,7 @@ from products.warehouse_sources.backend.models.external_data_source import Exterfrom products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (CreateExternalDataJobModelActivityInputs,+ SourceOrSchemaDeletedError,_build_schema_snapshot,_create_job,_enrichment_pending,@@ -271,3 +273,49 @@ class TestCreateJobActivityStatusOrdering:schema.refresh_from_db()assert schema.status == ExternalDataSchema.Status.FAILED+++class TestCreateJobActivityDeletedSourceOrSchema:+ # Deleting a source or a schema cancels its schedule, but a run Temporal already started still+ # reaches this activity and finds the rows gone. The activity has to cancel the leftover+ # schedule and fail with an error the interceptor will not report, or the race opens an error+ # tracking issue per orphaned run.+ @parameterized.expand(+ [+ ("source_deleted", True, False),+ ("schema_deleted", False, True),+ ]+ )+ @patch(f"{MODULE}.close_old_connections")+ @patch(f"{MODULE}.delete_external_data_schedule")+ def test_schedule_is_cancelled_and_the_failure_is_not_reported(+ self,+ _name: str,+ delete_source: bool,+ delete_schema: bool,+ mock_delete_schedule: MagicMock,+ _mock_close_connections: MagicMock,+ ) -> None:+ team = _team()+ schema = _schema(team, None)+ if delete_source:+ schema.source.deleted = True+ schema.source.save()+ if delete_schema:+ schema.deleted = True+ schema.save()++ inputs = CreateExternalDataJobModelActivityInputs(+ team_id=team.id,+ schema_id=schema.id,+ source_id=schema.source_id,+ billable=True,+ )++ with pytest.raises(SourceOrSchemaDeletedError) as exc_info:+ create_external_data_job_model_activity(inputs)++ assert is_expected_activity_failure(exc_info.value)+ mock_delete_schedule.assert_called_once_with(str(schema.id))+ assert ExternalDataJob.objects.filter(schema_id=schema.id).count() == 0diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.pyindex db0427aaf007..a3290e7f474b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py@@ -42,6 +42,56 @@ def _patch_common(source_mock, schemas_created=None, source_api_version=None, me}+def _patch_db(source_type, *, source_exists=True):+ """Patch the DB reads only, so the activity resolves `source_type` through the real enum."""+ objects = mock.MagicMock()+ objects.filter.return_value.exclude.return_value.exists.return_value = source_exists+ objects.get.return_value = mock.MagicMock(+ source_type=source_type, job_inputs={"k": "v"}, deleted=False, api_version=None+ )+ return objects+++def test_deleted_source_drops_the_schedule_and_completes():+ # A source deleted since the schedule was created is a race with a schedule that already+ # fired, not a defect. The activity must drop the schedule and complete, because failing+ # here opens an error tracking issue on every remaining discovery run.+ objects = _patch_db("GoogleAds", source_exists=False)++ with (+ mock.patch.object(module, "close_old_connections"),+ mock.patch.object(module.ExternalDataSource, "objects", objects),+ mock.patch.object(module, "delete_discover_schemas_schedule") as delete_schedule,+ mock.patch.object(module, "sync_old_schemas_with_new_schemas") as sync_schemas,+ ):+ sync_new_schemas_activity(SyncNewSchemasActivityInputs(source_id="src", team_id=1))++ delete_schedule.assert_called_once_with("src")+ sync_schemas.assert_not_called()+++def test_source_type_outside_the_enum_is_skipped():+ # A stored source type this build's enum does not carry (one dropped from the enum while rows+ # still referenced it, or one created by web code before every worker carries it) cannot be+ # synced by any code path here. Resolving it must not fail the activity, or the one row keeps+ # failing every discovery run for good.+ objects = _patch_db("NotARealSourceType")++ with (+ mock.patch.object(module, "close_old_connections"),+ mock.patch.object(module.ExternalDataSource, "objects", objects),+ mock.patch.object(module, "delete_discover_schemas_schedule") as delete_schedule,+ mock.patch.object(module, "sync_old_schemas_with_new_schemas") as sync_schemas,+ mock.patch.object(module.SourceRegistry, "get_source") as get_source,+ ):+ sync_new_schemas_activity(SyncNewSchemasActivityInputs(source_id="src", team_id=1))++ get_source.assert_not_called()+ sync_schemas.assert_not_called()+ # The value can become known again on a newer worker, so the schedule has to survive.+ delete_schedule.assert_not_called()++def _run_activity(source_mock, schemas_created=None, source_api_version=None, merge_error=None):patches = _patch_common(source_mock, schemas_created, source_api_version=source_api_version, merge_error=merge_error