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 v3 lock takeover racing the late loader (#67693)

estefania97c9545d0805
diff --git a/products/data_warehouse/backend/logic/external_data_source/jobs.py b/products/data_warehouse/backend/logic/external_data_source/jobs.py
index 2968069c897e..c16bf6b4c9c9 100644
--- a/products/data_warehouse/backend/logic/external_data_source/jobs.py
+++ b/products/data_warehouse/backend/logic/external_data_source/jobs.py
@@ -12,6 +12,7 @@ from products.data_warehouse.backend.tasks import (
)
from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
+ LOCK_TAKEOVER_LATEST_ERROR,
TERMINAL_JOB_STATUSES,
emit_data_import_app_metrics,
)
@@ -29,8 +30,16 @@ def update_external_job_status(
with transaction.atomic():
model = ExternalDataJob.objects.select_for_update().get(id=job_id, team_id=team_id)
+ # The loader may finish a run after lock takeover force-failed its job; only the
+ # exact takeover sentinel unseals Failed -> Completed — genuine failures stay absorbing.
+ is_takeover_recovery = (
+ model.status == ExternalDataJob.Status.FAILED
+ and status == ExternalDataJob.Status.COMPLETED
+ and model.latest_error == LOCK_TAKEOVER_LATEST_ERROR
+ )
+
# Terminal states are absorbing: same-status retries pass, different statuses are rejected.
- if model.status in TERMINAL_JOB_STATUSES and model.status != status:
+ if model.status in TERMINAL_JOB_STATUSES and model.status != status and not is_takeover_recovery:
logger.warning(
"dwh_job_status_transition_rejected",
job_id=job_id,
@@ -40,11 +49,20 @@ def update_external_job_status(
JOB_STATUS_TRANSITION_REJECTED.inc()
return model
+ if is_takeover_recovery:
+ logger.info(
+ "dwh_job_completed_after_lock_takeover",
+ job_id=job_id,
+ )
+
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
+ # Only stamp finished_at and emit metrics on the first terminal transition. Takeover
+ # recovery re-stamps: the Failed stamp predates the load and never emitted success metrics.
+ is_first_terminal_transition = status in TERMINAL_JOB_STATUSES and (
+ model.finished_at is None or is_takeover_recovery
+ )
update_fields = ["status", "latest_error", "updated_at"]
if is_first_terminal_transition:
model.finished_at = dt.datetime.now(dt.UTC)
diff --git a/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py b/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
index bb395df6fef9..4de36e7b03a3 100644
--- a/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
+++ b/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
@@ -7,6 +7,7 @@ from posthog.models import Organization, Team
from products.data_warehouse.backend.logic.external_data_source.jobs import update_external_job_status
from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.metrics import LOCK_TAKEOVER_LATEST_ERROR
pytestmark = [
pytest.mark.django_db,
@@ -265,6 +266,40 @@ class TestUpdateExternalJobStatus:
expected_error = "first error" if first_status == ExternalDataJob.Status.FAILED else None
assert db_job.latest_error == expected_error
+ def test_completed_after_lock_takeover_failure_is_allowed(self):
+ # A job force-failed by lock takeover while the loader was still working its run
+ # must accept the loader's completion instead of rejecting Failed -> Completed.
+ team, _source, schema, job = _create_org_team_source_schema_job()
+
+ with patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"
+ ) as mock_emit:
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.FAILED,
+ logger=MagicMock(),
+ latest_error=LOCK_TAKEOVER_LATEST_ERROR,
+ )
+
+ updated = update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.COMPLETED,
+ logger=MagicMock(),
+ latest_error=None,
+ )
+
+ assert updated.status == ExternalDataJob.Status.COMPLETED
+ assert updated.latest_error is None
+ assert updated.finished_at is not None
+ # Success metrics must be emitted even though the takeover already stamped finished_at.
+ assert mock_emit.call_count == 2
+ assert mock_emit.call_args.args[0].status == ExternalDataJob.Status.COMPLETED
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.COMPLETED
+ assert schema.latest_error is None
+
def test_rejected_transition_does_not_overwrite_schema_status(self):
team, _source, schema, job = _create_org_team_source_schema_job()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
index 4df51877371f..b26086493d96 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
@@ -29,6 +29,10 @@ _TERMINAL_STATUS_TO_METRIC: dict[str, tuple[str, str]] = {
# emission on the first terminal transition.
TERMINAL_JOB_STATUSES: frozenset[str] = frozenset(_TERMINAL_STATUS_TO_METRIC)
+# latest_error written when lock takeover force-fails a stuck-RUNNING job; sentinel that
+# lets update_external_job_status permit Failed -> Completed for takeover-failed jobs only.
+LOCK_TAKEOVER_LATEST_ERROR = "Lock takeover: workflow terminated but job was stuck in RUNNING"
+
def get_data_import_finished_metric(source_type: str | None, status: str) -> MetricCounter:
source_type = source_type or "unknown"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
index ab9f4ca2ecf2..318d121c71c6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -42,6 +42,10 @@ LEASE_TTL_SECONDS = 300
# gone by the time this matters.
PARTITION_PRUNING_INTERVAL = "14 days"
+# Quiet time (no batch inserts or status writes) before lock takeover treats a run as
+# abandoned. Must exceed worst-case loader backlog latency — an unclaimed backlog is still live.
+TAKEOVER_STALE_THRESHOLD_SECONDS = 6 * 60 * 60
+
def pending_batch_select_columns(status_alias: str) -> str:
return f"""
@@ -271,6 +275,10 @@ class BatchQueue:
group is being processed by its lease holder). This keeps a schema's
other queued runs from consuming the ``LIMIT`` window ahead of the lease
claim and starving other schemas' claimable work.
+
+ Per-team fairness: candidates are interleaved round-robin across teams so one
+ team's deep backlog cannot monopolize the ``LIMIT`` window; within a team,
+ oldest-first order (and so per-run ``batch_index`` ordering) is preserved.
"""
async with conn.cursor(row_factory=dict_row) as cur:
await cur.execute(
@@ -324,7 +332,12 @@ class BatchQueue:
AND b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND s_busy.job_state = 'executing'
)
- ORDER BY b.created_at ASC, b.batch_index ASC
+ ORDER BY
+ row_number() OVER (
+ PARTITION BY b.team_id ORDER BY b.created_at ASC, b.batch_index ASC
+ ) ASC,
+ b.created_at ASC,
+ b.batch_index ASC
LIMIT %(limit)s
),
candidate_groups AS (
@@ -624,23 +637,23 @@ class BatchQueue:
) -> RunActivitySummary:
"""Check the queue DB for batch activity belonging to a holder's run.
- Returns a summary indicating whether any non-terminal batches exist and
- the age of the most recent status update. Used by the lock takeover
- decision matrix to distinguish genuinely stale RUNNING jobs from ones
- with active consumer processing.
+ Used by the lock takeover decision matrix to distinguish genuinely stale
+ RUNNING jobs from ones the loader still has work for. Unclaimed batches
+ (no status row yet — hence the LEFT JOIN) count as non-terminal, and both
+ batch inserts and status writes count as activity.
"""
- STALE_THRESHOLD_SECONDS = 30 * 60 # 30 minutes
-
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
f"""
SELECT
+ COUNT(*) AS batch_count,
COUNT(*) FILTER (
- WHERE s.job_state NOT IN ('succeeded', 'failed')
+ WHERE s.batch_id IS NULL
+ OR s.job_state NOT IN ('succeeded', 'failed')
) AS non_terminal_count,
- MAX(s.created_at) AS latest_status_at
+ GREATEST(MAX(s.created_at), MAX(b.created_at)) AS latest_activity_at
FROM {BATCH_TABLE} b
- JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND b.job_id = %(job_id)s
@@ -650,15 +663,15 @@ class BatchQueue:
)
row = cur.fetchone()
- if row is None or row["latest_status_at"] is None:
+ if row is None or row["batch_count"] == 0 or row["latest_activity_at"] is None:
return RunActivitySummary(has_batches=False, has_non_terminal=False, is_stale=True)
non_terminal_count: int = row["non_terminal_count"]
- latest_status_at: datetime = row["latest_status_at"]
- age_seconds = (datetime.now(latest_status_at.tzinfo) - latest_status_at).total_seconds()
+ latest_activity_at: datetime = row["latest_activity_at"]
+ age_seconds = (datetime.now(latest_activity_at.tzinfo) - latest_activity_at).total_seconds()
return RunActivitySummary(
has_batches=True,
has_non_terminal=non_terminal_count > 0,
- is_stale=age_seconds > STALE_THRESHOLD_SECONDS,
+ is_stale=age_seconds > TAKEOVER_STALE_THRESHOLD_SECONDS,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
index ebe3e42c8f8e..784eb2ef226b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
@@ -154,6 +154,12 @@ async def conn_b(_db_url: str):
yield c
+def sync_conn(_db_url: str):
+ with psycopg.Connection.connect(_db_url, autocommit=True) as c:
+ yield c
+
+
@pytest.mark.django_db(transaction=True)
class TestBatchQueueInsert:
@pytest.mark.asyncio
@@ -249,6 +255,20 @@ class TestBatchQueueGetUnprocessed:
assert [b.schema_id for b in batches] == ["B"]
await _release(conn, batches=batches)
+ @pytest.mark.asyncio
+ async def test_heavy_team_does_not_monopolize_poll_window(self, conn):
+ # One team's deep, older backlog must not fill the whole LIMIT window under
+ # global FIFO — round-robin interleaving must still admit another team's newer batch.
+ for i in range(5):
+ await _insert_batch(conn, team_id=1, schema_id="heavy", run_uuid="heavy-run", batch_index=i)
+ await _insert_batch(conn, team_id=2, schema_id="light", run_uuid="light-run", batch_index=0)
+ await conn.execute(f"UPDATE {BATCH_TABLE} SET created_at = created_at - interval '1 hour' WHERE team_id = 1")
+
+ batches = await _claim(conn, limit=3)
+
+ assert {b.team_id for b in batches} == {1, 2}
+ await _release(conn, batches=batches)
+
@pytest.mark.asyncio
async def test_in_flight_gating_clears_after_terminal_status(self, conn):
# Once the executing batch is superseded by a terminal status, the schema's
@@ -627,3 +647,65 @@ class TestPendingBatchToExportSignal:
assert signal["data_folder"] == "/tmp/data"
assert signal["primary_keys"] == ["id"]
assert signal["cdc_write_mode"] == "upsert"
+
+
[email protected]_db(transaction=True)
+class TestGetRunActivitySummary:
+ WF_RUN_ID = "wf-run-1"
+
+ def _summary(self, sync_conn: psycopg.Connection[Any]):
+ return BatchQueue.get_run_activity_summary(sync_conn, job_id="job-1", workflow_run_id=self.WF_RUN_ID)
+
+ @pytest.mark.parametrize("age_hours,expect_stale", [(0, False), (7, True)])
+ @pytest.mark.asyncio
+ async def test_unclaimed_batches_are_non_terminal_and_stale_only_after_grace(
+ self, conn, sync_conn, age_hours, expect_stale
+ ):
+ # Unclaimed batches (no status rows yet) must read as live backlog, not batch-less;
+ # only after the grace window with zero activity does the run become stealable.
+ bid = await _insert_batch(conn, metadata={"workflow_run_id": self.WF_RUN_ID})
+ await conn.execute(
+ f"UPDATE {BATCH_TABLE} SET created_at = now() - make_interval(hours => %s) WHERE id = %s",
+ (age_hours, bid),
+ )
+
+ summary = self._summary(sync_conn)
+
+ assert summary.has_batches is True
+ assert summary.has_non_terminal is True
+ assert summary.is_stale is expect_stale
+
+ @pytest.mark.asyncio
+ async def test_partially_loaded_run_counts_unclaimed_backlog(self, conn, sync_conn):
+ # Some batches succeeded, the rest unclaimed: mid-load, not all-terminal.
+ done = await _insert_batch(conn, batch_index=0, metadata={"workflow_run_id": self.WF_RUN_ID})
+ await BatchQueue.update_status(conn, batch_id=done, job_state="succeeded", attempt=1)
+ await _insert_batch(conn, batch_index=1, metadata={"workflow_run_id": self.WF_RUN_ID})
+
+ summary = self._summary(sync_conn)
+
+ assert summary.has_non_terminal is True
+ assert summary.is_stale is False
+
+ @pytest.mark.asyncio
+ async def test_all_terminal_batches_report_no_non_terminal(self, conn, sync_conn):
+ # Every batch terminal but the job still RUNNING (final batch never
+ # enqueued) is genuinely abandoned and must remain stealable.
+ for i in range(2):
+ bid = await _insert_batch(conn, batch_index=i, metadata={"workflow_run_id": self.WF_RUN_ID})
+ await BatchQueue.update_status(conn, batch_id=bid, job_state="succeeded", attempt=1)
+
+ summary = self._summary(sync_conn)
+
+ assert summary.has_batches is True
+ assert summary.has_non_terminal is False
+
+ @pytest.mark.asyncio
+ async def test_other_runs_batches_do_not_count(self, conn, sync_conn):
+ await _insert_batch(conn, metadata={"workflow_run_id": "other-wf-run"})
+
+ summary = self._summary(sync_conn)
+
+ assert summary.has_batches is False
+ assert summary.has_non_terminal is False
+ assert summary.is_stale is True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
index 7531f13009ff..cbdfd666eab8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
@@ -19,7 +19,10 @@ from posthog.temporal.common.logger import get_logger
from products.data_warehouse.backend.facade.api import update_external_job_status
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
-from products.warehouse_sources.backend.temporal.data_imports.metrics import TERMINAL_JOB_STATUSES
+from products.warehouse_sources.backend.temporal.data_imports.metrics import (
+ LOCK_TAKEOVER_LATEST_ERROR,
+ TERMINAL_JOB_STATUSES,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BatchQueue,
)
@@ -255,7 +258,7 @@ def _take_over_stale_running_job(
team_id=inputs.team_id,
status=ExternalDataJob.Status.FAILED,
logger=takeover_logger,
- latest_error="Lock takeover: workflow terminated but job was stuck in RUNNING",
+ latest_error=LOCK_TAKEOVER_LATEST_ERROR,
)
except Exception as e:
logger.warning(