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): do not take over the v3 lock from a live loader (#115400)

Tom Owersaa502b76822d
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 aa7b3d9030c4..bae3944a14cf 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
@@ -36,8 +36,9 @@ from products.warehouse_sources_queue.backend.sdk import BatchQueue
LOGGER = get_logger(__name__)
-# Hard cap on how long a terminal-workflow holder can block takeover on queue
-# activity alone — the backstop when the staleness heuristic is being fooled.
+# A live loader past this hold still keeps the lock, because taking over lets the new run's
+# batch 0 overwrite the table while the old loader is still writing to it. Past the cap the
+# skip is logged as a warning, so a schema stuck behind a long load is visible.
TAKEOVER_MAX_HOLD_SECONDS = 24 * 60 * 60
# Must outlast the healthy startup tail (SET NX → job-row commit, minutes under
@@ -178,10 +179,10 @@ def _take_over_lock_if_holder_finished(inputs: AcquireV3LockActivityInputs, toke
assumed (no workflow_id anywhere), a young holder fails closed instead.
3. Holder workflow terminal + job terminal -> take over.
4. Holder workflow terminal + job RUNNING -> consult queue DB:
- - no batches, all-terminal, no recent loader progress, or the job has
- exceeded the max hold -> fail its leftover batches, mark job FAILED,
- take over.
- - non-terminal batches with recent loader progress -> fail closed.
+ - no batches, all-terminal, or no recent loader progress -> fail its
+ leftover batches, mark job FAILED, take over.
+ - non-terminal batches with recent loader progress -> fail closed,
+ whatever the hold time.
5. Describe error / queue DB error -> fail closed.
"""
holder = get_v3_pipeline_lock_holder(inputs.team_id, str(inputs.schema_id))
@@ -376,18 +377,20 @@ def _take_over_stale_running_job(
capture_exception(e)
return False
- # Backstop for a fooled staleness heuristic: a terminal-workflow holder
- # cannot block takeover on queue activity alone past the max hold.
hold_seconds = (datetime.now(UTC) - holder_job.created_at).total_seconds()
- max_hold_exceeded = hold_seconds > TAKEOVER_MAX_HOLD_SECONDS
- if summary.has_non_terminal and not summary.is_stale and not max_hold_exceeded:
- # The loader is making progress on this run's batches - don't steal
- logger.info(
+ if summary.has_non_terminal and not summary.is_stale:
+ # The loader is making progress on this run's batches - don't steal. Failing its
+ # batches does not stop a merge already in flight, so a takeover here lets two
+ # runs write the same table.
+ max_hold_exceeded = hold_seconds > TAKEOVER_MAX_HOLD_SECONDS
+ log = logger.warning if max_hold_exceeded else logger.info
+ log(
"v3_pipeline_lock_takeover_skipped",
schema_id=str(inputs.schema_id),
holder_token=holder,
- reason="active_consumer",
+ reason="max_hold_exceeded_live_holder" if max_hold_exceeded else "active_consumer",
+ holder_job_id=str(holder_job.id),
last_status_write_age_seconds=summary.last_status_write_age_seconds,
oldest_unclaimed_age_seconds=summary.oldest_unclaimed_age_seconds,
hold_seconds=round(hold_seconds, 1),
@@ -441,7 +444,7 @@ def _take_over_stale_running_job(
"v3_pipeline_lock_taking_over",
schema_id=str(inputs.schema_id),
holder_token=holder,
- reason="max_hold_exceeded" if (max_hold_exceeded and not summary.is_stale) else "stale_running_job",
+ reason="stale_running_job",
holder_job_id=str(holder_job.id),
has_batches=summary.has_batches,
is_stale=summary.is_stale,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
index 90a28c76d84e..d5a035ba67ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
@@ -425,34 +425,41 @@ class TestTakeOverStaleRunningJob:
assert self._run() is True
mock_update.assert_called_once()
+ # A live loader keeps the lock past the max hold: a takeover lets the new run's batch 0
+ # overwrite the table while the old loader is still merging and then publishing it.
+ @pytest.mark.parametrize(
+ "is_stale,hold_hours,expect_takeover",
+ [
+ pytest.param(False, 1, False, id="live_holder_within_max_hold"),
+ pytest.param(False, 25, False, id="live_holder_past_max_hold"),
+ pytest.param(True, 1, True, id="stale_holder_within_max_hold"),
+ pytest.param(True, 25, True, id="stale_holder_past_max_hold"),
+ ],
+ )
+ @time_machine.travel("2026-01-15 12:00:00+00:00", tick=False)
@patch(f"{MODULE}._release_and_acquire", return_value=True)
@patch(f"{MODULE}.update_external_job_status")
@patch(f"{MODULE}.BatchQueue")
@patch(f"{MODULE}.psycopg.Connection")
- def test_takes_over_when_stale_batches(
+ def test_takes_over_only_a_stale_holder_with_pending_batches(
self,
mock_conn_cls: MagicMock,
mock_queue: MagicMock,
mock_update: MagicMock,
mock_release: MagicMock,
+ is_stale: bool,
+ hold_hours: int,
+ expect_takeover: bool,
) -> None:
mock_queue.get_run_activity_summary.return_value = RunActivitySummary(
- has_batches=True, has_non_terminal=True, is_stale=True
+ has_batches=True, has_non_terminal=True, is_stale=is_stale
)
- assert self._run() is True
- mock_update.assert_called_once()
- @patch(f"{MODULE}.BatchQueue")
- @patch(f"{MODULE}.psycopg.Connection")
- def test_fails_closed_when_active_consumer(
- self,
- mock_conn_cls: MagicMock,
- mock_queue: MagicMock,
- ) -> None:
- mock_queue.get_run_activity_summary.return_value = RunActivitySummary(
- has_batches=True, has_non_terminal=True, is_stale=False
- )
- assert self._run() is False
+ assert self._run(holder_created_at=datetime.now(UTC) - timedelta(hours=hold_hours)) is expect_takeover
+
+ assert mock_queue.fail_batches_for_job_sync.called is expect_takeover
+ assert mock_update.called is expect_takeover
+ assert mock_release.called is expect_takeover
@patch(f"{MODULE}.capture_exception")
@patch(f"{MODULE}.psycopg.Connection")
@@ -464,26 +471,6 @@ class TestTakeOverStaleRunningJob:
mock_conn_cls.connect.side_effect = RuntimeError("connection refused")
assert self._run() is False
- @time_machine.travel("2026-01-01T12:00:00Z", tick=False)
- @patch(f"{MODULE}._release_and_acquire", return_value=True)
- @patch(f"{MODULE}.update_external_job_status")
- @patch(f"{MODULE}.BatchQueue")
- @patch(f"{MODULE}.psycopg.Connection")
- def test_max_hold_exceeded_takes_over_despite_active_consumer(
- self,
- mock_conn_cls: MagicMock,
- mock_queue: MagicMock,
- mock_update: MagicMock,
- mock_release: MagicMock,
- ) -> None:
- # Without the max-hold backstop, a fooled staleness heuristic can block
- # takeover forever.
- mock_queue.get_run_activity_summary.return_value = RunActivitySummary(
- has_batches=True, has_non_terminal=True, is_stale=False
- )
- assert self._run(holder_created_at=datetime.now(UTC) - timedelta(hours=25)) is True
- mock_update.assert_called_once()
-
@patch(f"{MODULE}._release_and_acquire", return_value=True)
@patch(f"{MODULE}.update_external_job_status")
@patch(f"{MODULE}.BatchQueue")