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): stop v3 sync jobs getting stuck in running (#60642)

estefania19f224a3aa4c
diff --git a/posthog/temporal/data_imports/pipelines/common/extract.py b/posthog/temporal/data_imports/pipelines/common/extract.py
index f989441d2ea8..bf4c22a3187f 100644
--- a/posthog/temporal/data_imports/pipelines/common/extract.py
+++ b/posthog/temporal/data_imports/pipelines/common/extract.py
@@ -192,7 +192,7 @@ async def reset_rows_synced_if_needed(
and not should_resume
):
job.rows_synced = 0
- await database_sync_to_async_pool(job.save)()
+ await database_sync_to_async_pool(job.save)(update_fields=["rows_synced", "updated_at"])
def validate_incremental_sync(
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index 309b92567449..d502394333a2 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -211,7 +211,7 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessag
if delta_table is None:
logger.error(
"no_delta_table_for_post_load",
- job_id=export_signal.job_id,
+ external_data_job_id=export_signal.job_id,
batch_index=export_signal.batch_index,
)
return
@@ -252,9 +252,9 @@ def _mark_job_completed(export_signal: ExportSignalMessage) -> None:
logger.info(
"job_marked_completed",
- job_id=export_signal.job_id,
+ external_data_job_id=export_signal.job_id,
team_id=export_signal.team_id,
- schema_id=export_signal.schema_id,
+ external_data_schema_id=export_signal.schema_id,
)
@@ -268,9 +268,9 @@ def _mark_job_failed(export_signal: ExportSignalMessage, error: Exception) -> No
if existing is not None:
logger.info(
"job_already_marked_failed",
- job_id=export_signal.job_id,
+ external_data_job_id=export_signal.job_id,
team_id=export_signal.team_id,
- schema_id=export_signal.schema_id,
+ external_data_schema_id=export_signal.schema_id,
)
return
@@ -284,9 +284,9 @@ def _mark_job_failed(export_signal: ExportSignalMessage, error: Exception) -> No
logger.info(
"job_marked_failed",
- job_id=export_signal.job_id,
+ external_data_job_id=export_signal.job_id,
team_id=export_signal.team_id,
- schema_id=export_signal.schema_id,
+ external_data_schema_id=export_signal.schema_id,
error=str(error),
)
@@ -333,7 +333,7 @@ def process_message(message: Any, progress_callback: Callable[[], None] | None =
logger.info(
"batch_already_processed",
team_id=export_signal.team_id,
- schema_id=export_signal.schema_id,
+ external_data_schema_id=export_signal.schema_id,
run_uuid=export_signal.run_uuid,
batch_index=export_signal.batch_index,
)
@@ -343,7 +343,7 @@ def process_message(message: Any, progress_callback: Callable[[], None] | None =
logger.info(
"batch_already_processed_running_post_load",
team_id=export_signal.team_id,
- schema_id=export_signal.schema_id,
+ external_data_schema_id=export_signal.schema_id,
run_uuid=export_signal.run_uuid,
batch_index=export_signal.batch_index,
)
@@ -354,7 +354,7 @@ def process_message(message: Any, progress_callback: Callable[[], None] | None =
logger.debug(
"message_received",
team_id=export_signal.team_id,
- schema_id=export_signal.schema_id,
+ external_data_schema_id=export_signal.schema_id,
resource_name=export_signal.resource_name,
batch_index=export_signal.batch_index,
is_final_batch=export_signal.is_final_batch,
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 864dd7167f11..b2116b1b7e6e 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -169,7 +169,7 @@ class BatchConsumer:
logger.info(
"shutdown_mid_group",
team_id=team_id,
- schema_id=schema_id,
+ external_data_schema_id=schema_id,
batch_id=batch.id,
batch_index=batch.batch_index,
remaining=len(batches) - batches.index(batch),
@@ -181,7 +181,7 @@ class BatchConsumer:
logger.info(
"group_halted_by_non_success",
team_id=team_id,
- schema_id=schema_id,
+ external_data_schema_id=schema_id,
run_uuid=batch.run_uuid,
batch_index=batch.batch_index,
remaining=len(batches) - batches.index(batch) - 1,
@@ -216,9 +216,9 @@ class BatchConsumer:
# LogMessagesRenderer needs workflow_type/id/run_id + team_id; log_source_id routes the line.
bound_keys = (
"team_id",
- "schema_id",
- "source_id",
- "job_id",
+ "external_data_schema_id",
+ "external_data_source_id",
+ "external_data_job_id",
"run_uuid",
"batch_id",
"resource_name",
@@ -230,9 +230,9 @@ class BatchConsumer:
)
structlog.contextvars.bind_contextvars(
team_id=batch.team_id,
- schema_id=batch.schema_id,
- source_id=batch.source_id,
- job_id=batch.job_id,
+ external_data_schema_id=batch.schema_id,
+ external_data_source_id=batch.source_id,
+ external_data_job_id=batch.job_id,
run_uuid=batch.run_uuid,
batch_id=batch.id,
resource_name=batch.resource_name,
@@ -389,9 +389,9 @@ class BatchConsumer:
recovery_bound_keys = (
"team_id",
- "schema_id",
- "source_id",
- "job_id",
+ "external_data_schema_id",
+ "external_data_source_id",
+ "external_data_job_id",
"run_uuid",
"batch_id",
"resource_name",
@@ -403,9 +403,9 @@ class BatchConsumer:
# (pre-increment in _process_single), so no +1 needed here.
structlog.contextvars.bind_contextvars(
team_id=batch.team_id,
- schema_id=batch.schema_id,
- source_id=batch.source_id,
- job_id=batch.job_id,
+ external_data_schema_id=batch.schema_id,
+ external_data_source_id=batch.source_id,
+ external_data_job_id=batch.job_id,
run_uuid=batch.run_uuid,
batch_id=batch.id,
resource_name=batch.resource_name,
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index 2e4b40ff310b..b11e4ed4d78b 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -340,7 +340,7 @@ class TestLogContextBinding:
assert seen.get("workflow_run_id") == "wf-run-id-456"
assert seen.get("team_id") == batch.team_id
assert seen.get("log_source_id") == batch.schema_id
- assert seen.get("schema_id") == batch.schema_id
+ assert seen.get("external_data_schema_id") == batch.schema_id
assert seen.get("attempt") == 1
# Cleared after the batch returns so context doesn't leak across batches.
diff --git a/posthog/temporal/data_imports/workflow_activities/calculate_table_size.py b/posthog/temporal/data_imports/workflow_activities/calculate_table_size.py
index d8734725dd19..cd4154432117 100644
--- a/posthog/temporal/data_imports/workflow_activities/calculate_table_size.py
+++ b/posthog/temporal/data_imports/workflow_activities/calculate_table_size.py
@@ -71,7 +71,7 @@ def calculate_table_size_activity(inputs: CalculateTableSizeActivityInputs) -> N
logger.debug(f"Table size delta in MiB = {table_size_delta:.2f}")
job.storage_delta_mib = table_size_delta
- job.save()
+ job.save(update_fields=["storage_delta_mib", "updated_at"])
table.size_in_s3_mib = total_mib
table.save()
diff --git a/posthog/temporal/tests/data_imports/test_calculate_table_size.py b/posthog/temporal/tests/data_imports/test_calculate_table_size.py
new file mode 100644
index 000000000000..7f5418ff55aa
--- /dev/null
+++ b/posthog/temporal/tests/data_imports/test_calculate_table_size.py
@@ -0,0 +1,89 @@
+import uuid
+from datetime import UTC, datetime
+
+import pytest
+from unittest.mock import patch
+
+from posthog.models import Organization, Team
+from posthog.temporal.data_imports.workflow_activities.calculate_table_size import (
+ CalculateTableSizeActivityInputs,
+ calculate_table_size_activity,
+)
+
+from products.warehouse_sources.backend.models import DataWarehouseTable
+from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+pytestmark = [
+ pytest.mark.django_db(transaction=True),
+]
+
+
+def _setup() -> tuple[Team, ExternalDataSchema, ExternalDataJob]:
+ org = Organization.objects.create(name="Test Org")
+ team = Team.objects.create(organization=org, name="Test Team")
+ source = ExternalDataSource.objects.create(
+ team=team,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ status="running",
+ source_type="Stripe",
+ )
+ credential = DataWarehouseCredential.objects.create(access_key="x", access_secret="y", team=team)
+ table = DataWarehouseTable.objects.create(
+ name="charge",
+ format="Parquet",
+ team=team,
+ external_data_source=source,
+ external_data_source_id=source.id,
+ credential=credential,
+ url_pattern="https://bucket.s3/data/*",
+ columns={},
+ )
+ schema = ExternalDataSchema.objects.create(name="Charge", team=team, source=source, table=table)
+ job = ExternalDataJob.objects.create(
+ team=team,
+ pipeline=source,
+ schema=schema,
+ status=ExternalDataJob.Status.RUNNING,
+ rows_synced=29,
+ )
+ return team, schema, job
+
+
+def test_calculate_table_size_does_not_clobber_concurrent_completion():
+ """Regression: the activity reads the job while it is RUNNING, then saves after a
+ slow S3 size lookup. In V3 the standalone consumer can mark the job COMPLETED in
+ that window. A full save would rewind status to RUNNING (and clear finished_at);
+ the scoped save must leave status/finished_at intact while still writing
+ storage_delta_mib."""
+ team, schema, job = _setup()
+
+ original_save = ExternalDataJob.save
+ completed_at = datetime(2026, 5, 29, 2, 57, 8, tzinfo=UTC)
+
+ def save_with_concurrent_completion(self, *args, **kwargs):
+ # Simulate the consumer completing the job between the activity's read and its save.
+ ExternalDataJob.objects.filter(id=self.id).update(
+ status=ExternalDataJob.Status.COMPLETED, finished_at=completed_at
+ )
+ return original_save(self, *args, **kwargs)
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.workflow_activities.calculate_table_size.get_size_of_folder",
+ return_value=1.0,
+ ),
+ patch.object(ExternalDataJob, "save", autospec=True, side_effect=save_with_concurrent_completion),
+ ):
+ calculate_table_size_activity(
+ CalculateTableSizeActivityInputs(team_id=team.pk, schema_id=str(schema.id), job_id=str(job.id))
+ )
+
+ refreshed = ExternalDataJob.objects.get(id=job.id)
+ assert refreshed.status == ExternalDataJob.Status.COMPLETED
+ assert refreshed.finished_at == completed_at
+ assert refreshed.storage_delta_mib == 1.0