: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): start v2 post-import steps via post-import workflow (#75880)
estefania3852e6800495
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 8e58b142acf1..62612073be70 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@@ -49,6 +49,11 @@ from products.warehouse_sources.backend.temporal.data_imports.metrics import (get_data_import_finished_metric,get_v3_lock_skipped_metric,)+from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ PostImportWorkflow,+ PostImportWorkflowInputs,+ build_post_import_workflow_id,+)from products.warehouse_sources.backend.temporal.data_imports.row_tracking import finish_row_tracking, get_rowsfrom products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (@@ -413,6 +418,8 @@ class ExternalDataJobWorkflow(PostHogWorkflow):source_type = Noneconsumer_manages_job_status = False+ skip_post_import_activities = False+ workflow_starts_post_import = Falseis_v3 = Falselock_token = None@@ -591,14 +598,20 @@ 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.+ # The load-dependent post-import steps have one home: `data-import-post-import`+ # (post_import_job.py). V3 with batches: the load consumer starts it after the final+ # batch is loaded, so the steps must not race the load from here. Everywhere else:+ # this workflow starts it in the finally block, after the COMPLETED status write its+ # resolve activity gates on. 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 (which still runs the steps inline below).consumer_runs_post_import = consumer_manages_job_status and workflow.patched("v3-consumer-post-import-2026-07")+ workflow_starts_post_import = not consumer_runs_post_import and workflow.patched(+ "v2-post-import-workflow-2026-07"+ )+ post_import_in_workflow = consumer_runs_post_import or workflow_starts_post_importif pipeline_result.get("should_trigger_cdp_producer", False):await start_child_workflow(@@ -633,7 +646,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):source_type is not Noneand schema_name is not Noneand emit_signals_enabled- and not consumer_runs_post_import+ and not post_import_in_workflow):# 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.@@ -695,7 +708,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 and not consumer_runs_post_import:+ if enrichment_needed and not post_import_in_workflow:try:await workflow.start_child_workflow(EnrichTableSemanticsWorkflow.run,@@ -721,7 +734,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 and not consumer_runs_post_import:+ if statistics_needed and not post_import_in_workflow:try:await workflow.start_child_workflow(ComputeTableStatisticsWorkflow.run,@@ -749,7 +762,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=2),)- if not consumer_runs_post_import:+ if not post_import_in_workflow:await workflow.execute_activity(calculate_table_size_activity,CalculateTableSizeActivityInputs(@@ -860,6 +873,8 @@ class ExternalDataJobWorkflow(PostHogWorkflow):# Release the V3 pipeline lock when the consumer is NOT managing job# status (extraction failed before producing batches, or non-V3).# When consumer_manages_job_status is True, the consumer releases.+ # Runs before the post-import start so a raise there (cancellation)+ # can't leave the lock held.if is_v3 and lock_token and not consumer_manages_job_status:try:await workflow.execute_activity(@@ -877,3 +892,33 @@ class ExternalDataJobWorkflow(PostHogWorkflow):"Failed to release V3 pipeline lock in workflow finally block",extra={"schema_id": str(inputs.external_data_schema_id)},)++ # Post-import must start after the COMPLETED write above: its resolve activity+ # skips every step for a non-completed job. Excluded paths keep their pre-fork+ # behavior — externally managed schemas (skip_post_import_activities) and+ # non-COMPLETED outcomes never ran these steps here either.+ if (+ workflow_starts_post_import+ and not skip_post_import_activities+ and update_inputs.status == ExternalDataJob.Status.COMPLETED+ and update_inputs.job_id is not None+ ):+ try:+ await workflow.start_child_workflow(+ PostImportWorkflow.run,+ PostImportWorkflowInputs(+ team_id=inputs.team_id,+ job_id=update_inputs.job_id,+ schema_id=str(inputs.external_data_schema_id),+ source_id=str(inputs.external_data_source_id),+ ),+ id=build_post_import_workflow_id(update_inputs.job_id),+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,+ parent_close_policy=ParentClosePolicy.ABANDON,+ )+ except WorkflowAlreadyStartedError:+ workflow.logger.info(+ "Post-import workflow already started for job, skipping",+ extra={"job_id": update_inputs.job_id},+ )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 bca3e6e3b761..bdd08e238a3a 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@@ -526,11 +526,10 @@ def _trigger_ducklake_register_data_imports(export_signal: ExportSignalMessage,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+ V2 starts the same workflow from `external-data-job` after the COMPLETED status+ write, 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`: thestart only happens when this `*_load` deployment has Temporal client env varsconfigured; any failure is logged and captured without failing the load."""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.pyindex da90e1a08d1a..d870f0d892db 100644--- a/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py@@ -1,12 +1,13 @@-"""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`.+"""Post-import Temporal workflow for data imports.++The single home for the post-import steps that read the loaded table (signal emission,+semantic enrichment, column statistics, table size, DuckLake copy). On V3 the+`external-data-job` workflow ends at extraction: batches land on S3 and a separate load+consumer writes them into Delta Lake, so these steps can't run from that workflow+without racing the load — the load consumer starts this workflow after the final batch+is loaded and the job is completed (see pipelines/pipeline_v3/load/processor.py). On V2+(and zero-batch V3), `external-data-job` starts this workflow after writing the+COMPLETED job status."""import jsondiff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.pyindex a0f623b6c886..7d8ea9dc34c8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSTATUS_TABLE,STATUS_VIEW,)+from products.warehouse_sources.backend.temporal.data_imports.post_import_job import PostImportWorkflowfrom products.warehouse_sources.backend.temporal.data_imports.settings import ACTIVITIESBUCKET_NAME = "test-pipeline"@@ -224,7 +225,7 @@ async def run_external_data_job_workflow(async with Worker(activity_environment.client,task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,- workflows=[ExternalDataJobWorkflow],+ workflows=[ExternalDataJobWorkflow, PostImportWorkflow],activities=ACTIVITIES, # type: ignoreworkflow_runner=UnsandboxedWorkflowRunner(),activity_executor=ThreadPoolExecutor(max_workers=50),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 c5fb501ea659..e5d12b058fdd 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@@ -31,6 +31,7 @@ from dlt.common.configuration.specs.aws_credentials import AwsCredentialsfrom dlt.sources.helpers.rest_client.client import RESTClientfrom stripe import ListObjectfrom temporalio.common import RetryPolicy+from temporalio.service import RPCError, RPCStatusCodefrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker@@ -80,6 +81,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineBATCH_TABLE,PendingBatch,)+from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ PostImportWorkflow,+ build_post_import_workflow_id,+)from products.warehouse_sources.backend.temporal.data_imports.row_tracking import get_rowsfrom products.warehouse_sources.backend.temporal.data_imports.settings import ACTIVITIESfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry@@ -648,6 +653,7 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, mocCDPProducerJobWorkflow,DuckLakeCopyDataImportsWorkflow,DuckLakeRegisterDataImportsWorkflow,+ PostImportWorkflow,],activities=ACTIVITIES + DUCKLAKE_ACTIVITIES, # type: ignoreworkflow_runner=UnsandboxedWorkflowRunner(),@@ -663,6 +669,23 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, mocretry_policy=RetryPolicy(maximum_attempts=1),)+ # The load-dependent post-import steps run in an abandoned child, so+ # assertions on its side effects (e.g. storage_delta_mib) would race+ # worker shutdown — await it before leaving the worker context. Absent+ # on paths that never start it (V3 consumer-owned, non-completed jobs).+ job = await sync_to_async(+ ExternalDataJob.objects.filter(team_id=inputs.team_id, schema_id=inputs.external_data_schema_id)+ .order_by("-created_at")+ .first+ )()+ if job is not None:+ handle = activity_environment.client.get_workflow_handle(build_post_import_workflow_id(str(job.id)))+ try:+ await handle.result()+ except RPCError as e:+ if e.status != RPCStatusCode.NOT_FOUND:+ raise+_STRIPE_JOB_INPUTS: dict[str, str | dict[str, str]] = {"auth_method": {"selection": "api_key", "stripe_secret_key": "test-key"},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.pyindex 04bf72f03389..8c6fb8cdf846 100644--- 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.py@@ -1,9 +1,12 @@"""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.+The load-dependent post-import steps run only in `data-import-post-import`: V3 runs+with batches rely on the load consumer to start it after the final batch loads, while+V2 (and zero-batch V3) start it from `external-data-job` after the COMPLETED status+write. If the workflow-side trigger is dropped, V2 syncs silently lose every step; if+it fires before the status write, the resolve activity skips them all; if it+over-applies, V3-with-batches double-triggers or externally managed schemas gain a+fan-out they never had."""import uuid@@ -52,7 +55,9 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie_JOB_ID = "01960000-0000-0000-0000-000000000000"-def _stub_activities(executed: list[str], *, is_v3: bool, consumer_manages_job_status: bool) -> list:+def _stub_activities(+ executed: list[str], *, is_v3: bool, consumer_manages_job_status: bool, skip_post_import_activities: bool = False+) -> list:@activity.defn(name="check_pipeline_version_activity")async def check_pipeline_version(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:executed.append("check_pipeline_version_activity")@@ -97,6 +102,7 @@ def _stub_activities(executed: list[str], *, is_v3: bool, consumer_manages_job_sreturn PipelineResult(should_trigger_cdp_producer=False,consumer_manages_job_status=consumer_manages_job_status,+ skip_post_import_activities=skip_post_import_activities,)@activity.defn(name="create_source_templates")@@ -125,14 +131,21 @@ def _stub_activities(executed: list[str], *, is_v3: bool, consumer_manages_job_s]-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)."""+async def _run_workflow(+ *, is_v3: bool, consumer_manages_job_status: bool, skip_post_import_activities: bool = False+) -> tuple[list[str], list[str]]:+ """Run the workflow with stubbed activities; return (executed activities + child starts in+ order, started child ids)."""executed: list[str] = []+ async def record_child_start(*args, **kwargs) -> None:+ executed.append(f"child:{kwargs['id']}")+with (mock.patch("products.warehouse_sources.backend.temporal.data_imports.external_data_job.workflow.start_child_workflow",new_callable=mock.AsyncMock,+ side_effect=record_child_start,) as mock_start_child,mock.patch("products.warehouse_sources.backend.temporal.data_imports.external_data_job.get_data_import_finished_metric"@@ -144,7 +157,10 @@ async def _run_workflow(*, is_v3: bool, consumer_manages_job_status: bool) -> tutask_queue="test-post-import-fork",workflows=[ExternalDataJobWorkflow],activities=_stub_activities(- executed, is_v3=is_v3, consumer_manages_job_status=consumer_manages_job_status+ executed,+ is_v3=is_v3,+ consumer_manages_job_status=consumer_manages_job_status,+ skip_post_import_activities=skip_post_import_activities,),workflow_runner=UnsandboxedWorkflowRunner(),activity_executor=ThreadPoolExecutor(max_workers=10),@@ -176,32 +192,52 @@ LOAD_DEPENDENT_CHILD_PREFIXES = (@pytest.mark.asyncio@pytest.mark.parametrize(- "is_v3,consumer_manages_job_status,expect_inline",+ "is_v3,consumer_manages_job_status,skip_post_import_activities,expect_post_import_child",[- # V2: everything runs inline, exactly as before the fork.- pytest.param(False, False, True, id="v2_runs_steps_inline"),+ # V2: the workflow starts data-import-post-import after the COMPLETED write.+ pytest.param(False, False, False, True, id="v2_starts_post_import_workflow"),# 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"),+ pytest.param(True, False, False, True, id="v3_zero_batches_starts_post_import_workflow"),+ # V3 with batches: the load consumer starts data-import-post-import; starting it here+ # too would race the consumer's load.+ pytest.param(True, True, False, False, id="v3_with_batches_leaves_trigger_to_consumer"),+ # Externally managed schemas never ran the post-import steps; the finally-block+ # trigger must not give them a fan-out.+ pytest.param(False, False, True, False, id="externally_managed_schema_gets_no_post_import"),],)-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)+async def test_post_import_fork(+ is_v3: bool,+ consumer_manages_job_status: bool,+ skip_post_import_activities: bool,+ expect_post_import_child: bool,+):+ executed, child_ids = await _run_workflow(+ is_v3=is_v3,+ consumer_manages_job_status=consumer_manages_job_status,+ skip_post_import_activities=skip_post_import_activities,+ )+ # The load-dependent steps never run inline in new executions — data-import-post-import+ # is their only home (the inline path survives solely for pre-patch replay).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)+ assert started == set()+ assert "calculate_table_size_activity" not in executed++ post_import_marker = f"child:data-import-post-import-{_JOB_ID}"+ if expect_post_import_child:+ # Must start after the COMPLETED write: the resolve activity skips every step+ # for a non-completed job, so the reverse order silently loses them all.+ assert executed.index("update_external_data_job_model") < executed.index(post_import_marker)else:- assert "calculate_table_size_activity" not in executed- assert started == set()+ assert post_import_marker not in executed++ if not skip_post_import_activities:# The person-property sync child reads extraction-staged chunks, not the loaded- # table, so it must keep starting from the workflow even on V3.+ # table, so it must keep starting from the workflow on every path.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+ # Steps that don't read the loaded table stay inline.+ assert "create_source_templates" in executed@pytest.mark.asyncio