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-warehouse): stop a timed-out job creation from leaving a running job row (#114623)

Tom Owers373a3be4ea17
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.py
index 82572aa16f9e..b30cbc9dc586 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
@@ -1,4 +1,5 @@
import uuid
+import dataclasses
from concurrent.futures import ThreadPoolExecutor
from typing import Optional
@@ -71,6 +72,13 @@ def _create_schema(schema_name: str, source: ExternalDataSource, team: Team, tab
)
+def _run_create_job_activity(activity_environment, inputs: CreateExternalDataJobModelActivityInputs):
+ # The default test activity info has a one second start-to-close timeout counted from import time,
+ # which the activity's deadline check would see as already passed.
+ activity_environment.info = dataclasses.replace(activity_environment.info, start_to_close_timeout=None)
+ return activity_environment.run(create_external_data_job_model_activity, inputs)
+
+
@sync_to_async
def _create_external_data_job(
external_data_source_id: uuid.UUID,
@@ -113,7 +121,7 @@ def test_create_external_job_activity(activity_environment, team, **kwargs):
team_id=team.id, source_id=new_source.pk, schema_id=test_1_schema.id, billable=True
)
- result = activity_environment.run(create_external_data_job_model_activity, inputs)
+ result = _run_create_job_activity(activity_environment, inputs)
runs = ExternalDataJob.objects.filter(id=result.job_id)
assert runs.exists()
@@ -140,7 +148,7 @@ def test_create_external_job_activity_schemas_exist(activity_environment, team,
team_id=team.id, source_id=new_source.pk, schema_id=schema.id, billable=True
)
- result = activity_environment.run(create_external_data_job_model_activity, inputs)
+ result = _run_create_job_activity(activity_environment, inputs)
runs = ExternalDataJob.objects.filter(id=result.job_id)
assert runs.exists()
@@ -184,7 +192,7 @@ def test_create_external_job_activity_emit_signals_respects_ai_consent(
inputs = CreateExternalDataJobModelActivityInputs(
team_id=team.id, source_id=new_source.pk, schema_id=schema.id, billable=True
)
- result = activity_environment.run(create_external_data_job_model_activity, inputs)
+ result = _run_create_job_activity(activity_environment, inputs)
assert result.emit_signals_enabled is expected
@@ -213,7 +221,7 @@ def test_create_external_job_activity_enrichment_gates_on_consent(activity_envir
inputs = CreateExternalDataJobModelActivityInputs(
team_id=team.id, source_id=new_source.pk, schema_id=schema.id, billable=True
)
- result = activity_environment.run(create_external_data_job_model_activity, inputs)
+ result = _run_create_job_activity(activity_environment, inputs)
assert result.enrichment_needed is expected
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 684098d58fe1..aaf7e0f6f953 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
@@ -82,6 +82,27 @@ class V3PipelineLockLostError(NonReportableError):
"""
+class JobCreationTimedOutError(NonReportableError):
+ """The workflow stopped waiting for this activity before it created the job row.
+
+ The activity is a sync function. Temporal times it out on the server and the worker does not
+ stop its thread, so a late start still runs to the end. The workflow has already finalized
+ the run by then, so a row created now would stay Running with no run to close it.
+ """
+
+
+JOB_CREATION_TIMED_OUT_MESSAGE = (
+ "This run did not start in time, so it was closed. The next scheduled run syncs the data."
+)
+
+
+def _start_to_close_deadline_passed() -> bool:
+ info = activity.info()
+ if info.start_to_close_timeout is None:
+ return False
+ return dt.datetime.now(dt.UTC) >= info.started_time + info.start_to_close_timeout
+
+
class V2PipelineRemovedError(NonReportableError):
"""A workflow history recorded before every run moved to V3 asked for a V2 job.
@@ -190,6 +211,8 @@ def _create_job(
# A deadlock aborts the INSERT without creating a row, so retrying from scratch is safe. This
# activity has no Temporal-level retry (see external_data_job.py), because a retry after job
# creation succeeds would create a duplicate job — retrying just the INSERT avoids that.
+ if _start_to_close_deadline_passed():
+ raise JobCreationTimedOutError("The activity timed out before it created the job")
return ExternalDataJob.objects.create(
team_id=team_id,
pipeline_id=source_id,
@@ -404,6 +427,16 @@ def create_external_data_job_model_activity(
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
+ # The deadline can pass between the check before the insert and the insert itself. Close the
+ # new row here, because the workflow has already finalized this run and nothing else will.
+ if _start_to_close_deadline_passed():
+ ExternalDataJob.objects.filter(id=job.id, status=ExternalDataJob.Status.RUNNING).update(
+ status=ExternalDataJob.Status.FAILED,
+ latest_error=JOB_CREATION_TIMED_OUT_MESSAGE,
+ finished_at=timezone.now(),
+ updated_at=timezone.now(),
+ )
+ raise JobCreationTimedOutError("The activity timed out while it created the job")
# 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.
@@ -492,6 +525,9 @@ def create_external_data_job_model_activity(
except NonRetryableException:
# Already classified and logged where it was raised.
raise
+ except JobCreationTimedOutError:
+ logger.warning("Job creation started after the activity timeout, no job is left running")
+ raise
except V3PipelineLockLostError:
# The takeover race the guard handles, not a defect — skip the generic handler's
# stack trace log, same reasoning as SourceOrSchemaDeletedError above.
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 17d8cdd947cc..834d1773f966 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
@@ -28,13 +28,16 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.enabl
)
from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
+ JOB_CREATION_TIMED_OUT_MESSAGE,
CreateExternalDataJobModelActivityInputs,
+ JobCreationTimedOutError,
SourceOrSchemaDeletedError,
V2PipelineRemovedError,
V3PipelineLockLostError,
_build_schema_snapshot,
_create_job,
_enrichment_pending,
+ _start_to_close_deadline_passed,
_statistics_stale,
_verify_v3_lock_still_held,
create_external_data_job_model_activity,
@@ -229,6 +232,7 @@ class TestCreateJob:
) -> None:
mock_activity.info.return_value.workflow_id = "wf-1"
mock_activity.info.return_value.workflow_run_id = "run-1"
+ mock_activity.info.return_value.start_to_close_timeout = None
team = _team()
schema = _schema(team, None)
@@ -258,6 +262,88 @@ class TestCreateJob:
mock_sleep.assert_called_once()
+class TestStartToCloseDeadline:
+ @parameterized.expand(
+ [
+ ("no_timeout", dt.timedelta(seconds=500), None, False),
+ ("inside_the_timeout", dt.timedelta(seconds=10), dt.timedelta(minutes=1), False),
+ ("past_the_timeout", dt.timedelta(seconds=75), dt.timedelta(minutes=1), True),
+ ]
+ )
+ @patch(f"{MODULE}.activity")
+ def test_deadline(
+ self,
+ _name: str,
+ started_ago: dt.timedelta,
+ timeout: dt.timedelta | None,
+ expected: bool,
+ mock_activity: MagicMock,
+ ) -> None:
+ mock_activity.info.return_value.started_time = dt.datetime.now(dt.UTC) - started_ago
+ mock_activity.info.return_value.start_to_close_timeout = timeout
+
+ assert _start_to_close_deadline_passed() is expected
+
+
+class TestCreateJobActivityAfterTimeout:
+ # The server times the activity out and the worker still runs its thread. The workflow has
+ # finalized the run by then, so a Running row made now would never be closed.
+ def _inputs(self, schema: ExternalDataSchema) -> CreateExternalDataJobModelActivityInputs:
+ return CreateExternalDataJobModelActivityInputs(
+ team_id=schema.team_id, schema_id=schema.id, source_id=schema.source_id, billable=True
+ )
+
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}._verify_v3_lock_still_held")
+ @patch(f"{MODULE}.activity")
+ def test_a_late_start_creates_no_job_and_leaves_the_schema_alone(
+ self, mock_activity: MagicMock, _mock_verify_lock: MagicMock, _mock_close_connections: MagicMock
+ ) -> None:
+ mock_activity.info.return_value.workflow_id = "wf-1"
+ mock_activity.info.return_value.workflow_run_id = "run-1"
+ mock_activity.info.return_value.started_time = dt.datetime.now(dt.UTC) - dt.timedelta(minutes=5)
+ mock_activity.info.return_value.start_to_close_timeout = dt.timedelta(minutes=1)
+ schema = _schema(_team(), None)
+ schema.status = ExternalDataSchema.Status.COMPLETED
+ schema.save()
+
+ with pytest.raises(JobCreationTimedOutError) as exc_info:
+ create_external_data_job_model_activity(self._inputs(schema))
+
+ assert is_expected_activity_failure(exc_info.value)
+ assert not ExternalDataJob.objects.filter(schema_id=schema.id).exists()
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.COMPLETED
+
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}._verify_v3_lock_still_held")
+ @patch(f"{MODULE}._start_to_close_deadline_passed", side_effect=[False, True])
+ @patch(f"{MODULE}.activity")
+ def test_a_timeout_during_the_insert_closes_the_new_job(
+ self,
+ mock_activity: MagicMock,
+ _mock_deadline: MagicMock,
+ _mock_verify_lock: MagicMock,
+ _mock_close_connections: MagicMock,
+ ) -> None:
+ mock_activity.info.return_value.workflow_id = "wf-1"
+ mock_activity.info.return_value.workflow_run_id = "run-1"
+ schema = _schema(_team(), None)
+ schema.status = ExternalDataSchema.Status.COMPLETED
+ schema.save()
+
+ with pytest.raises(JobCreationTimedOutError):
+ create_external_data_job_model_activity(self._inputs(schema))
+
+ job = ExternalDataJob.objects.get(schema_id=schema.id)
+ assert job.status == ExternalDataJob.Status.FAILED
+ assert job.latest_error == JOB_CREATION_TIMED_OUT_MESSAGE
+ assert job.finished_at is not None
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.COMPLETED
+
+
@pytest.mark.django_db
class TestCreateJobActivityStatusOrdering:
# The Running status must only be persisted once the job row exists: a Running schema with no
@@ -310,6 +396,7 @@ class TestCreateJobActivityStatusOrdering:
) -> None:
mock_activity.info.return_value.workflow_id = "wf-1"
mock_activity.info.return_value.workflow_run_id = "run-1"
+ mock_activity.info.return_value.start_to_close_timeout = None
team = _team()
schema = _schema(team, None)
schema.status = ExternalDataSchema.Status.FAILED
@@ -333,6 +420,7 @@ class TestCreateJobActivityStatusOrdering:
) -> None:
mock_activity.info.return_value.workflow_id = "wf-1"
mock_activity.info.return_value.workflow_run_id = "run-1"
+ mock_activity.info.return_value.start_to_close_timeout = None
team = _team()
schema = _schema(team, None)
schema.sync_type_config = {
@@ -357,6 +445,7 @@ class TestCreateJobActivityStatusOrdering:
) -> None:
mock_activity.info.return_value.workflow_id = "wf-1"
mock_activity.info.return_value.workflow_run_id = "run-1"
+ mock_activity.info.return_value.start_to_close_timeout = None
team = _team()
schema = _schema(team, None)
destination = ExternalDataDestination.objects.for_team(team.id).create(
@@ -433,6 +522,7 @@ class TestCreateJobActivityScheduledFullRefresh:
) -> None:
mock_activity.info.return_value.workflow_id = "wf-1"
mock_activity.info.return_value.workflow_run_id = "run-1"
+ mock_activity.info.return_value.start_to_close_timeout = None
team = _team()
schema = _schema(team, None)
schema.sync_type = ExternalDataSchema.SyncType.INCREMENTAL
@@ -564,6 +654,7 @@ class TestCreateJobActivityPrepareRunOutputs:
) -> None:
mock_activity.info.return_value.workflow_id = "wf-1"
mock_activity.info.return_value.workflow_run_id = "run-1"
+ mock_activity.info.return_value.start_to_close_timeout = None
team = _team()
schema = _schema(team, None)
# Past the free window for a new source, so only the quota decides.
@@ -603,6 +694,7 @@ class TestCreateJobActivityPrepareRunOutputs:
) -> None:
mock_activity.info.return_value.workflow_id = "wf-1"
mock_activity.info.return_value.workflow_run_id = "run-1"
+ mock_activity.info.return_value.start_to_close_timeout = None
team = _team()
source = ExternalDataSource.objects.create(
source_id="src", connection_id="conn", team=team, source_type=source_type