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(ws): make job terminal statuses absorbing to prevent race overwrites (#65110)

estefaniacf63e83ca15c
diff --git a/products/data_warehouse/backend/external_data_source/jobs.py b/products/data_warehouse/backend/external_data_source/jobs.py
index 384a00cf307d..a38241d5dcf6 100644
--- a/products/data_warehouse/backend/external_data_source/jobs.py
+++ b/products/data_warehouse/backend/external_data_source/jobs.py
@@ -1,5 +1,8 @@
import datetime as dt
+from django.db import transaction
+
+from prometheus_client import Counter
from structlog.types import FilteringBoundLogger
from posthog.temporal.data_imports.metrics import TERMINAL_JOB_STATUSES, emit_data_import_app_metrics
@@ -12,41 +15,55 @@ from products.data_warehouse.backend.tasks import (
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+JOB_STATUS_TRANSITION_REJECTED = Counter(
+ "dwh_job_status_transition_rejected",
+ "Job status transition rejected because the job was already in a different terminal state",
+)
+
def update_external_job_status(
job_id: str, team_id: int, status: ExternalDataJob.Status, logger: FilteringBoundLogger, latest_error: str | None
) -> ExternalDataJob:
- model = ExternalDataJob.objects.get(id=job_id, team_id=team_id)
- model.status = status
- model.latest_error = latest_error
-
- # Both the finished_at stamp and the metric emission must only fire on the
- # first terminal transition — a retried Temporal activity or redelivered
- # Kafka message can land here with the job already in a terminal state, and
- # re-emitting would inflate the counters.
- is_first_terminal_transition = status in TERMINAL_JOB_STATUSES and model.finished_at is None
- update_fields = ["status", "latest_error", "updated_at"]
- if is_first_terminal_transition:
- model.finished_at = dt.datetime.now(dt.UTC)
- update_fields.append("finished_at")
-
- # Scope the save to the fields we mutated so a concurrent F-update from
- # `update_job_row_count` (V3 activity) isn't clobbered by writing back the
- # in-memory `rows_synced` we read at the top of this function.
- model.save(update_fields=update_fields)
-
- if status == ExternalDataJob.Status.FAILED:
- schema_status: ExternalDataSchema.Status = ExternalDataSchema.Status.FAILED
- else:
- schema_status = status # type: ignore
-
- if model.schema_id is None:
- raise ValueError(f"External data job {job_id} is not attached to a schema")
-
- schema = ExternalDataSchema.objects.get(id=model.schema_id, team_id=team_id)
- schema.status = schema_status
- schema.latest_error = latest_error
- schema.save()
+ is_first_terminal_transition = False
+ with transaction.atomic():
+ model = ExternalDataJob.objects.select_for_update().get(id=job_id, team_id=team_id)
+
+ # Terminal states are absorbing: same-status retries pass, different statuses are rejected.
+ if model.status in TERMINAL_JOB_STATUSES and model.status != status:
+ logger.warning(
+ "dwh_job_status_transition_rejected",
+ job_id=job_id,
+ current_status=model.status,
+ requested_status=status,
+ )
+ JOB_STATUS_TRANSITION_REJECTED.inc()
+ return model
+
+ model.status = status
+ model.latest_error = latest_error
+
+ # Only stamp finished_at and emit metrics on the first terminal transition.
+ is_first_terminal_transition = status in TERMINAL_JOB_STATUSES and model.finished_at is None
+ update_fields = ["status", "latest_error", "updated_at"]
+ if is_first_terminal_transition:
+ model.finished_at = dt.datetime.now(dt.UTC)
+ update_fields.append("finished_at")
+
+ # Scoped save so concurrent F-updates to rows_synced aren't clobbered.
+ model.save(update_fields=update_fields)
+
+ if status == ExternalDataJob.Status.FAILED:
+ schema_status: ExternalDataSchema.Status = ExternalDataSchema.Status.FAILED
+ else:
+ schema_status = status # type: ignore
+
+ if model.schema_id is None:
+ raise ValueError(f"External data job {job_id} is not attached to a schema")
+
+ schema = ExternalDataSchema.objects.select_for_update().get(id=model.schema_id, team_id=team_id)
+ schema.status = schema_status
+ schema.latest_error = latest_error
+ schema.save(update_fields=["status", "latest_error", "updated_at"])
model.refresh_from_db()
diff --git a/products/data_warehouse/backend/external_data_source/test/test_jobs.py b/products/data_warehouse/backend/external_data_source/test/test_jobs.py
index a13db4f00209..1a826504a4a3 100644
--- a/products/data_warehouse/backend/external_data_source/test/test_jobs.py
+++ b/products/data_warehouse/backend/external_data_source/test/test_jobs.py
@@ -233,3 +233,63 @@ class TestUpdateExternalJobStatus:
assert updated.status == ExternalDataJob.Status.FAILED
assert updated.finished_at is not None
+
+ @pytest.mark.parametrize(
+ "first_status,rejected_status",
+ [
+ (ExternalDataJob.Status.COMPLETED, ExternalDataJob.Status.FAILED),
+ (ExternalDataJob.Status.FAILED, ExternalDataJob.Status.COMPLETED),
+ ],
+ )
+ def test_terminal_to_different_terminal_is_rejected(self, first_status, rejected_status):
+ team, _source, _schema, job = _create_org_team_source_schema_job()
+
+ with patch("products.data_warehouse.backend.external_data_source.jobs.emit_data_import_app_metrics"):
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=first_status,
+ logger=MagicMock(),
+ latest_error="first error" if first_status == ExternalDataJob.Status.FAILED else None,
+ )
+
+ result = update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=rejected_status,
+ logger=MagicMock(),
+ latest_error="late error",
+ )
+
+ assert result.status == first_status
+ db_job = ExternalDataJob.objects.get(id=job.id)
+ assert db_job.status == first_status
+ expected_error = "first error" if first_status == ExternalDataJob.Status.FAILED else None
+ assert db_job.latest_error == expected_error
+
+ def test_rejected_transition_does_not_overwrite_schema_status(self):
+ team, _source, schema, job = _create_org_team_source_schema_job()
+
+ with patch("products.data_warehouse.backend.external_data_source.jobs.emit_data_import_app_metrics"):
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.COMPLETED,
+ logger=MagicMock(),
+ latest_error=None,
+ )
+
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.COMPLETED
+
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.FAILED,
+ logger=MagicMock(),
+ latest_error="late failure",
+ )
+
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.COMPLETED
+ assert schema.latest_error is None