: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
feat(data-warehouse): trigger v3 post-import steps from load consumer (#75575)
estefaniaa3a9b73e20c1
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 f56d9cfc980f..3ad752b8319f 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@@ -588,6 +588,15 @@ class ExternalDataJobWorkflow(PostHogWorkflow):consumer_manages_job_status = pipeline_result.get("consumer_manages_job_status", False)skip_post_import_activities = pipeline_result.get("skip_post_import_activities", False)+ # V3 with batches: the load consumer starts `data-import-post-import` after the final+ # batch is loaded (see post_import_job.py / load/processor.py), so the load-dependent+ # steps below must not race the load from here. Gated on recorded history only:+ # consumer_manages_job_status is activity output, and patched() keeps in-flight+ # pre-patch executions replaying the old command sequence.+ consumer_runs_post_import = consumer_manages_job_status and workflow.patched(+ "v3-consumer-post-import-2026-07"+ )+if pipeline_result.get("should_trigger_cdp_producer", False):await start_child_workflow(workflow="dwh-cdp-producer-job",@@ -617,7 +626,12 @@ class ExternalDataJobWorkflow(PostHogWorkflow):# Emit signals for new records (if registered for this source type + schema), if FF enabled.# Fire-and-forget: runs on its own task queue so it doesn't block the import pipeline.- if source_type is not None and schema_name is not None and emit_signals_enabled:+ if (+ source_type is not None+ and schema_name is not None+ and emit_signals_enabled+ and not consumer_runs_post_import+ ):# Started by registered workflow name (not class import) so warehouse_sources# doesn't import the signals product, which depends on it. See external_product_hooks.await workflow.start_child_workflow(@@ -678,7 +692,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):# net and is idempotent. Keyed per schema so only one runs per schema at a time: a concurrent# sync gets WorkflowAlreadyStartedError, which we swallow. Fire-and-forget child on the# dedicated metadata queue; ABANDON means it never blocks or fails the import.- if enrichment_needed:+ if enrichment_needed and not consumer_runs_post_import:try:await workflow.start_child_workflow(EnrichTableSemanticsWorkflow.run,@@ -704,7 +718,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):# tries to start a second one gets WorkflowAlreadyStartedError, which we swallow (the running# one already covers this schema). The activity itself re-checks recency. Fire-and-forget# metadata queue; ABANDON so it never blocks or fails the import.- if statistics_needed:+ if statistics_needed and not consumer_runs_post_import:try:await workflow.start_child_workflow(ComputeTableStatisticsWorkflow.run,@@ -732,34 +746,35 @@ class ExternalDataJobWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=2),)- await workflow.execute_activity(- calculate_table_size_activity,- CalculateTableSizeActivityInputs(- team_id=inputs.team_id, schema_id=str(inputs.external_data_schema_id), job_id=job_id- ),- start_to_close_timeout=dt.timedelta(minutes=10),- retry_policy=RetryPolicy(maximum_attempts=3),- )-- # Start DuckLake copy workflow as a child (fire-and-forget)- try:- await workflow.start_child_workflow(- DuckLakeCopyDataImportsWorkflow.run,- DataImportsDuckLakeCopyInputs(- team_id=inputs.team_id,- job_id=job_id,- schema_ids=[inputs.external_data_schema_id],+ if not consumer_runs_post_import:+ await workflow.execute_activity(+ calculate_table_size_activity,+ CalculateTableSizeActivityInputs(+ team_id=inputs.team_id, schema_id=str(inputs.external_data_schema_id), job_id=job_id),- id=f"ducklake-copy-data-imports-{inputs.team_id}-{inputs.external_data_schema_id}",- task_queue=settings.DUCKLAKE_TASK_QUEUE,- parent_close_policy=workflow.ParentClosePolicy.ABANDON,- )- except WorkflowAlreadyStartedError:- workflow.logger.warning(- "DuckLake copy already running, skipping",- extra={"schema_id": str(inputs.external_data_schema_id)},+ start_to_close_timeout=dt.timedelta(minutes=10),+ retry_policy=RetryPolicy(maximum_attempts=3),)+ # Start DuckLake copy workflow as a child (fire-and-forget)+ try:+ await workflow.start_child_workflow(+ DuckLakeCopyDataImportsWorkflow.run,+ DataImportsDuckLakeCopyInputs(+ team_id=inputs.team_id,+ job_id=job_id,+ schema_ids=[inputs.external_data_schema_id],+ ),+ id=f"ducklake-copy-data-imports-{inputs.team_id}-{inputs.external_data_schema_id}",+ task_queue=settings.DUCKLAKE_TASK_QUEUE,+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ )+ except WorkflowAlreadyStartedError:+ workflow.logger.warning(+ "DuckLake copy already running, skipping",+ extra={"schema_id": str(inputs.external_data_schema_id)},+ )+prepared_queryable_folder = pipeline_result.get("prepared_queryable_folder")if prepared_queryable_folder and workflow.patched("data-imports-ducklake-registration-workflow-v1"):try:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.pyindex 42ddeabcf45c..bca3e6e3b761 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -12,6 +12,7 @@ import structlogimport pyarrow.compute as pcimport posthoganalyticsfrom asgiref.sync import async_to_sync+from temporalio.common import WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.exceptions_capture import capture_exception@@ -522,6 +523,77 @@ def _trigger_ducklake_register_data_imports(export_signal: ExportSignalMessage,capture_exception(e)+def _trigger_post_import_workflow(export_signal: ExportSignalMessage) -> None:+ """Fire-and-forget start of `data-import-post-import` after a V3 final batch lands.++ V2 runs the load-dependent post-import steps (signal emission, semantic enrichment,+ column statistics, table size, DuckLake copy) inline in `external-data-job`, but on+ V3 that workflow ends at extraction — the loaded table only exists once this+ consumer's post-load operations and job completion finish, so the trigger lives+ here instead. Same tolerance as `_trigger_ducklake_register_data_imports`: the+ start only happens when this `*_load` deployment has Temporal client env vars+ configured; any failure is logged and captured without failing the load.+ """+ if export_signal.cdc_write_mode == "scd2_append" or export_signal.sync_type == "cdc":+ # CDC finals land once per flush tick; running the post-import fan-out on every+ # tick would spam these steps continuously. This also mirrors the pre-existing+ # workflow behavior: CDC streaming schemas return early from `external-data-job`+ # with skip_post_import_activities, so these steps never ran per tick there+ # either. Deliberate gap, same as the DuckLake registration trigger above.+ return++ try:+ from posthog.temporal.common.client import async_connect++ from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ PostImportWorkflow,+ PostImportWorkflowInputs,+ build_post_import_workflow_id,+ )++ # Connect and start inside one event loop (see the DuckLake trigger above).+ # ALLOW_DUPLICATE_FAILED_ONLY keyed by job id: a redelivered final batch can't+ # double-run a completed post-import, but can retry a failed one.+ async def _start() -> None:+ temporal = await async_connect()+ await temporal.start_workflow(+ PostImportWorkflow.run,+ PostImportWorkflowInputs(+ team_id=export_signal.team_id,+ job_id=export_signal.job_id,+ schema_id=export_signal.schema_id,+ source_id=export_signal.source_id,+ ),+ id=build_post_import_workflow_id(export_signal.job_id),+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,+ )++ async_to_sync(_start)()+ logger.info(+ "post_import_workflow_started",+ team_id=export_signal.team_id,+ external_data_schema_id=export_signal.schema_id,+ external_data_job_id=export_signal.job_id,+ )+ except WorkflowAlreadyStartedError:+ logger.info(+ "post_import_workflow_already_started",+ team_id=export_signal.team_id,+ external_data_schema_id=export_signal.schema_id,+ external_data_job_id=export_signal.job_id,+ )+ except Exception as e:+ logger.error(+ "failed_to_start_post_import_workflow",+ team_id=export_signal.team_id,+ external_data_schema_id=export_signal.schema_id,+ external_data_job_id=export_signal.job_id,+ exc_info=True,+ )+ capture_exception(e)++def _promote_staged_cursor(export_signal: ExportSignalMessage) -> None:# Runs inside the completion transaction; failures roll it back so the batch retries.schema = ExternalDataSchema.objects.get(id=export_signal.schema_id, team_id=export_signal.team_id)@@ -644,6 +716,7 @@ def process_message(_mark_job_completed(export_signal)if prepared_queryable_folder:_trigger_ducklake_register_data_imports(export_signal, prepared_queryable_folder)+ _trigger_post_import_workflow(export_signal)returnlogger.debug(@@ -808,6 +881,8 @@ def process_message(if prepared_queryable_folder:_trigger_ducklake_register_data_imports(export_signal, prepared_queryable_folder)+ _trigger_post_import_workflow(export_signal)+logger.debug("post_load_operations_complete")mark_batch_as_processed(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.pyindex 37a332e844cd..b9c4f4549d78 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pyarrow as pafrom deltalake import DeltaTable, write_deltalakefrom parameterized import parameterized+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (CDC_OP_COLUMN,@@ -21,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_mark_job_completed,_promote_staged_cursor,_read_existing_rows_by_first_pk,+ _trigger_post_import_workflow,process_message,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.test_mocks import mock_delta_table@@ -463,6 +465,131 @@ class TestMarkJobCompleted:mock_release.assert_not_called()+class TestPostImportTrigger:+ """The V3 hand-off to `data-import-post-import`: without it the load-dependent+ post-import steps (signals, enrichment, statistics, table size, DuckLake copy)+ never run for V3 syncs."""++ @patch(f"{_PROCESSOR}.posthoganalytics")+ @patch(f"{_PROCESSOR}.mark_batch_as_processed")+ @patch(f"{_PROCESSOR}._trigger_post_import_workflow")+ @patch(f"{_PROCESSOR}._trigger_ducklake_register_data_imports")+ @patch(f"{_PROCESSOR}._mark_job_completed")+ @patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value="folder")+ @patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)+ @patch(f"{_PROCESSOR}.DeltaTableHelper")+ @patch(f"{_PROCESSOR}.ExternalDataJob")+ @patch(f"{_PROCESSOR}.s3fs")+ def test_final_batch_triggers_post_import_once(+ self,+ _s3fs: MagicMock,+ mock_job_model: MagicMock,+ mock_helper_cls: MagicMock,+ _already: MagicMock,+ _read: MagicMock,+ _post_load: AsyncMock,+ mock_mark_completed: MagicMock,+ _ducklake: MagicMock,+ mock_trigger: MagicMock,+ _mark_processed: MagicMock,+ _analytics: MagicMock,+ ) -> None:+ delta_table = MagicMock()+ delta_table.schema.return_value = pa.schema([pa.field("id", pa.int64())])+ delta_table.file_uris.return_value = []+ helper = mock_helper_cls.return_value+ helper.get_delta_table = AsyncMock(return_value=None)+ helper.write_to_deltalake = AsyncMock(return_value=delta_table)+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()++ process_message(_message(is_final_batch=True))++ mock_mark_completed.assert_called_once()+ mock_trigger.assert_called_once()++ @patch(f"{_PROCESSOR}.posthoganalytics")+ @patch(f"{_PROCESSOR}._trigger_post_import_workflow")+ @patch(f"{_PROCESSOR}._mark_job_completed")+ @patch(f"{_PROCESSOR}._run_post_load_for_already_processed_batch", return_value=None)+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)+ @patch(f"{_PROCESSOR}.DeltaTableHelper")+ @patch(f"{_PROCESSOR}.ExternalDataJob")+ @patch(f"{_PROCESSOR}.s3fs")+ def test_redelivered_final_batch_triggers_post_import(+ self,+ _s3fs: MagicMock,+ mock_job_model: MagicMock,+ _helper_cls: MagicMock,+ _already: MagicMock,+ _post_load: MagicMock,+ _mark_completed: MagicMock,+ mock_trigger: MagicMock,+ _analytics: MagicMock,+ ) -> None:+ # A writer crash between the final batch's Delta commit and the trigger means the+ # redelivery is the only chance to hand off — the trigger must fire on this path too.+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()++ process_message(_message(is_final_batch=True))++ mock_trigger.assert_called_once()++ @parameterized.expand(+ [+ ("cdc_sync_type", "cdc", None),+ ("scd2_companion_write", "incremental", "scd2_append"),+ ]+ )+ @patch("posthog.temporal.common.client.async_connect", new_callable=AsyncMock)+ def test_cdc_finals_do_not_trigger_post_import(+ self, _case: str, sync_type: str, cdc_write_mode: str | None, mock_connect: AsyncMock+ ) -> None:+ # CDC finals land once per flush tick; triggering per tick would spam the fan-out.+ signal = MagicMock()+ signal.sync_type = sync_type+ signal.cdc_write_mode = cdc_write_mode++ _trigger_post_import_workflow(signal)++ mock_connect.assert_not_called()++ @parameterized.expand(+ [+ # Any start failure (e.g. no Temporal env vars on the load deployment) must+ # not fail the load; it is logged and captured.+ ("start_failure_is_captured", RuntimeError("no temporal"), True),+ # An id collision means a prior delivery already started this job's run.+ ("already_started_is_benign", WorkflowAlreadyStartedError("wf-id", "wf-type"), False),+ ]+ )+ @patch(f"{_PROCESSOR}.capture_exception")+ @patch("posthog.temporal.common.client.async_connect", new_callable=AsyncMock)+ def test_trigger_failures_never_fail_the_load(+ self,+ _case: str,+ error: Exception,+ expect_captured: bool,+ mock_connect: AsyncMock,+ mock_capture: MagicMock,+ ) -> None:+ client = MagicMock()+ client.start_workflow = AsyncMock(side_effect=error)+ mock_connect.return_value = client++ signal = MagicMock()+ signal.sync_type = "incremental"+ signal.cdc_write_mode = None+ signal.team_id = 1+ signal.job_id = "job-1"+ signal.schema_id = "schema-1"+ signal.source_id = "source-1"++ _trigger_post_import_workflow(signal)++ assert mock_capture.called is expect_captured++# Regression guard for #70476: pyarrow 21+ string_view broke delta pushdown on string PKs.class TestEnrichCdcRows:"""Cross-batch CDC enrichment against a real local Delta table."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.pynew file mode 100644index 000000000000..da90e1a08d1a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py@@ -0,0 +1,276 @@+"""Post-import Temporal workflow for V3 data imports.++On V3 the `external-data-job` workflow ends at extraction: batches land on S3 and a+separate load consumer writes them into Delta Lake. The post-import steps that read the+loaded table (signal emission, semantic enrichment, column statistics, table size,+DuckLake copy) therefore can't run from that workflow without racing the load — the V3+load consumer starts this workflow after the final batch is loaded and the job is+completed (see pipelines/pipeline_v3/load/processor.py). V2 keeps running the same+steps inline from `external-data-job`.+"""++import json+import uuid+import typing+import datetime as dt+import dataclasses++from django.conf import settings+from django.db import close_old_connections++from structlog.contextvars import bind_contextvars+from temporalio import activity, workflow+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.workflow import ParentClosePolicy++from posthog.models.team.team import Team+from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.logger import get_logger+from posthog.temporal.ducklake.ducklake_copy_data_imports_workflow import (+ DataImportsDuckLakeCopyInputs,+ DuckLakeCopyDataImportsWorkflow,+)++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.temporal.data_imports.external_product_hooks import (+ EmitSignalsActivityInputs,+ emit_signals_enabled_for,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (+ CalculateTableSizeActivityInputs,+ calculate_table_size_activity,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.compute_table_statistics import (+ ComputeTableStatisticsInputs,+ ComputeTableStatisticsWorkflow,+ statistics_enabled,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (+ _enrichment_pending,+ _statistics_stale,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.enrich_table_semantics import (+ EnrichTableSemanticsInputs,+ EnrichTableSemanticsWorkflow,+ enrichment_enabled,+)++LOGGER = get_logger(__name__)+++def build_post_import_workflow_id(job_id: str) -> str:+ """Workflow id for a job's post-import run, keyed by job so a redelivered final+ batch coalesces with (or is rejected against) the run the first delivery started."""+ return f"data-import-post-import-{job_id}"++[email protected](frozen=True)+class PostImportWorkflowInputs:+ team_id: int+ job_id: str+ schema_id: str+ source_id: str++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {+ "team_id": self.team_id,+ "job_id": self.job_id,+ "schema_id": self.schema_id,+ "source_id": self.source_id,+ }++[email protected](frozen=True)+class PostImportContext:+ """Gating context resolved from the DB once the load has finished. Defaults are the+ skip values so a vanished job/schema (deleted mid-flight) skips every step."""++ source_type: str | None = None+ schema_name: str | None = None+ # Pre-sync watermark from the job's schema snapshot — by the time this workflow runs,+ # post-load bookkeeping has already advanced schema.last_synced_at to this sync.+ last_synced_at: str | None = None+ emit_signals_enabled: bool = False+ enrichment_needed: bool = False+ statistics_needed: bool = False+++def resolve_post_import_context_activity(inputs: PostImportWorkflowInputs) -> PostImportContext:+ bind_contextvars(team_id=inputs.team_id)+ logger = LOGGER.bind()+ close_old_connections()++ try:+ job = ExternalDataJob.objects.get(id=inputs.job_id, team_id=inputs.team_id)+ schema = ExternalDataSchema.objects.prefetch_related("source", "table").get(+ id=inputs.schema_id, team_id=inputs.team_id+ )+ except (ExternalDataJob.DoesNotExist, ExternalDataSchema.DoesNotExist):+ logger.warning(+ "Post-import context could not be resolved (job or schema deleted), skipping all steps",+ job_id=inputs.job_id,+ schema_id=inputs.schema_id,+ )+ return PostImportContext()++ # The consumer triggers after _mark_job_completed, but the Completed write is suppressed+ # when the job was cancelled after the final batch passed the gate — don't emit signals+ # or run the fan-out for a job that didn't actually complete.+ if job.status != ExternalDataJob.Status.COMPLETED:+ logger.info(+ "Post-import skipped: job is not completed",+ job_id=inputs.job_id,+ job_status=job.status,+ )+ return PostImportContext()++ source_type = schema.source.source_type+ snapshot = job.schema_snapshot or {}+ last_synced_at = snapshot.get("last_synced_at")++ team = (+ Team.objects.filter(id=inputs.team_id)+ .select_related("organization")+ .only("uuid", "organization_id", "organization__is_ai_data_processing_approved")+ .first()+ )+ ai_data_processing_approved = team is not None and team.organization.is_ai_data_processing_approved is True++ emit_signals = emit_signals_enabled_for(inputs.team_id, source_type, schema.name, ai_data_processing_approved)++ # Same gates create_external_data_job_model_activity applies for V2, but evaluated+ # post-register: columns this sync added are already visible, so enrichment picks+ # them up now instead of on the next sync. Both children re-check and are idempotent.+ table = schema.table+ enrichment_needed = bool(+ ai_data_processing_approved+ and team is not None+ and enrichment_enabled(team)+ and _enrichment_pending(inputs.team_id, table, schema)+ )+ statistics_needed = bool(team is not None and statistics_enabled(team) and _statistics_stale(inputs.team_id, table))++ return PostImportContext(+ source_type=source_type,+ schema_name=schema.name,+ last_synced_at=last_synced_at,+ emit_signals_enabled=emit_signals,+ enrichment_needed=enrichment_needed,+ statistics_needed=statistics_needed,+ )++[email protected](name="data-import-post-import")+class PostImportWorkflow(PostHogWorkflow):+ """Runs the load-dependent post-import steps for a completed V3 import job."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> PostImportWorkflowInputs:+ loaded = json.loads(inputs[0])+ return PostImportWorkflowInputs(**loaded)++ @workflow.run+ async def run(self, inputs: PostImportWorkflowInputs) -> None:+ ctx = await workflow.execute_activity(+ resolve_post_import_context_activity,+ inputs,+ start_to_close_timeout=dt.timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ schema_id = uuid.UUID(inputs.schema_id)++ # Started by registered workflow name (not class import) so warehouse_sources+ # doesn't import the signals product, which depends on it. See external_product_hooks.+ if ctx.source_type is not None and ctx.schema_name is not None and ctx.emit_signals_enabled:+ try:+ await workflow.start_child_workflow(+ "emit-data-import-signals",+ EmitSignalsActivityInputs(+ team_id=inputs.team_id,+ schema_id=schema_id,+ source_id=uuid.UUID(inputs.source_id),+ job_id=inputs.job_id,+ source_type=ctx.source_type,+ schema_name=ctx.schema_name,+ last_synced_at=ctx.last_synced_at,+ ),+ id=f"emit-data-import-signals-{inputs.job_id}",+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ # TBD: Signals are currently using video export queue as the main one, comment to clarify+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ parent_close_policy=ParentClosePolicy.ABANDON,+ execution_timeout=dt.timedelta(hours=2),+ )+ except WorkflowAlreadyStartedError:+ # A retried post-import run for the same job collides with the child the+ # first run started — that child already covers this job.+ workflow.logger.info(+ "Signal emission already running for job, skipping",+ extra={"job_id": inputs.job_id},+ )++ # Keyed per schema so only one runs per schema at a time; a collision means the+ # running one already covers this schema. Fire-and-forget on the metadata queue.+ if ctx.enrichment_needed:+ try:+ await workflow.start_child_workflow(+ EnrichTableSemanticsWorkflow.run,+ EnrichTableSemanticsInputs(team_id=inputs.team_id, schema_id=schema_id),+ id=f"enrich-warehouse-table-semantics-{inputs.schema_id}",+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,+ parent_close_policy=ParentClosePolicy.ABANDON,+ execution_timeout=dt.timedelta(minutes=30),+ )+ except WorkflowAlreadyStartedError:+ workflow.logger.info(+ "Semantic enrichment already running for schema, skipping",+ extra={"schema_id": inputs.schema_id},+ )++ if ctx.statistics_needed:+ try:+ await workflow.start_child_workflow(+ ComputeTableStatisticsWorkflow.run,+ ComputeTableStatisticsInputs(team_id=inputs.team_id, schema_id=schema_id),+ id=f"compute-warehouse-table-statistics-{inputs.schema_id}",+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,+ parent_close_policy=ParentClosePolicy.ABANDON,+ execution_timeout=dt.timedelta(minutes=30),+ )+ except WorkflowAlreadyStartedError:+ workflow.logger.info(+ "Column statistics already running for schema, skipping",+ extra={"schema_id": inputs.schema_id},+ )++ await workflow.execute_activity(+ calculate_table_size_activity,+ CalculateTableSizeActivityInputs(team_id=inputs.team_id, schema_id=inputs.schema_id, job_id=inputs.job_id),+ start_to_close_timeout=dt.timedelta(minutes=10),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ try:+ await workflow.start_child_workflow(+ DuckLakeCopyDataImportsWorkflow.run,+ DataImportsDuckLakeCopyInputs(+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ schema_ids=[schema_id],+ ),+ id=f"ducklake-copy-data-imports-{inputs.team_id}-{inputs.schema_id}",+ task_queue=settings.DUCKLAKE_TASK_QUEUE,+ parent_close_policy=ParentClosePolicy.ABANDON,+ )+ except WorkflowAlreadyStartedError:+ workflow.logger.warning(+ "DuckLake copy already running, skipping",+ extra={"schema_id": inputs.schema_id},+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/settings.py b/products/warehouse_sources/backend/temporal/data_imports/settings.pyindex cd65898cccfb..4fea98fdc94e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/settings.py@@ -22,6 +22,10 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_jobtrigger_schedule_buffer_one_activity,update_external_data_job_model,)+from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ PostImportWorkflow,+ resolve_post_import_context_activity,+)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (acquire_v3_pipeline_lock_activity,check_pipeline_version_activity,@@ -42,6 +46,7 @@ WORKFLOWS = [CDCExtractionWorkflow,CDCSlotCleanupWorkflow,DiscoverSchemasWorkflow,+ PostImportWorkflow,]ACTIVITIES = [@@ -61,4 +66,5 @@ ACTIVITIES = [acquire_v3_pipeline_lock_activity,release_v3_pipeline_lock_activity,maybe_repartition_table_activity,+ resolve_post_import_context_activity,]diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.pynew file mode 100644index 000000000000..04bf72f03389--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py@@ -0,0 +1,365 @@+"""The V2/V3 post-import fork in `external-data-job`.++V2 (and zero-batch V3) must keep running the load-dependent post-import steps inline;+V3 runs with batches must skip them, because the load consumer starts+`data-import-post-import` after the final batch loads. If the gate is dropped the+workflow races the consumer's load again; if it over-applies, V2 loses the steps.+"""++import uuid+from concurrent.futures import ThreadPoolExecutor++import pytest+from unittest import mock++from temporalio import activity+from temporalio.common import RetryPolicy+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.temporal.utils import ExternalDataWorkflowInputs++from products.warehouse_sources.backend.temporal.data_imports.external_data_job import (+ CreateSourceTemplateInputs,+ ExternalDataJobWorkflow,+ UpdateExternalDataJobStatusInputs,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (+ AcquireV3LockActivityInputs,+ AcquireV3LockActivityOutputs,+ CheckPipelineVersionActivityInputs,+ CheckPipelineVersionActivityOutputs,+ ReleaseV3LockActivityInputs,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (+ CalculateTableSizeActivityInputs,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.check_billing_limits import (+ CheckBillingLimitsActivityInputs,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (+ CreateExternalDataJobModelActivityInputs,+ CreateExternalDataJobModelActivityOutputs,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (+ ImportDataActivityInputs,+)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (+ RepartitionActivityInputs,+)++_JOB_ID = "01960000-0000-0000-0000-000000000000"+++def _stub_activities(executed: list[str], *, is_v3: bool, consumer_manages_job_status: bool) -> list:+ @activity.defn(name="check_pipeline_version_activity")+ async def check_pipeline_version(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:+ executed.append("check_pipeline_version_activity")+ return CheckPipelineVersionActivityOutputs(is_v3=is_v3)++ @activity.defn(name="acquire_v3_pipeline_lock_activity")+ async def acquire_lock(inputs: AcquireV3LockActivityInputs) -> AcquireV3LockActivityOutputs:+ executed.append("acquire_v3_pipeline_lock_activity")+ return AcquireV3LockActivityOutputs(acquired=True, token="token")++ @activity.defn(name="release_v3_pipeline_lock_activity")+ async def release_lock(inputs: ReleaseV3LockActivityInputs) -> None:+ executed.append("release_v3_pipeline_lock_activity")++ @activity.defn(name="create_external_data_job_model_activity")+ async def create_job(inputs: CreateExternalDataJobModelActivityInputs) -> CreateExternalDataJobModelActivityOutputs:+ executed.append("create_external_data_job_model_activity")+ return CreateExternalDataJobModelActivityOutputs(+ job_id=_JOB_ID,+ incremental_or_append=False,+ source_type="Stripe",+ schema_name="Customer",+ last_synced_at=None,+ emit_signals_enabled=True,+ enrichment_needed=True,+ statistics_needed=True,+ person_property_sync_enabled=True,+ )++ @activity.defn(name="check_billing_limits_activity")+ async def check_billing(inputs: CheckBillingLimitsActivityInputs) -> bool:+ executed.append("check_billing_limits_activity")+ return False++ @activity.defn(name="maybe_repartition_table_activity")+ async def maybe_repartition(inputs: RepartitionActivityInputs) -> None:+ executed.append("maybe_repartition_table_activity")++ @activity.defn(name="import_data_activity_sync")+ async def import_data(inputs: ImportDataActivityInputs) -> PipelineResult:+ executed.append("import_data_activity_sync")+ return PipelineResult(+ should_trigger_cdp_producer=False,+ consumer_manages_job_status=consumer_manages_job_status,+ )++ @activity.defn(name="create_source_templates")+ async def create_templates(inputs: CreateSourceTemplateInputs) -> None:+ executed.append("create_source_templates")++ @activity.defn(name="calculate_table_size_activity")+ async def calculate_table_size(inputs: CalculateTableSizeActivityInputs) -> None:+ executed.append("calculate_table_size_activity")++ @activity.defn(name="update_external_data_job_model")+ async def update_job(inputs: UpdateExternalDataJobStatusInputs) -> None:+ executed.append("update_external_data_job_model")++ return [+ check_pipeline_version,+ acquire_lock,+ release_lock,+ create_job,+ check_billing,+ maybe_repartition,+ import_data,+ create_templates,+ calculate_table_size,+ update_job,+ ]+++async def _run_workflow(*, is_v3: bool, consumer_manages_job_status: bool) -> tuple[list[str], list[str]]:+ """Run the workflow with stubbed activities; return (executed activities, started child ids)."""+ executed: list[str] = []++ with (+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.workflow.start_child_workflow",+ new_callable=mock.AsyncMock,+ ) as mock_start_child,+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.get_data_import_finished_metric"+ ),+ ):+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue="test-post-import-fork",+ workflows=[ExternalDataJobWorkflow],+ activities=_stub_activities(+ executed, is_v3=is_v3, consumer_manages_job_status=consumer_manages_job_status+ ),+ workflow_runner=UnsandboxedWorkflowRunner(),+ activity_executor=ThreadPoolExecutor(max_workers=10),+ ):+ await env.client.execute_workflow(+ ExternalDataJobWorkflow.run,+ ExternalDataWorkflowInputs(+ team_id=1,+ external_data_source_id=uuid.uuid4(),+ external_data_schema_id=uuid.uuid4(),+ billable=False,+ ),+ id=str(uuid.uuid4()),+ task_queue="test-post-import-fork",+ retry_policy=RetryPolicy(maximum_attempts=1),+ )++ child_ids = [call.kwargs["id"] for call in mock_start_child.call_args_list]+ return executed, child_ids+++LOAD_DEPENDENT_CHILD_PREFIXES = (+ "emit-data-import-signals-",+ "enrich-warehouse-table-semantics-",+ "compute-warehouse-table-statistics-",+ "ducklake-copy-data-imports-",+)+++ "is_v3,consumer_manages_job_status,expect_inline",+ [+ # V2: everything runs inline, exactly as before the fork.+ pytest.param(False, False, True, id="v2_runs_steps_inline"),+ # V3 with zero batches: the consumer never sees a final batch, so the workflow keeps ownership.+ pytest.param(True, False, True, id="v3_zero_batches_runs_steps_inline"),+ # V3 with batches: the load consumer starts data-import-post-import instead.+ pytest.param(True, True, False, id="v3_with_batches_skips_steps"),+ ],+)+async def test_post_import_fork(is_v3: bool, consumer_manages_job_status: bool, expect_inline: bool):+ executed, child_ids = await _run_workflow(is_v3=is_v3, consumer_manages_job_status=consumer_manages_job_status)++ started = {prefix for prefix in LOAD_DEPENDENT_CHILD_PREFIXES if any(c.startswith(prefix) for c in child_ids)}+ if expect_inline:+ assert "calculate_table_size_activity" in executed+ assert started == set(LOAD_DEPENDENT_CHILD_PREFIXES)+ else:+ assert "calculate_table_size_activity" not in executed+ assert started == set()+ # The person-property sync child reads extraction-staged chunks, not the loaded+ # table, so it must keep starting from the workflow even on V3.+ assert any(c.startswith("sync-warehouse-person-properties-") for c in child_ids)++ # Steps that don't read the loaded table stay inline on every path.+ assert "create_source_templates" in executed+++ "gates_on",+ [+ pytest.param(True, id="all_steps_gated_on"),+ pytest.param(False, id="gated_steps_skipped"),+ ],+)+async def test_post_import_workflow_runs_moved_steps(gates_on: bool):+ # If a moved step is dropped from data-import-post-import, V3 syncs silently lose it+ # (there is no other place it runs); if the gates are ignored, disabled products run.+ from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ PostImportContext,+ PostImportWorkflow,+ PostImportWorkflowInputs,+ )++ executed: list[str] = []++ @activity.defn(name="resolve_post_import_context_activity")+ async def resolve_context(inputs: PostImportWorkflowInputs) -> PostImportContext:+ return PostImportContext(+ source_type="Stripe",+ schema_name="Customer",+ last_synced_at="2026-07-01T00:00:00+00:00",+ emit_signals_enabled=gates_on,+ enrichment_needed=gates_on,+ statistics_needed=gates_on,+ )++ @activity.defn(name="calculate_table_size_activity")+ async def calculate_table_size(inputs: CalculateTableSizeActivityInputs) -> None:+ executed.append("calculate_table_size_activity")++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.post_import_job.workflow.start_child_workflow",+ new_callable=mock.AsyncMock,+ ) as mock_start_child:+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue="test-post-import-workflow",+ workflows=[PostImportWorkflow],+ activities=[resolve_context, calculate_table_size],+ workflow_runner=UnsandboxedWorkflowRunner(),+ activity_executor=ThreadPoolExecutor(max_workers=10),+ ):+ await env.client.execute_workflow(+ PostImportWorkflow.run,+ PostImportWorkflowInputs(+ team_id=1,+ job_id=_JOB_ID,+ schema_id=str(uuid.uuid4()),+ source_id=str(uuid.uuid4()),+ ),+ id=str(uuid.uuid4()),+ task_queue="test-post-import-workflow",+ retry_policy=RetryPolicy(maximum_attempts=1),+ )++ child_ids = [call.kwargs["id"] for call in mock_start_child.call_args_list]+ gated_prefixes = (+ "emit-data-import-signals-",+ "enrich-warehouse-table-semantics-",+ "compute-warehouse-table-statistics-",+ )+ started = {prefix for prefix in gated_prefixes if any(c.startswith(prefix) for c in child_ids)}+ assert started == (set(gated_prefixes) if gates_on else set())++ # Table size and the DuckLake copy run for every completed V3 import.+ assert executed == ["calculate_table_size_activity"]+ assert any(c.startswith("ducklake-copy-data-imports-") for c in child_ids)+++def _no_close_old_connections():+ # The activity reconnects stale worker connections; under pytest-django that would+ # close the test transaction's connection mid-test.+ with mock.patch("products.warehouse_sources.backend.temporal.data_imports.post_import_job.close_old_connections"):+ yield+++def _create_job(team, *, status, schema_snapshot, schema_last_synced_at):+ 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++ source = ExternalDataSource.objects.create(team=team, source_type="Stripe")+ schema = ExternalDataSchema.objects.create(+ team=team, name="Customer", source=source, last_synced_at=schema_last_synced_at+ )+ job = ExternalDataJob.objects.create(+ team=team,+ pipeline=source,+ schema=schema,+ status=status,+ schema_snapshot=schema_snapshot,+ rows_synced=0,+ )+ return source, schema, job+++def test_resolve_context_uses_pre_sync_watermark_from_snapshot(team, _no_close_old_connections):+ # By the time the post-import workflow runs, post-load bookkeeping has already advanced+ # schema.last_synced_at to this sync. Reading the live value instead of the job's+ # creation-time snapshot would filter the entire sync window out of signal emission.+ from datetime import UTC, datetime++ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+ from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ PostImportWorkflowInputs,+ resolve_post_import_context_activity,+ )++ pre_sync = "2026-07-01T00:00:00+00:00"+ source, schema, job = _create_job(+ team,+ status=ExternalDataJob.Status.COMPLETED,+ schema_snapshot={"last_synced_at": pre_sync},+ schema_last_synced_at=datetime(2026, 7, 30, tzinfo=UTC),+ )++ ctx = resolve_post_import_context_activity(+ PostImportWorkflowInputs(+ team_id=team.pk, job_id=str(job.id), schema_id=str(schema.id), source_id=str(source.id)+ )+ )++ assert ctx.source_type == "Stripe"+ assert ctx.schema_name == "Customer"+ assert ctx.last_synced_at == pre_sync++[email protected]("case", ["job_deleted", "job_not_completed"])+def test_resolve_context_skips_all_steps_when_job_is_gone_or_not_completed(team, case, _no_close_old_connections):+ # A cancelled job (Completed write suppressed after the final batch) or a deleted job+ # must not fan out signals/enrichment — the resolve activity returns the skip-all context.+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+ from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ PostImportContext,+ PostImportWorkflowInputs,+ resolve_post_import_context_activity,+ )++ source, schema, job = _create_job(+ team,+ status=ExternalDataJob.Status.FAILED if case == "job_not_completed" else ExternalDataJob.Status.COMPLETED,+ schema_snapshot={"last_synced_at": "2026-07-01T00:00:00+00:00"},+ schema_last_synced_at=None,+ )+ job_id = str(uuid.uuid4()) if case == "job_deleted" else str(job.id)++ ctx = resolve_post_import_context_activity(+ PostImportWorkflowInputs(team_id=team.pk, job_id=job_id, schema_id=str(schema.id), source_id=str(source.id))+ )++ assert ctx == PostImportContext()