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(ws): attempt-scoped run identity to prevent retry table corruption (#65149)

estefania83c01107ad4a
diff --git a/posthog/temporal/common/activity_context.py b/posthog/temporal/common/activity_context.py
index 879c2115beaa..8d9ee21e86d1 100644
--- a/posthog/temporal/common/activity_context.py
+++ b/posthog/temporal/common/activity_context.py
@@ -25,3 +25,11 @@ def current_workflow_run_id() -> str | None:
return activity.info().workflow_run_id
except RuntimeError:
return None
+
+
+def current_activity_attempt() -> int:
+ """Return the current Temporal activity attempt number (1-based), or 1 if not inside an activity."""
+ try:
+ return activity.info().attempt
+ except RuntimeError:
+ return 1
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 3d93b3a93dd2..2c3983202a37 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -8,7 +8,11 @@ from structlog.types import FilteringBoundLogger
from temporalio import activity
from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
-from posthog.temporal.common.activity_context import current_workflow_id, current_workflow_run_id
+from posthog.temporal.common.activity_context import (
+ current_activity_attempt,
+ current_workflow_id,
+ current_workflow_run_id,
+)
from posthog.temporal.common.shutdown import ShutdownMonitor
from posthog.temporal.data_imports.pipelines.common.extract import (
advance_xmin_state,
@@ -114,9 +118,13 @@ class PipelineV3(Generic[ResumableData]):
self._delta_table_helper = DeltaTableHelper(self._resource_name, self._job, self._logger)
+ attempt = current_activity_attempt()
+ attempt_scoped_run_uuid = f"{self._job.workflow_run_id}-a{attempt}" if self._job.workflow_run_id else None
+
self._s3_batch_writer = S3BatchWriter(
- self._logger, self._job, str(self._schema.id), self._job.workflow_run_id, compression=PARQUET_COMPRESSION
+ self._logger, self._job, str(self._schema.id), attempt_scoped_run_uuid, compression=PARQUET_COMPRESSION
)
+ self._attempt = attempt
sync_type: SyncTypeLiteral = "full_refresh"
if self._schema.is_incremental or self._schema.is_webhook or self._schema.is_xmin:
@@ -218,9 +226,13 @@ class PipelineV3(Generic[ResumableData]):
row_count = 0
chunk_index = 0
- await handle_reset_or_full_refresh(
- self._reset_pipeline, should_resume, self._schema, self._delta_table_helper, self._logger
- )
+ # On retry (attempt > 1) skip reset_table() - the consumer-side batch-0
+ # overwrite handles it. Wiping the delta table mid-retry while the consumer
+ # is loading the previous attempt's batches causes data loss.
+ if self._attempt <= 1:
+ await handle_reset_or_full_refresh(
+ self._reset_pipeline, should_resume, self._schema, self._delta_table_helper, self._logger
+ )
is_fresh_sync = self._delta_table_helper.is_first_sync or self._schema.table is None
if is_fresh_sync:
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
index f11fdea05d26..ca2b4179967c 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -426,6 +426,34 @@ class BatchQueue:
)
return cursor.rowcount or 0
+ @staticmethod
+ def supersede_other_runs(
+ conn: psycopg.Connection[Any],
+ *,
+ job_id: str,
+ current_run_uuid: str,
+ ) -> int:
+ """Mark non-terminal batches from older runs of the same job as superseded."""
+ cursor = conn.execute(
+ f"""
+ INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)
+ SELECT b.id, 'failed', 0, now(), %(error_response)s, now()
+ FROM {BATCH_TABLE} b
+ LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b.job_id = %(job_id)s
+ AND b.run_uuid != %(current_run_uuid)s
+ AND (s.batch_id IS NULL OR s.job_state IN ('waiting', 'waiting_retry', 'executing'))
+ """,
+ {
+ "job_id": job_id,
+ "current_run_uuid": current_run_uuid,
+ "error_response": json.dumps({"error": "superseded by newer attempt", "superseded": True}),
+ },
+ )
+ return cursor.rowcount or 0
+
@staticmethod
async def get_failed_runs(
conn: psycopg.AsyncConnection[Any],
@@ -454,6 +482,7 @@ class BatchQueue:
AND s.job_state = 'failed'
AND s.created_at <= now() - make_interval(secs => %(grace)s)
AND s.created_at >= now() - make_interval(secs => %(lookback)s)
+ AND COALESCE((s.error_response->>'superseded')::boolean, false) = false
ORDER BY b.run_uuid, s.created_at DESC
) failed_runs
ORDER BY failed_at DESC
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
index 015bba36abb3..ae02c1a08cb8 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
@@ -17,7 +17,7 @@ from structlog.types import FilteringBoundLogger
from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat, PartitionMode
from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral
-from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import BATCH_TABLE
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import BATCH_TABLE, BatchQueue
from posthog.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult
logger = structlog.get_logger(__name__)
@@ -126,6 +126,13 @@ class PostgresProducer:
metadata["workflow_run_id"] = self._workflow_run_id
metadata["timestamp_ns"] = batch_result.timestamp_ns
+ if batch_result.batch_index == 0 and not self._is_resume:
+ superseded = BatchQueue.supersede_other_runs(
+ self._conn, job_id=self._job_id, current_run_uuid=self._run_uuid
+ )
+ if superseded > 0:
+ self._logger.info("superseded_old_run_batches", count=superseded)
+
self._conn.execute(
f"""
INSERT INTO {BATCH_TABLE} (
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
index d2e5cecb2362..0bb185d1a9cc 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
@@ -44,7 +44,7 @@ def _mock_conn(producer: PostgresProducer) -> Any:
class TestPostgresProducerSendBatch:
def test_inserts_row_on_send(self) -> None:
producer = _make_producer()
- batch_result = _make_batch_result()
+ batch_result = _make_batch_result(batch_index=1)
producer.send_batch_notification(batch_result)
@@ -56,7 +56,7 @@ class TestPostgresProducerSendBatch:
assert params["team_id"] == 1
assert params["s3_path"] == "s3://bucket/path"
assert params["row_count"] == 100
- assert params["batch_index"] == 0
+ assert params["batch_index"] == 1
def test_metadata_includes_optional_fields(self) -> None:
producer = _make_producer(
@@ -65,7 +65,7 @@ class TestPostgresProducerSendBatch:
cdc_write_mode="upsert",
cdc_table_mode="merge",
)
- batch_result = _make_batch_result()
+ batch_result = _make_batch_result(batch_index=1)
producer.send_batch_notification(batch_result)
@@ -82,9 +82,9 @@ class TestPostgresProducerSendBatch:
class TestPostgresProducerFlush:
def test_returns_count_and_resets(self) -> None:
producer = _make_producer()
- producer.send_batch_notification(_make_batch_result(0))
- producer.send_batch_notification(_make_batch_result(1))
- producer.send_batch_notification(_make_batch_result(2))
+ producer.send_batch_notification(_make_batch_result(batch_index=1))
+ producer.send_batch_notification(_make_batch_result(batch_index=2))
+ producer.send_batch_notification(_make_batch_result(batch_index=3))
count = producer.flush()
@@ -119,6 +119,42 @@ class TestPostgresProducerClose:
mock.close.assert_not_called()
+class TestPostgresProducerSupersede:
+ def test_supersedes_old_runs_on_batch_zero(self) -> None:
+ producer = _make_producer(is_resume=False)
+ batch_result = _make_batch_result(batch_index=0)
+
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",
+ return_value=2,
+ ) as mock_supersede:
+ producer.send_batch_notification(batch_result)
+
+ mock_supersede.assert_called_once_with(producer._conn, job_id="job-1", current_run_uuid="run-1")
+
+ def test_does_not_supersede_on_non_zero_batch(self) -> None:
+ producer = _make_producer(is_resume=False)
+ batch_result = _make_batch_result(batch_index=1)
+
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",
+ ) as mock_supersede:
+ producer.send_batch_notification(batch_result)
+
+ mock_supersede.assert_not_called()
+
+ def test_does_not_supersede_on_resume(self) -> None:
+ producer = _make_producer(is_resume=True)
+ batch_result = _make_batch_result(batch_index=0)
+
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",
+ ) as mock_supersede:
+ producer.send_batch_notification(batch_result)
+
+ mock_supersede.assert_not_called()
+
+
class TestPostgresProducerProperties:
def test_sync_type_property(self) -> None:
producer = _make_producer(sync_type="incremental")
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index 7bd16171cfb9..12f105a54a0f 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -48,10 +48,126 @@ def _make_pipeline() -> PipelineV3:
pipeline._accumulated_pa_schema = None
pipeline._batch_results = []
pipeline._shutdown_monitor = MagicMock()
+ pipeline._attempt = 1
return pipeline
+class TestAttemptScopedRunUuid:
+ def test_run_uuid_includes_attempt_number(self) -> None:
+ mock_job = MagicMock(
+ team_id=1,
+ workflow_run_id="wfrun-abc",
+ billable=False,
+ id="job-1",
+ )
+ mock_schema = MagicMock(
+ id="schema-1",
+ source_id="source-1",
+ is_incremental=False,
+ is_webhook=False,
+ is_xmin=False,
+ is_append=False,
+ table=None,
+ primary_key_columns=None,
+ partition_count=None,
+ partition_size=None,
+ partitioning_keys=None,
+ partition_format=None,
+ partition_mode=None,
+ incremental_field_earliest_value=None,
+ incremental_field_type=None,
+ )
+ mock_source = MagicMock()
+ mock_resource = MagicMock(
+ name="test",
+ primary_keys=["id"],
+ partition_count=None,
+ partition_size=None,
+ partition_keys=None,
+ partition_format=None,
+ partition_mode=None,
+ )
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.current_activity_attempt",
+ return_value=3,
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.current_workflow_id",
+ return_value="wf-1",
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.current_workflow_run_id",
+ return_value="wfrun-abc",
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.S3BatchWriter",
+ ) as mock_s3_writer_cls,
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.PostgresProducer",
+ ),
+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.DeltaTableHelper"),
+ ):
+ mock_s3_writer_cls.return_value = MagicMock(get_run_uuid=MagicMock(return_value="wfrun-abc-a3"))
+ pipeline: PipelineV3 = PipelineV3(
+ source_response=mock_resource,
+ logger=_make_logger(),
+ job_id="job-1",
+ reset_pipeline=False,
+ shutdown_monitor=MagicMock(),
+ job=mock_job,
+ schema=mock_schema,
+ source=mock_source,
+ table=None,
+ resumable_source_manager=None,
+ )
+
+ assert pipeline._attempt == 3
+ mock_s3_writer_cls.assert_called_once()
+ assert mock_s3_writer_cls.call_args[0][3] == "wfrun-abc-a3"
+
+ @pytest.mark.asyncio
+ async def test_skips_reset_table_on_retry(self) -> None:
+ pipeline = _make_pipeline()
+ pipeline._attempt = 2
+ pipeline._reset_pipeline = True
+ pipeline._cdp_producer = MagicMock(should_produce_table=AsyncMock(return_value=False))
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.cdp_producer_clear_chunks",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.reset_rows_synced_if_needed",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.validate_incremental_sync",
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.setup_row_tracking_with_billing_check",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.handle_reset_or_full_refresh",
+ new_callable=AsyncMock,
+ ) as mock_reset,
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.activity",
+ ) as mock_activity,
+ ):
+ mock_activity.in_activity.return_value = False
+ pipeline._resource.items = MagicMock(return_value=iter([]))
+ pipeline._batcher.should_yield.return_value = False # type: ignore[attr-defined]
+
+ await pipeline.run()
+
+ mock_reset.assert_not_called()
+
+
class TestExtractionFailureDoesNotCleanupS3:
@pytest.mark.asyncio
async def test_s3_files_preserved_when_extraction_fails(self) -> None:
diff --git a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py b/posthog/temporal/data_imports/workflow_activities/import_data_sync.py
index e532f136b60e..78b437e04145 100644
--- a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/posthog/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -12,9 +12,11 @@ from temporalio import activity
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.common.activity_context import current_activity_attempt
from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.shutdown import ShutdownMonitor
+from posthog.temporal.data_imports.metrics import TERMINAL_JOB_STATUSES
from posthog.temporal.data_imports.pipelines.common.extract import (
handle_non_retryable_error,
report_heartbeat_timeout,
@@ -95,6 +97,19 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
model = await _get_external_data_job(inputs.run_id)
+ if model.pipeline_version == ExternalDataJob.PipelineVersion.V3:
+ attempt = current_activity_attempt()
+ if attempt > 1 and model.status in TERMINAL_JOB_STATUSES:
+ await logger.ainfo(
+ "Skipping retry - job already terminal",
+ status=model.status,
+ attempt=attempt,
+ )
+ return PipelineResult(
+ should_trigger_cdp_producer=False,
+ consumer_manages_job_status=True,
+ )
+
await logger.adebug("Running import_data_activity")
source_type = ExternalDataSourceType(model.pipeline.source_type)
@@ -215,7 +230,6 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
)
except CDCHandledExternally:
await logger.ainfo("Schema is in CDC streaming mode — handled by CDCExtractionWorkflow, skipping")
- from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
await database_sync_to_async_pool(ExternalDataJob.objects.filter(id=job_inputs.run_id).update)(
billable=False, status=ExternalDataJob.Status.COMPLETED, finished_at=dt.datetime.now(dt.UTC)
diff --git a/products/logs/backend/test/test_alert_utils.py b/products/logs/backend/test/test_alert_utils.py
index e2a30f3443dc..15fe6e5cb2fc 100644
--- a/products/logs/backend/test/test_alert_utils.py
+++ b/products/logs/backend/test/test_alert_utils.py
@@ -1,3 +1,4 @@
+import random
from datetime import UTC, datetime, timedelta
from uuid import UUID
@@ -342,13 +343,13 @@ class TestComputeShardOffsetSeconds(TestCase):
assert 0 <= offset < cadence * 60
def test_distribution_across_many_alerts_is_roughly_uniform(self) -> None:
- # 1000 random UUIDs at 5-min cadence (5 shards). Each shard should
- # see ~200 alerts. Allow ±20% drift before flagging non-uniformity.
- from uuid import uuid4
-
+ # 1000 UUIDs at 5-min cadence (5 shards). Each shard should see ~200
+ # alerts. Seeded so an unlucky random draw can't flake the ±20% bound
+ # while still exercising the same uniform-spread property.
+ rng = random.Random(0)
counts: dict[int, int] = {0: 0, 60: 0, 120: 0, 180: 0, 240: 0}
for _ in range(1000):
- offset = compute_shard_offset_seconds(uuid4(), 5)
+ offset = compute_shard_offset_seconds(UUID(int=rng.getrandbits(128)), 5)
counts[offset] += 1
for offset, count in counts.items():