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): fall back to per-batch retry after set write fails (#111918)

Tom Owers1587c7278c43
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index 369445ed877b..25319d2ceff8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -4082,6 +4082,50 @@ class TestProcessGroupCoalescing:
(batches[1].id, "succeeded", expected_status_attempt),
]
+ @pytest.mark.asyncio
+ async def test_a_set_whose_post_write_status_update_fails_falls_back_to_its_members(self):
+ # The set's write (process_batches) already landed; only the bookkeeping status update
+ # after it crashes (e.g. a dropped queue-DB connection). This must not bubble out of the
+ # group unhandled — it falls back to the single-batch path, same as a set that never
+ # wrote in the first place, so the already-established retry classification applies
+ # instead of an unconditional captured exception.
+ loaded: list[list[int]] = []
+
+ async def process_batches(batches, verify_ownership=None):
+ loaded.append([b.batch_index for b in batches])
+
+ process_batch = AsyncMock()
+ consumer = self._consumer(process_batches, process_batch)
+ batches = _run_batches(2)
+
+ statuses: list[_BatchStatus] = []
+ raised = False
+
+ async def record_status(conn, *, batch_id, job_state, attempt, **kwargs):
+ nonlocal raised
+ if job_state == "succeeded" and not raised:
+ raised = True
+ raise psycopg.errors.ProtocolViolation("server conn crashed?")
+ statuses.append(_BatchStatus(batch_id, job_state, attempt))
+ return True
+
+ with (
+ patch(f"{self._CONSUMER_QUEUE}.update_status_unless_failed", side_effect=record_status),
+ patch(f"{self._CONSUMER_QUEUE}.unlock_for_batches", new_callable=AsyncMock),
+ patch(f"{self._CONSUMER_QUEUE}.verify_advisory_lock", new_callable=AsyncMock, return_value=True),
+ patch.object(DeltaBatchConsumerAdapter, "should_process_batch", new_callable=AsyncMock, return_value=True),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ await consumer._process_group((1, "schema-1"), batches)
+
+ assert loaded == [[0, 1]] # the set loaded exactly once despite the later crash
+ # Every batch still reaches a terminal "succeeded" status via the single-batch fallback.
+ assert [s.job_state for s in statuses if s.batch_id == batches[0].id][-1] == "succeeded"
+ assert [s.job_state for s in statuses if s.batch_id == batches[1].id][-1] == "succeeded"
+ # A transient queue-DB blip during bookkeeping must not reach error tracking.
+ mock_capture.assert_not_called()
+
@pytest.mark.asyncio
async def test_without_a_set_loader_every_batch_is_single(self):
process_batch = AsyncMock()
diff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.py
index 2b41b969994e..420f6577900f 100644
--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py
+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py
@@ -1286,38 +1286,56 @@ class BatchConsumer:
await self._stop_heartbeat(heartbeat_task)
heartbeat_task = None
- for batch in batches:
- await self._adapter.after_batch_processed(status_conn, batch=batch)
-
- duration = time.monotonic() - start
- self._metrics.batch_processing_duration_seconds.observe(duration)
-
- await self._verify_ownership(lock_conn, head)
- for batch in batches:
- await self._adapter.update_status(
- status_conn,
- batch_id=batch.id,
- job_state=self._adapter.succeeded_state,
- attempt=attempts[batch.id],
- batch_created_at=batch.created_at,
+ try:
+ for batch in batches:
+ await self._adapter.after_batch_processed(status_conn, batch=batch)
+
+ duration = time.monotonic() - start
+ self._metrics.batch_processing_duration_seconds.observe(duration)
+
+ await self._verify_ownership(lock_conn, head)
+ for batch in batches:
+ await self._adapter.update_status(
+ status_conn,
+ batch_id=batch.id,
+ job_state=self._adapter.succeeded_state,
+ attempt=attempts[batch.id],
+ batch_created_at=batch.created_at,
+ )
+ self._metrics.batches_processed_total.labels(status="success").inc()
+ self._metrics.coalesced_sets_total.labels(outcome="success").inc()
+ self._metrics.coalesced_set_batches.observe(len(batches))
+ self._metrics.coalesced_set_runs.observe(len(run_uuids))
+ self._metrics.coalesced_set_rows.observe(row_count)
+ logger.info(
+ self._event("batch_set_processed_ok"),
+ run_uuid=head.run_uuid,
+ run_uuids=run_uuids,
+ batch_indexes=[batch.batch_index for batch in batches],
+ batch_count=len(batches),
+ row_count=row_count,
+ byte_size=byte_size,
+ is_final_batch=batches[-1].is_final_batch,
+ duration_seconds=round(duration, 3),
)
- self._metrics.batches_processed_total.labels(status="success").inc()
- self._metrics.coalesced_sets_total.labels(outcome="success").inc()
- self._metrics.coalesced_set_batches.observe(len(batches))
- self._metrics.coalesced_set_runs.observe(len(run_uuids))
- self._metrics.coalesced_set_rows.observe(row_count)
- logger.info(
- self._event("batch_set_processed_ok"),
- run_uuid=head.run_uuid,
- run_uuids=run_uuids,
- batch_indexes=[batch.batch_index for batch in batches],
- batch_count=len(batches),
- row_count=row_count,
- byte_size=byte_size,
- is_final_batch=batches[-1].is_final_batch,
- duration_seconds=round(duration, 3),
- )
- return True
+ return True
+ except OwnershipLostError:
+ raise
+ except Exception as err:
+ # The set's write already landed (process_batches returned), so only the
+ # post-write bookkeeping failed — e.g. a dropped queue-DB connection while
+ # marking a member succeeded. Falling back to the single-batch path, the same
+ # way a load failure above does, routes the error through
+ # _handle_batch_failure's retryable/transient classification instead of
+ # letting it bubble to the group handler as an unconditional capture_exception.
+ logger.warning(
+ self._event("batch_set_failed_post_processing"),
+ run_uuid=head.run_uuid,
+ run_uuids=run_uuids,
+ error=str(err),
+ error_type=type(err).__name__,
+ )
+ return await self._process_singly(batches, lock_conn, spent_attempt=True)
finally:
await self._stop_heartbeat(heartbeat_task)