: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): harden v3 queue retention against silent run loss (#72377)
estefania1e6af8c055ae
diff --git a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.pyindex a737a5b8d5a6..b12ed1fcceb8 100644--- a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py+++ b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py@@ -7,11 +7,13 @@ from datetime import datefrom typing import Any, Literalimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom posthog.temporal.warehouse_sources_queue_partition_management import activities as activities_modulefrom posthog.temporal.warehouse_sources_queue_partition_management.activities import (+ RETENTION_STRANDED_ERROR,_cleanup_old_s3_extractions,+ _terminalize_stranded_runs,manage_warehouse_sources_queue_partitions,)@@ -297,7 +299,16 @@ def test_uses_configured_bucket_prefix() -> None:class _FakePgConn:- """Minimal psycopg.Connection stand-in: context manager + .execute returning a cursor."""+ """Minimal psycopg.Connection stand-in: context manager + .execute returning a cursor.++ ``partitions`` (parent table -> partition names) feeds the pg_inherits+ listing so the drop loop has something to drop; executed DROPs are recorded+ in ``dropped``.+ """++ def __init__(self, partitions: dict[str, list[str]] | None = None) -> None:+ self.partitions = partitions or {}+ self.dropped: list[str] = []def __enter__(self) -> _FakePgConn:return self@@ -305,22 +316,27 @@ class _FakePgConn:def __exit__(self, *args: Any) -> Literal[False]:return False- def execute(self, _sql: Any, _params: Any = None) -> MagicMock:+ def execute(self, sql: Any, params: Any = None) -> MagicMock:cursor = MagicMock()cursor.fetchall.return_value = []+ if "pg_inherits" in sql and params:+ cursor.fetchall.return_value = [(name,) for name in self.partitions.get(params[0], [])]+ elif sql.startswith("DROP TABLE IF EXISTS "):+ self.dropped.append(sql.removeprefix("DROP TABLE IF EXISTS "))return cursor@contextmanager-def _patched_pg():+def _patched_pg(partitions: dict[str, list[str]] | None = None):# _verify_partitions is stubbed because the fake connection returns no rows, which would# otherwise flood `errors` with bogus "partition missing" messages — orthogonal to the# S3-cleanup wiring these integration tests cover.+ conn = _FakePgConn(partitions)with (- patch.object(activities_module.psycopg.Connection, "connect", return_value=_FakePgConn()) as connect,+ patch.object(activities_module.psycopg.Connection, "connect", return_value=conn),patch.object(activities_module, "_verify_partitions"),):- yield connect+ yield conn@pytest.mark.asyncio@@ -359,6 +375,128 @@ async def test_activity_s3_failure_marks_success_false_and_triggers_slack(activipost.assert_called_once()+# Terminalizing stranded runs before partition drops+++class _StrandedQueryConn:+ """Stand-in for the queue-DB connection inside _terminalize_stranded_runs."""++ def __init__(self, rows: list[tuple[Any, ...]]) -> None:+ self.rows = rows++ def execute(self, _sql: Any, _params: Any = None) -> MagicMock:+ cursor = MagicMock()+ cursor.fetchall.return_value = self.rows+ return cursor+++@contextmanager+def _patched_terminalize_collaborators():+ with (+ patch("products.warehouse_sources.backend.facade.pipelines.BatchQueue") as batch_queue,+ patch("products.warehouse_sources.backend.facade.pipelines.mark_job_failed_if_not_terminal") as mark_failed,+ patch("products.warehouse_sources.backend.facade.pipelines.release_v3_pipeline_lock") as release_lock,+ ):+ batch_queue.fail_batches_for_job_sync.return_value = 2+ yield batch_queue, mark_failed, release_lock+++def test_terminalize_fails_each_stranded_run_and_releases_its_lock() -> None:+ conn = _StrandedQueryConn(+ [+ ("run-1", 1, "schema-a", "job-1", "wf-run-1", 3),+ ("run-2", 2, "schema-b", "job-2", None, 1),+ ]+ )++ with _patched_terminalize_collaborators() as (batch_queue, mark_failed, release_lock):+ _terminalize_stranded_runs(conn, "sourcebatch_20000101") # type: ignore[arg-type]++ assert batch_queue.fail_batches_for_job_sync.call_args_list == [+ call(conn, job_id="job-1", reason=RETENTION_STRANDED_ERROR),+ call(conn, job_id="job-2", reason=RETENTION_STRANDED_ERROR),+ ]+ assert mark_failed.call_args_list == [+ call(job_id="job-1", team_id=1, error=RETENTION_STRANDED_ERROR),+ call(job_id="job-2", team_id=2, error=RETENTION_STRANDED_ERROR),+ ]+ # Only run-1 recorded a workflow_run_id; releasing without the holder's token must not happen.+ release_lock.assert_called_once_with(1, "schema-a", "wf-run-1")+++def test_terminalize_keeps_batches_non_terminal_when_job_fail_write_errors() -> None:+ # The queue-batch fail must come last: it flips the very state the sweep uses+ # to rediscover a stranded run, so committing it before a failed app-DB write+ # would make tomorrow's retry see an all-terminal partition and drop the+ # evidence with the job still RUNNING.+ conn = _StrandedQueryConn([("run-1", 1, "schema-a", "job-1", "wf-run-1", 3)])++ with _patched_terminalize_collaborators() as (batch_queue, mark_failed, _release_lock):+ mark_failed.side_effect = RuntimeError("app db unavailable")+ with pytest.raises(RuntimeError):+ _terminalize_stranded_runs(conn, "sourcebatch_20000101") # type: ignore[arg-type]++ batch_queue.fail_batches_for_job_sync.assert_not_called()+++def test_terminalize_makes_no_writes_for_all_terminal_partition() -> None:+ with _patched_terminalize_collaborators() as (batch_queue, mark_failed, release_lock):+ _terminalize_stranded_runs(_StrandedQueryConn([]), "sourcebatch_20000101") # type: ignore[arg-type]++ batch_queue.fail_batches_for_job_sync.assert_not_called()+ mark_failed.assert_not_called()+ release_lock.assert_not_called()+++OLD_BATCH_PART = "sourcebatch_20000101"+OLD_BATCH_PART_2 = "sourcebatch_20000102"+OLD_STATUS_PART = "sourcebatchstatus_20000101"+++async def test_activity_terminalizes_only_sourcebatch_partitions_then_drops(activity_environment) -> None:+ partitions = {"sourcebatch": [OLD_BATCH_PART], "sourcebatchstatus": [OLD_STATUS_PART]}++ with (+ _patched_pg(partitions) as conn,+ _patched_s3([]),+ patch.object(activities_module, "_terminalize_stranded_runs") as terminalize,+ ):+ result = await activity_environment.run(manage_warehouse_sources_queue_partitions)++ # Status partitions carry no run state, so only the sourcebatch partition terminalizes.+ terminalize.assert_called_once_with(conn, OLD_BATCH_PART)+ assert OLD_BATCH_PART in result["dropped"]+ assert OLD_STATUS_PART in result["dropped"]+ assert result["success"] is True+++async def test_activity_keeps_partition_when_terminalization_fails(activity_environment) -> None:+ partitions = {+ "sourcebatch": [OLD_BATCH_PART, OLD_BATCH_PART_2],+ "sourcebatchstatus": [OLD_STATUS_PART],+ }++ def _boom(_conn: Any, partition_name: str) -> None:+ if partition_name == OLD_BATCH_PART:+ raise RuntimeError("app-db unavailable")++ with (+ _patched_pg(partitions) as conn,+ _patched_s3([]),+ patch.object(activities_module, "_terminalize_stranded_runs", side_effect=_boom),+ ):+ result = await activity_environment.run(manage_warehouse_sources_queue_partitions)++ # The failed partition is preserved as evidence (no DROP even attempted); everything else proceeds.+ assert OLD_BATCH_PART not in conn.dropped+ assert OLD_BATCH_PART_2 in result["dropped"]+ assert OLD_STATUS_PART in result["dropped"]+ assert result["success"] is False+ assert any(OLD_BATCH_PART in e for e in result["errors"])++@pytest.mark.asyncioasync def test_activity_logs_s3_deleted_count(activity_environment) -> None:entries = [diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.pyindex 76e8f93446aa..1438d6bb2ffd 100644--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py@@ -2,6 +2,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom datetime import UTC, date, datetime, timedelta+from typing import Anyfrom django.conf import settings@@ -9,6 +10,7 @@ import psycopgimport requestsimport structlogimport temporalio.activity+from asgiref.sync import sync_to_asynclogger = structlog.get_logger(__name__)@@ -16,6 +18,14 @@ PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus", "sourcebatchduckgresstPARTITIONS_AHEAD = 7RETENTION_DAYS = 7+# Deliberately not the lock-takeover sentinel — that string has special+# downstream semantics in the dead-job gate.+RETENTION_STRANDED_ERROR = "batches aged out of retention without being processed"++# Batch states that mean a run is still owed work (mirrors the non-terminal+# set in postgres_queue/jobs_db.py; 'pending' = never claimed).+_NON_TERMINAL_BATCH_STATES = ("pending", "waiting", "waiting_retry", "executing")+# The duckgres apply-marker table is unpartitioned (small rows, UNIQUE-constrained),# so retention is DELETE-based. Must comfortably exceed the consumers' eligibility# window (PARTITION_PRUNING_INTERVAL, 14d): the duckgres ordering gate and@@ -81,6 +91,18 @@ async def manage_warehouse_sources_queue_partitions() -> dict:except (ValueError, IndexError):continueif partition_date < cutoff:+ if table == "sourcebatch":+ try:+ await sync_to_async(_terminalize_stranded_runs)(conn, partition_name)+ except Exception as e:+ # Keep the partition as evidence while the alert is live;+ # partitions are daily and small, so retrying tomorrow is cheap.+ errors.append(f"Failed to terminalize stranded runs in {partition_name}: {e}")+ logger.exception(+ "Failed to terminalize stranded runs before partition drop",+ partition=partition_name,+ )+ continuetry:conn.execute(f"DROP TABLE IF EXISTS {partition_name}")dropped.append(partition_name)@@ -126,6 +148,83 @@ async def manage_warehouse_sources_queue_partitions() -> dict:}+def _terminalize_stranded_runs(conn: psycopg.Connection, partition_name: str) -> None:+ """Fail runs that still have non-terminal batches in ``partition_name`` before it is dropped.++ Dropping the data itself is deliberate — the staged cursor never promoted,+ so the next run re-extracts. What must not happen silently is the run: with+ its batches gone, the final batch never arrives, the ExternalDataJob stays+ RUNNING forever, no terminal status means no app_metrics2 alert, and the+ pipeline lock stays held. So fail the run's batches (the whole run — runs+ span partitions, and leftover claimable siblings could resurrect the job),+ mark the job Failed, and release the schema lock.++ Fail-closed: any error propagates so the caller records it and skips the+ drop, preserving the evidence for the retry.+ """+ from django.db import close_old_connections++ from products.warehouse_sources.backend.facade.pipelines import (+ BatchQueue,+ mark_job_failed_if_not_terminal,+ release_v3_pipeline_lock,+ )++ states = ", ".join(f"'{s}'" for s in _NON_TERMINAL_BATCH_STATES)+ stranded = conn.execute(+ f"""+ SELECT run_uuid, team_id, schema_id, job_id,+ MAX(metadata->>'workflow_run_id') AS workflow_run_id,+ COUNT(*) AS non_terminal_batches+ FROM {partition_name}+ WHERE latest_state IN ({states})+ GROUP BY run_uuid, team_id, schema_id, job_id+ ORDER BY run_uuid+ """+ ).fetchall()+ if not stranded:+ return++ # Drop stale app-DB connections so the job-status writes reconnect instead of erroring.+ close_old_connections()++ runs_failed: list[dict[str, Any]] = []+ total_failed_batches = 0+ for run_uuid, team_id, schema_id, job_id, workflow_run_id, non_terminal_batches in stranded:+ # Batches are failed LAST — the inverse of the takeover ordering, which is+ # safe here because these batches are past CLAIM_ELIGIBILITY_INTERVAL and+ # can never be claimed. Failing them first would flip the very state this+ # sweep uses to rediscover the run, so a crash between the two DBs+ # (autocommit, no cross-DB atomicity) would strand the job invisibly.+ mark_job_failed_if_not_terminal(job_id=job_id, team_id=team_id, error=RETENTION_STRANDED_ERROR)+ lock_released: bool | None = None+ if workflow_run_id:+ lock_released = release_v3_pipeline_lock(team_id, schema_id, workflow_run_id)+ total_failed_batches += BatchQueue.fail_batches_for_job_sync(+ conn, job_id=job_id, reason=RETENTION_STRANDED_ERROR+ )+ runs_failed.append(+ {+ "run_uuid": run_uuid,+ "team_id": team_id,+ "schema_id": schema_id,+ "job_id": job_id,+ "non_terminal_batches": non_terminal_batches,+ # False also covers benign cases (already expired / taken over),+ # so this is observability only — never gate the drop on it.+ "lock_released": lock_released,+ }+ )++ logger.warning(+ "Terminalized stranded runs before partition drop",+ partition=partition_name,+ runs_failed=len(runs_failed),+ failed_batches=total_failed_batches,+ runs=runs_failed,+ )++def _cleanup_old_s3_extractions(today: date, errors: list[str]) -> list[str]:"""Delete S3 date-partitioned extraction prefixes older than RETENTION_DAYS."""from products.data_warehouse.backend.facade.api import get_s3_clientdiff --git a/products/warehouse_sources/backend/facade/pipelines.py b/products/warehouse_sources/backend/facade/pipelines.pyindex 69cbc5d8cad4..546539faa4e6 100644--- a/products/warehouse_sources/backend/facade/pipelines.py+++ b/products/warehouse_sources/backend/facade/pipelines.py@@ -18,6 +18,9 @@ _LAZY = {"LOCK_TAKEOVER_LATEST_ERROR": "metrics","TERMINAL_JOB_STATUSES": "metrics","emit_data_import_app_metrics": "metrics",+ "BatchQueue": "pipelines.pipeline_v3.postgres_queue.jobs_db",+ "mark_job_failed_if_not_terminal": "pipelines.pipeline_v3.postgres_queue.consumer",+ "release_v3_pipeline_lock": "pipelines.pipeline_v3.sync_lock","CDCExtractionInput": "cdc.workflows","is_pipeline_v3_enabled": "workflow_activities.create_job_model","SyncNewSchemasActivityInputs": "workflow_activities.sync_new_schemas",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 1890a10d7270..0790ef416695 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,17 @@ LEASE_TTL_SECONDS = 300# gone by the time this matters.PARTITION_PRUNING_INTERVAL = "14 days"+# Oldest a batch may be and still be claimed or recovery-swept. MUST stay below+# the retention window (RETENTION_DAYS in+# posthog/temporal/warehouse_sources_queue_partition_management/activities.py):+# a claimed batch's extraction parquet must still exist in S3, and the half-day+# margin absorbs clock skew and sweep timing. Applies only to the outer claim+# candidates and the recovery sweep — never to the head-of-line/failed-run/+# schema-busy gates, which must keep seeing rows aged past this window for as+# long as they exist. The duckgres claim path (duckgres/jobs_db.py) has a+# similar exposure but is deliberately out of scope here.+CLAIM_ELIGIBILITY_INTERVAL = "6 days 12 hours"+# 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@@ -211,6 +222,12 @@ def _state_claim_candidates_sql(sync_type_scope: str = "") -> str:candidate set to this fleet's classes. It must never be applied inside theNOT EXISTS gates below: they have to see other fleets' batches so oneschema's runs stay mutually exclusive across fleets.++ The outer candidate set is likewise bounded by+ ``CLAIM_ELIGIBILITY_INTERVAL``: a batch older than that may already have+ lost its parquet to retention, so it must never be claimed. The gates keep+ ``PARTITION_PRUNING_INTERVAL`` for the same reason the sync-type scope+ stays out of them — they must see every row that still exists."""return f"""SELECT@@ -223,7 +240,7 @@ def _state_claim_candidates_sql(sync_type_scope: str = "") -> str:b.created_atFROM {BATCH_TABLE} bWHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'{sync_type_scope}AND (b.latest_state = 'pending'@@ -275,6 +292,9 @@ def _stale_executing_sql(scope_sql: str = "") -> str:currently-executing batches. The lateral itself must stay: heartbeatsrefresh the status log, deliberately not the column, so the grace clockcomes from ``s.created_at``.++ Bounded by ``CLAIM_ELIGIBILITY_INTERVAL``, matching the claim path: a+ recovered batch gets re-processed, which needs its parquet to still exist."""return f"""SELECT@@ -283,7 +303,7 @@ def _stale_executing_sql(scope_sql: str = "") -> str:{latest_status_lateral("b", "s", join="INNER")}LEFT JOIN {LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_idWHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ b.created_at > now() - interval '{CLAIM_ELIGIBILITY_INTERVAL}'AND b.latest_state = 'executing'AND s.job_state = 'executing'AND s.created_at <= now() - make_interval(secs => %(grace)s)@@ -511,8 +531,9 @@ class BatchQueue:"""Fetch unprocessed batches whose (team_id, schema_id) group lease is claimable by ``owner_token``.Candidates come from the denormalized state columns, so poll cost- tracks the claimable set rather than everything retained in the- 14-day window.+ tracks the claimable set rather than everything retained; candidates+ are also capped at ``CLAIM_ELIGIBILITY_INTERVAL`` old so a claimed+ batch's parquet is guaranteed to predate the retention sweep.Group ownership is a row in ``sourcegrouplease`` keyed by(team_id, schema_id). The outer query claims-or-renews the lease fordiff --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 64e363ab1337..ddd444ce8134 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@@ -1,3 +1,5 @@+import re+from datetime import timedeltafrom typing import Anyfrom uuid import uuid4@@ -7,6 +9,7 @@ import psycopgfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (BATCH_TABLE,+ CLAIM_ELIGIBILITY_INTERVAL,LEASE_TABLE,STATUS_TABLE,STATUS_VIEW,@@ -1107,6 +1110,74 @@ class TestClaimGates:assert "sb_claimable_idx" in plan[email protected]_db(transaction=True)+class TestClaimEligibilityWindow:+ """Batches old enough to have lost their parquet to retention must never be+ claimed or recovery-swept — but the claim gates must keep seeing them."""++ @pytest.mark.parametrize("age,claimable", [("6 days", True), ("7 days", False)])+ @pytest.mark.asyncio+ async def test_claim_excludes_batches_past_eligibility_window(self, conn, age, claimable):+ bid = await _insert_batch(conn)+ await conn.execute(+ f"UPDATE {BATCH_TABLE} SET created_at = now() - interval '{age}' WHERE id = %s",+ [bid],+ )++ batches = await _claim(conn)++ assert len(batches) == (1 if claimable else 0)+ await _release(conn, batches=batches)++ @pytest.mark.parametrize(+ "gate_state,old_run_uuid",+ [+ ("executing", "run-other"), # schema-busy gate: old executing batch in a sibling run+ ("failed", "run-x"), # failed-run gate: old failed batch in the same run+ ],+ )+ @pytest.mark.asyncio+ async def test_gates_still_see_batches_past_eligibility_window(self, conn, gate_state, old_run_uuid):+ # Guards against "optimizing" CLAIM_ELIGIBILITY_INTERVAL into the NOT+ # EXISTS gates: a 7-day-old row still exists and must keep gating until+ # retention actually removes it, or two runs of one schema overlap.+ old = await _insert_batch(conn, batch_index=0, run_uuid=old_run_uuid)+ await BatchQueue.update_status(conn, batch_id=old, job_state=gate_state, attempt=1)+ await conn.execute(+ f"UPDATE {BATCH_TABLE} SET created_at = now() - interval '7 days' WHERE id = %s",+ [old],+ )+ await _insert_batch(conn, batch_index=1, run_uuid="run-x")++ assert await _claim(conn) == []++ @pytest.mark.parametrize("age,collected", [("6 days", True), ("7 days", False)])+ @pytest.mark.asyncio+ async def test_recovery_sweep_excludes_batches_past_eligibility_window(self, conn, age, collected):+ bid = await _insert_batch(conn)+ await _insert_backdated_executing(conn, batch_id=bid, age_seconds=120)+ await conn.execute(+ f"UPDATE {BATCH_TABLE} SET created_at = now() - interval '{age}' WHERE id = %s",+ [bid],+ )++ stale = await BatchQueue.get_stale_executing(conn, grace_seconds=60)++ assert len(stale) == (1 if collected else 0)++ def test_eligibility_window_stays_below_retention_window(self):+ from posthog.temporal.warehouse_sources_queue_partition_management.activities import RETENTION_DAYS++ match = re.fullmatch(r"(?:(\d+) days?)?\s*(?:(\d+) hours?)?", CLAIM_ELIGIBILITY_INTERVAL.strip())+ assert match, f"unparseable CLAIM_ELIGIBILITY_INTERVAL: {CLAIM_ELIGIBILITY_INTERVAL!r}"+ window = timedelta(days=int(match.group(1) or 0), hours=int(match.group(2) or 0))++ assert timedelta(0) < window < timedelta(days=RETENTION_DAYS), (+ "CLAIM_ELIGIBILITY_INTERVAL must stay below RETENTION_DAYS: a claimable "+ "batch's parquet must still exist when the retention sweep runs"+ )++@pytest.mark.django_db(transaction=True)class TestSyncTypeFleetPartition:@pytest.mark.asyncio