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): sweep v3 queue batches at job finalize (#74227)

estefaniab5ebc75b2083
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 bd3f180a01a0..19a62d67b951 100644
--- a/products/data_warehouse/backend/logic/external_data_source/jobs.py
+++ b/products/data_warehouse/backend/logic/external_data_source/jobs.py
@@ -1,10 +1,13 @@
import datetime as dt
+from functools import partial
from django.db import transaction
from prometheus_client import Counter
from structlog.types import FilteringBoundLogger
+from posthog.exceptions_capture import capture_exception
+
from products.data_warehouse.backend.tasks.tasks import schedule_external_data_failure_digest
from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema
from products.warehouse_sources.backend.facade.pipelines import (
@@ -18,6 +21,16 @@ JOB_STATUS_TRANSITION_REJECTED = Counter(
"Job status transition rejected because the job was already in a different terminal state",
)
+FINALIZE_QUEUE_BATCHES_SWEPT = Counter(
+ "dwh_finalize_queue_batches_swept",
+ "Queue batches failed because their v3 job reached a terminal state before the queue drained",
+)
+
+FINALIZE_QUEUE_SWEEP_ERRORS = Counter(
+ "dwh_finalize_queue_sweep_errors",
+ "Errors swallowed while sweeping queue batches at job finalize",
+)
+
def update_external_job_status(
job_id: str, team_id: int, status: ExternalDataJob.Status, logger: FilteringBoundLogger, latest_error: str | None
@@ -93,6 +106,21 @@ def update_external_job_status(
schema.latest_error = latest_error
schema.save(update_fields=["status", "latest_error", "updated_at"])
+ # Every risky terminal write (any non-Completed terminal, plus the takeover-recovery
+ # Completed flip) can leave still-claimable batches in the v3 queue; a straggler loaded
+ # later can stale-overwrite newer data or flip this job's status. A normal v3 completion
+ # has drained the queue by construction, so the common completion path stays queue-free.
+ # on_commit: the queue is a separate Postgres; never call it holding these row locks.
+ should_sweep_queue = (
+ model.pipeline_version == ExternalDataJob.PipelineVersion.V3
+ and status in TERMINAL_JOB_STATUSES
+ and (status != ExternalDataJob.Status.COMPLETED or is_takeover_recovery)
+ )
+ if should_sweep_queue:
+ transaction.on_commit(
+ partial(_sweep_v3_queue_batches_swallowing_errors, job_id=job_id, status=status, logger=logger)
+ )
+
model.refresh_from_db()
if is_first_terminal_transition:
@@ -106,3 +134,46 @@ def update_external_job_status(
logger.exception("Failed to schedule external data failure digest")
return model
+
+
+def _sweep_v3_queue_batches_swallowing_errors(
+ *, job_id: str, status: ExternalDataJob.Status, logger: FilteringBoundLogger
+) -> None:
+ # A queue-DB error must never surface into the caller that just committed the status write.
+ # The stale-stranded reconcile sweep on the loader retries what this misses.
+ try:
+ _sweep_v3_queue_batches(job_id=job_id, status=status, logger=logger)
+ except Exception as e:
+ FINALIZE_QUEUE_SWEEP_ERRORS.inc()
+ logger.exception("dwh_finalize_queue_sweep_failed", job_id=job_id)
+ capture_exception(e)
+
+
+def _sweep_v3_queue_batches(*, job_id: str, status: ExternalDataJob.Status, logger: FilteringBoundLogger) -> None:
+ """Fail any still-non-terminal queue batches of a v3 job that just went terminal."""
+ # Deferred: the queue package imports back through this module (see postgres_queue.consumer),
+ # so a top-level import would cycle.
+ import psycopg
+
+ from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+
+ from products.warehouse_sources.backend.facade.pipelines import BatchQueue
+
+ conn = psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True)
+ try:
+ swept = BatchQueue.fail_batches_for_job_sync(
+ conn,
+ job_id=job_id,
+ reason=f"job finalized as {status} before its queue drained",
+ )
+ finally:
+ conn.close()
+
+ if swept:
+ FINALIZE_QUEUE_BATCHES_SWEPT.inc(swept)
+ logger.warning(
+ "dwh_finalize_swept_queue_batches",
+ job_id=job_id,
+ status=status,
+ batch_count=swept,
+ )
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 a268d8f29627..9891d91d7150 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
@@ -14,7 +14,9 @@ pytestmark = [
]
-def _create_org_team_source_schema_job() -> tuple[Team, ExternalDataSource, ExternalDataSchema, ExternalDataJob]:
+def _create_org_team_source_schema_job(
+ pipeline_version: ExternalDataJob.PipelineVersion | None = None,
+) -> tuple[Team, ExternalDataSource, ExternalDataSchema, ExternalDataJob]:
org = Organization.objects.create(name="Test Org")
team = Team.objects.create(organization=org, name="Test Team")
source = ExternalDataSource.objects.create(
@@ -32,6 +34,7 @@ def _create_org_team_source_schema_job() -> tuple[Team, ExternalDataSource, Exte
schema=schema,
status=ExternalDataJob.Status.RUNNING,
rows_synced=100,
+ pipeline_version=pipeline_version,
)
return team, source, schema, job
@@ -355,3 +358,147 @@ class TestUpdateExternalJobStatus:
schema.refresh_from_db()
assert schema.status == ExternalDataSchema.Status.COMPLETED
assert schema.latest_error is None
+
+
+class TestFinalizeQueueSweep:
+ @pytest.mark.parametrize(
+ "status",
+ [
+ ExternalDataJob.Status.FAILED,
+ ExternalDataJob.Status.BILLING_LIMIT_REACHED,
+ ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW,
+ ],
+ )
+ def test_v3_risky_terminal_sweeps_queue_batches(self, status, django_capture_on_commit_callbacks):
+ # Any non-Completed terminal can leave enqueued batches behind; the sweep must fire
+ # after commit or the batches stay claimable until the retention prune.
+ team, _source, _schema, job = _create_org_team_source_schema_job(
+ pipeline_version=ExternalDataJob.PipelineVersion.V3
+ )
+
+ with (
+ patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"),
+ patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs.schedule_external_data_failure_digest"
+ ),
+ patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs._sweep_v3_queue_batches"
+ ) as mock_sweep,
+ django_capture_on_commit_callbacks(execute=True),
+ ):
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=status,
+ logger=MagicMock(),
+ latest_error="boom",
+ )
+
+ mock_sweep.assert_called_once()
+ assert mock_sweep.call_args.kwargs["job_id"] == str(job.id)
+
+ @pytest.mark.parametrize(
+ "pipeline_version,status",
+ [
+ # A normally-completed v3 run has drained its queue by construction; the fleet's
+ # hottest status write must not gain a cross-DB call.
+ (ExternalDataJob.PipelineVersion.V3, ExternalDataJob.Status.COMPLETED),
+ # v1/v2 have no batch queue at all.
+ (ExternalDataJob.PipelineVersion.V2, ExternalDataJob.Status.FAILED),
+ (ExternalDataJob.PipelineVersion.V1, ExternalDataJob.Status.FAILED),
+ (None, ExternalDataJob.Status.FAILED),
+ ],
+ )
+ def test_no_queue_sweep_for_normal_completion_or_non_v3(
+ self, pipeline_version, status, django_capture_on_commit_callbacks
+ ):
+ team, _source, _schema, job = _create_org_team_source_schema_job(pipeline_version=pipeline_version)
+
+ with (
+ patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"),
+ patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs.schedule_external_data_failure_digest"
+ ),
+ patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs._sweep_v3_queue_batches"
+ ) as mock_sweep,
+ django_capture_on_commit_callbacks(execute=True),
+ ):
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=status,
+ logger=MagicMock(),
+ latest_error="boom" if status == ExternalDataJob.Status.FAILED else None,
+ )
+
+ mock_sweep.assert_not_called()
+
+ def test_takeover_recovery_completed_flip_sweeps_queue_batches(self, django_capture_on_commit_callbacks):
+ # Failed -> Completed after lock takeover is the one Completed write that can leave
+ # batches behind: a producer may have enqueued after the takeover's own sweep.
+ team, _source, _schema, job = _create_org_team_source_schema_job(
+ pipeline_version=ExternalDataJob.PipelineVersion.V3
+ )
+
+ with (
+ patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"),
+ patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs.schedule_external_data_failure_digest"
+ ),
+ patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs._sweep_v3_queue_batches"
+ ) as mock_sweep,
+ ):
+ with django_capture_on_commit_callbacks(execute=True):
+ 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,
+ )
+ mock_sweep.reset_mock()
+
+ with django_capture_on_commit_callbacks(execute=True):
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.COMPLETED,
+ logger=MagicMock(),
+ latest_error=None,
+ )
+
+ mock_sweep.assert_called_once()
+ assert mock_sweep.call_args.kwargs["status"] == ExternalDataJob.Status.COMPLETED
+
+ def test_queue_sweep_error_does_not_fail_status_update(self, django_capture_on_commit_callbacks):
+ # The queue is a separate physical Postgres; an outage there must never fail or roll
+ # back the status write the sweep rides on.
+ team, _source, _schema, job = _create_org_team_source_schema_job(
+ pipeline_version=ExternalDataJob.PipelineVersion.V3
+ )
+
+ with (
+ patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"),
+ patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs.schedule_external_data_failure_digest"
+ ),
+ patch(
+ "products.data_warehouse.backend.logic.external_data_source.jobs._sweep_v3_queue_batches",
+ side_effect=Exception("queue db down"),
+ ) as mock_sweep,
+ django_capture_on_commit_callbacks(execute=True),
+ ):
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.FAILED,
+ logger=MagicMock(),
+ latest_error="boom",
+ )
+
+ mock_sweep.assert_called_once()
+ db_job = ExternalDataJob.objects.get(id=job.id)
+ assert db_job.status == ExternalDataJob.Status.FAILED
+ assert db_job.finished_at is not None