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.

fix(data-imports): close the FK race between a deleted source and job creation (#107367)

Tom Owersbe3c2854467c
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.py
index 1300f0f121b4..c3e17930044a 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
@@ -4,7 +4,7 @@ import datetime as dt
import dataclasses
from typing import Any
-from django.db import close_old_connections
+from django.db import IntegrityError, close_old_connections
from django.db.models import Max
from django.utils import timezone
@@ -88,6 +88,10 @@ class SourceOrSchemaDeletedError(NonReportableError):
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.
+
+ Also raised when the deletion happens in the narrower window between the existence check
+ above and the job insert (e.g. a team torn down mid-run cascades the source/schema away),
+ which surfaces as an ``IntegrityError`` on the FK to the now-gone row instead.
"""
@@ -372,15 +376,23 @@ def create_external_data_job_model_activity(
schema_snapshot["scheduled_full_refresh"] = True
logger.info("This sync is a scheduled full refresh. It re-imports every row of the table.")
- job = _create_job(
- team_id=inputs.team_id,
- source_id=inputs.source_id,
- schema_id=inputs.schema_id,
- pipeline_version=pipeline_version,
- billable=inputs.billable,
- schema_snapshot=schema_snapshot,
- destination_ids=destination_ids,
- )
+ try:
+ job = _create_job(
+ team_id=inputs.team_id,
+ source_id=inputs.source_id,
+ schema_id=inputs.schema_id,
+ pipeline_version=pipeline_version,
+ billable=inputs.billable,
+ schema_snapshot=schema_snapshot,
+ destination_ids=destination_ids,
+ )
+ except IntegrityError:
+ # The source or schema can still be deleted (or its team torn down, cascading to
+ # both) between the existence check above and this insert. Same race as
+ # SourceOrSchemaDeletedError, just found a step later.
+ delete_external_data_schedule(str(inputs.schema_id))
+ logger.info("Source or schema was deleted before the job could be created, deleted the sync schedule")
+ raise SourceOrSchemaDeletedError("Source or schema no longer exists - deleted temporal schedule") from None
# Persist the Running status only after the job row exists: a Running schema with no job
# behind it can never be finalized, so it would stay stuck on Running forever. With the job
# committed first, the workflow's finalizer can always resolve it and repaint the schema.
@@ -450,6 +462,9 @@ def create_external_data_job_model_activity(
# The takeover race the guard handles, not a defect — skip the generic handler's
# stack trace log, same reasoning as SourceOrSchemaDeletedError above.
raise
+ except SourceOrSchemaDeletedError:
+ # Raised (and already logged) from the IntegrityError handler around _create_job above.
+ raise
except Exception as e:
logger.exception(
f"External data job failed on create_external_data_job_model_activity for {str(inputs.source_id)} with error: {e}"
diff --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.py
index 633a1dc758d8..07f7668efba3 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
@@ -4,7 +4,7 @@ import datetime as dt
import pytest
from unittest.mock import MagicMock, patch
-from django.db import OperationalError
+from django.db import IntegrityError, OperationalError
from django.utils import timezone
from parameterized import parameterized
@@ -432,3 +432,34 @@ class TestCreateJobActivityDeletedSourceOrSchema:
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() == 0
+
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}.delete_external_data_schedule")
+ @patch(f"{MODULE}._create_job")
+ def test_integrity_error_on_insert_is_treated_as_the_same_race(
+ self,
+ mock_create_job: MagicMock,
+ mock_delete_schedule: MagicMock,
+ _mock_close_connections: MagicMock,
+ ) -> None:
+ # The row can still vanish (e.g. a team deletion cascading to its source/schema) between
+ # the existence check passing and the insert itself, surfacing as a raw IntegrityError
+ # instead of the early check catching it.
+ team = _team()
+ schema = _schema(team, None)
+ mock_create_job.side_effect = IntegrityError(
+ 'insert or update on table "posthog_externaldatajob" violates foreign key constraint'
+ )
+
+ 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))