: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): spare queued v3 runs, fail restart-killed jobs (#100514)
Daniel RC08275cd9503a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 3fd411c7131c..4bb635a4cc4d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -300,6 +300,11 @@ CANCELLED_RUN_MESSAGE = ("it or the source is paused. It will run again on its next schedule.")+WORKER_RESTART_ERROR_MESSAGE = (+ "This sync run was interrupted too many times by restarts on PostHog's side, so it did not finish. "+ "It will run again automatically. No action is needed."+)+TRANSIENT_SOURCE_ERROR_MESSAGE = ("The source's API kept returning temporary errors, such as rate limits or server errors, so this ""sync run did not finish. This is usually a short problem on the source's side. The sync will run "@@ -1157,6 +1162,14 @@ class ExternalDataJobWorkflow(PostHogWorkflow):except exceptions.ActivityError as e:if isinstance(e.cause, exceptions.ApplicationError) and e.cause.type == "WorkerShuttingDownError":+ if is_v3:+ # No final batch reached the queue, so the loader can never complete this job.+ # A COMPLETED write would release the pipeline lock and let the buffered run+ # extract the same table again on top of this run's still-queued batches.+ # Set before the buffer-one activity so a failure there cannot skip it.+ update_inputs.status = ExternalDataJob.Status.FAILED+ update_inputs.internal_error = str(e.cause)+ update_inputs.latest_error = WORKER_RESTART_ERROR_MESSAGE# Check if this is a WorkerShuttingDownError - implement Buffer One retryschedule_id = str(inputs.external_data_schema_id)await workflow.execute_activity(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.pyindex 4da473023c48..98aee2fc745e 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@@ -387,6 +387,22 @@ def _stranded_candidate_runs_sql() -> str:The ``OFFSET 0`` in the failed-run gate is an optimization fence: withoutit the planner flattens the subquery back into that same hash anti-join.It changes no semantics; the plan-shape test pins the probe.++ Loader progress anywhere in a (team_id, schema_id) group spares every run+ in it. The loader serializes a group and claims its batches oldest-first,+ so a run queued behind a long sibling makes no progress of its own until+ the sibling drains, however many hours that takes. An active-state+ transition in the group inside the stale window means the group is being+ drained and its other runs are waiting their turn, not abandoned. Only+ 'executing', 'succeeded' and 'waiting_retry' count, as in+ ``supersede_other_runs``: a 'failed' write is the reconcile sweep's own+ output, and heartbeats refresh the status log but not ``state_changed_at``,+ so a wedged-but-heartbeating loader cannot shield a group forever (its live+ lease already protects it while it heartbeats). The group lease cannot+ stand in for this check: the loader releases it between claim windows, so+ a busy group is lease-less for an instant many times an hour. The probe+ runs once per group rather than once per run, because a genuinely stale+ group answers only after reading every batch it holds."""return f"""WITH stranded_runs AS (@@ -396,6 +412,17 @@ def _stranded_candidate_runs_sql() -> str:AND b.created_at <= now() - make_interval(secs => %(stale)s)AND b.latest_state IN ('pending', 'waiting', 'waiting_retry', 'executing')GROUP BY b.run_uuid, b.team_id, b.schema_id+ ),+ progressing_groups AS (+ SELECT g.team_id, g.schema_id+ FROM (SELECT DISTINCT team_id, schema_id FROM stranded_runs) g+ WHERE EXISTS (+ SELECT 1 FROM {BATCH_TABLE} bp+ WHERE bp.team_id = g.team_id AND bp.schema_id = g.schema_id+ AND bp.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND bp.latest_state IN ('executing', 'succeeded', 'waiting_retry')+ AND bp.state_changed_at > now() - make_interval(secs => %(stale)s)+ ))SELECT r.run_uuid, r.team_id, r.schema_idFROM stranded_runs r@@ -411,6 +438,10 @@ def _stranded_candidate_runs_sql() -> str:AND bf.latest_state = 'failed'OFFSET 0)+ AND NOT EXISTS (+ SELECT 1 FROM progressing_groups p+ WHERE p.team_id = r.team_id AND p.schema_id = r.schema_id+ )-- Oldest-batch-first, so the window can't be starved by an arbitrary set of-- not-yet-stale runs the outer HAVING later rejects: the longest-stranded runs-- always land in it, and successive sweeps make deterministic forward progress.@@ -1265,7 +1296,9 @@ class BatchQueue:without this the batches strand until the retention prune (days later).Staleness is *loader progress only*: the newest status write across the run, or — when the- loader never claimed anything — the oldest batch's age. Batch inserts (producer activity)+ loader never claimed anything — the oldest batch's age. Progress on any sibling run of the same+ (team_id, schema_id) group also spares the run: the loader drains a group one run at a time, so+ a run queued behind a long sibling is waiting, not abandoned. Batch inserts (producer activity)deliberately do not reset the clock, mirroring ``get_run_activity_summary``, so a live producerstreaming into a dead loader still reads as stale. A live group lease means a pod is activelyworking the group (making progress, or the recovery sweep reclaims it on lease expiry), so thosediff --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.pyindex e48dcd8abede..4d5fbddff2cf 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@@ -1030,6 +1030,23 @@ class TestGetStaleStrandedRuns:assert await self._run(conn) == []+ @pytest.mark.parametrize(+ "head_state, queued_schema_id, expect_stranded",+ [("succeeded", "schema-1", False), ("succeeded", "schema-2", True), ("failed", "schema-1", True)],+ )+ @pytest.mark.asyncio+ async def test_progress_anywhere_in_group_spares_runs_queued_behind_it(+ self, conn, head_state: str, queued_schema_id: str, expect_stranded: bool+ ):+ await self._stale_pending(conn, batch_index=0, run_uuid="head", job_id="job-head")+ done = await self._stale_pending(conn, batch_index=1, run_uuid="head", job_id="job-head")+ await BatchQueue.update_status(conn, batch_id=done, job_state=head_state, attempt=1)+ await self._stale_pending(conn, run_uuid="queued", job_id="job-queued", schema_id=queued_schema_id)++ refs = await self._run(conn)++ assert [ref.run_uuid for ref in refs] == (["queued"] if expect_stranded else [])+@pytest.mark.asyncioasync def test_excludes_run_with_failed_batch(self, conn):# A failed batch is the failed-run reconcile's job; this sweep must not double-handle it.diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.pyindex 253a2f566bcb..1548c2908c8e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py@@ -68,7 +68,10 @@ from products.warehouse_sources.backend.models.external_data_destination importfrom products.warehouse_sources.backend.models.external_table_definitions import external_tablesfrom products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEventfrom products.warehouse_sources.backend.temporal.data_imports.cdp_producer_job import CDPProducerJobWorkflow-from products.warehouse_sources.backend.temporal.data_imports.external_data_job import ExternalDataJobWorkflow+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import (+ WORKER_RESTART_ERROR_MESSAGE,+ ExternalDataJobWorkflow,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenancefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef@@ -3365,15 +3368,20 @@ async def test_worker_shutdown_triggers_schedule_buffer_one(team, zendesk_brandsignore_assertions=True,)- # assert that the running job was completed successfully and that the new workflow was triggeredmock_trigger_schedule_buffer_one.assert_called_once_with(mock.ANY, str(inputs.external_data_schema_id))- run: ExternalDataJob | None = await get_latest_run_if_exists(- team_id=inputs.team_id, pipeline_id=inputs.external_data_source_id- )+ run: ExternalDataJob | None = await sync_to_async(+ ExternalDataJob.objects.filter(team_id=inputs.team_id, pipeline_id=inputs.external_data_source_id)+ .order_by("-created_at")+ .first+ )()assert run is not None- assert run.status == ExternalDataJobStatus.COMPLETED+ if _current_pipeline_mode == "v3":+ assert run.status == ExternalDataJobStatus.FAILED+ assert run.latest_error == WORKER_RESTART_ERROR_MESSAGE+ else:+ assert run.status == ExternalDataJobStatus.COMPLETED@pytest.mark.django_db(transaction=True)