: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): restructure post-import workflow as a step list (#75945)
estefaniad9b629a0f9d0
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 d870f0d892db..279a89caf736 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@@ -8,6 +8,10 @@ without racing the load — the load consumer starts this workflow after the finis 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 theCOMPLETED job status.++Steps are declared in POST_IMPORT_STEPS: each entry carries its gate (evaluated in the+resolve activity, with DB access) and its workflow-side dispatch. The workflow body is+just a loop over the step keys the activity recorded."""import json@@ -86,8 +90,14 @@ class PostImportWorkflowInputs:@dataclasses.dataclass(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."""+ """Gating context resolved from the DB once the load has finished.++ `steps` is the ordered list of POST_IMPORT_STEPS keys to run, computed by the resolve+ activity so the workflow's command sequence derives from recorded history only. None+ means the context predates the step list (an in-flight pre-deploy run) — the workflow+ then falls back to deriving the same sequence from the legacy boolean fields, which+ stay populated for that reason.+ """source_type: str | None = Noneschema_name: str | None = None@@ -97,6 +107,201 @@ class PostImportContext:emit_signals_enabled: bool = Falseenrichment_needed: bool = Falsestatistics_needed: bool = False+ steps: list[str] | None = None++[email protected](frozen=True)+class PostImportGateContext:+ """Activity-side inputs to the step gates. Never serialized: gates run inside+ resolve_post_import_context_activity with full DB access, and only the resulting+ step keys cross into the workflow."""++ team_id: int+ job: ExternalDataJob+ schema: ExternalDataSchema+ source_type: str+ team: Team | None+ ai_data_processing_approved: bool++[email protected](frozen=True)+class PostImportStep:+ """One load-dependent post-import step.++ `enabled` runs inside the resolve activity (normal Python: DB, feature flags);+ `start` runs inside the workflow and may only issue Temporal commands. Adding a step+ means adding one POST_IMPORT_STEPS entry. Removing or reordering one needs+ workflow.patched() discipline — in-flight runs have its key recorded, so replay must+ still issue its commands (see .claude/rules/temporal-workflow-versioning.md).+ """++ key: str+ enabled: typing.Callable[[PostImportGateContext], bool]+ start: typing.Callable[[PostImportWorkflowInputs, PostImportContext], typing.Awaitable[None]]+++def _emit_signals_gate(gate: PostImportGateContext) -> bool:+ return emit_signals_enabled_for(gate.team_id, gate.source_type, gate.schema.name, gate.ai_data_processing_approved)+++def _enrichment_gate(gate: PostImportGateContext) -> bool:+ # 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.+ return bool(+ gate.ai_data_processing_approved+ and gate.team is not None+ and enrichment_enabled(gate.team)+ and _enrichment_pending(gate.team_id, gate.schema.table, gate.schema)+ )+++def _statistics_gate(gate: PostImportGateContext) -> bool:+ return bool(+ gate.team is not None and statistics_enabled(gate.team) and _statistics_stale(gate.team_id, gate.schema.table)+ )+++def _always(gate: PostImportGateContext) -> bool:+ return True+++async def _start_emit_signals(inputs: PostImportWorkflowInputs, ctx: PostImportContext) -> None:+ # The gate guarantees these when the key is recorded; the guard is type narrowing only.+ if ctx.source_type is None or ctx.schema_name is None:+ return+ # 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.+ try:+ await workflow.start_child_workflow(+ "emit-data-import-signals",+ EmitSignalsActivityInputs(+ team_id=inputs.team_id,+ schema_id=uuid.UUID(inputs.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},+ )+++async def _start_semantic_enrichment(inputs: PostImportWorkflowInputs, ctx: PostImportContext) -> None:+ # 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.+ try:+ await workflow.start_child_workflow(+ EnrichTableSemanticsWorkflow.run,+ EnrichTableSemanticsInputs(team_id=inputs.team_id, schema_id=uuid.UUID(inputs.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},+ )+++async def _start_table_statistics(inputs: PostImportWorkflowInputs, ctx: PostImportContext) -> None:+ try:+ await workflow.start_child_workflow(+ ComputeTableStatisticsWorkflow.run,+ ComputeTableStatisticsInputs(team_id=inputs.team_id, schema_id=uuid.UUID(inputs.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},+ )+++async def _start_table_size(inputs: PostImportWorkflowInputs, ctx: PostImportContext) -> None:+ 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),+ )+++async def _start_ducklake_copy(inputs: PostImportWorkflowInputs, ctx: PostImportContext) -> None:+ try:+ await workflow.start_child_workflow(+ DuckLakeCopyDataImportsWorkflow.run,+ DataImportsDuckLakeCopyInputs(+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ schema_ids=[uuid.UUID(inputs.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},+ )+++EMIT_SIGNALS_STEP = "emit-signals"+SEMANTIC_ENRICHMENT_STEP = "semantic-enrichment"+TABLE_STATISTICS_STEP = "table-statistics"+TABLE_SIZE_STEP = "table-size"+DUCKLAKE_COPY_STEP = "ducklake-copy"++# Ordered registry of every post-import step. This is the future registration point for+# product-owned steps (external_product_hooks-style), so entries stay self-contained:+# gate on the activity side, commands on the workflow side, nothing in the workflow body.+POST_IMPORT_STEPS: tuple[PostImportStep, ...] = (+ PostImportStep(key=EMIT_SIGNALS_STEP, enabled=_emit_signals_gate, start=_start_emit_signals),+ PostImportStep(key=SEMANTIC_ENRICHMENT_STEP, enabled=_enrichment_gate, start=_start_semantic_enrichment),+ PostImportStep(key=TABLE_STATISTICS_STEP, enabled=_statistics_gate, start=_start_table_statistics),+ PostImportStep(key=TABLE_SIZE_STEP, enabled=_always, start=_start_table_size),+ PostImportStep(key=DUCKLAKE_COPY_STEP, enabled=_always, start=_start_ducklake_copy),+)++_STEP_BY_KEY = {step.key: step for step in POST_IMPORT_STEPS}+++def _legacy_step_keys(ctx: PostImportContext) -> list[str]:+ """The step sequence the pre-step-list workflow issued, derived from the legacy+ boolean fields. Replay fidelity: an in-flight run whose recorded context predates+ `steps` must produce exactly the commands the old code produced, in the same order —+ including the unconditional table-size and DuckLake steps on skip-all contexts."""+ keys = []+ if ctx.source_type is not None and ctx.schema_name is not None and ctx.emit_signals_enabled:+ keys.append(EMIT_SIGNALS_STEP)+ if ctx.enrichment_needed:+ keys.append(SEMANTIC_ENRICHMENT_STEP)+ if ctx.statistics_needed:+ keys.append(TABLE_STATISTICS_STEP)+ keys.append(TABLE_SIZE_STEP)+ keys.append(DUCKLAKE_COPY_STEP)+ return keys@activity.defn@@ -116,7 +321,7 @@ def resolve_post_import_context_activity(inputs: PostImportWorkflowInputs) -> Pojob_id=inputs.job_id,schema_id=inputs.schema_id,)- return PostImportContext()+ return PostImportContext(steps=[])# 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@@ -127,7 +332,7 @@ def resolve_post_import_context_activity(inputs: PostImportWorkflowInputs) -> Pojob_id=inputs.job_id,job_status=job.status,)- return PostImportContext()+ return PostImportContext(steps=[])source_type = schema.source.source_typesnapshot = job.schema_snapshot or {}@@ -141,27 +346,24 @@ def resolve_post_import_context_activity(inputs: PostImportWorkflowInputs) -> Po)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)+ gate_ctx = PostImportGateContext(+ team_id=inputs.team_id,+ job=job,+ schema=schema,+ source_type=source_type,+ team=team,+ ai_data_processing_approved=ai_data_processing_approved,)- statistics_needed = bool(team is not None and statistics_enabled(team) and _statistics_stale(inputs.team_id, table))+ steps = [step.key for step in POST_IMPORT_STEPS if step.enabled(gate_ctx)]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,+ emit_signals_enabled=EMIT_SIGNALS_STEP in steps,+ enrichment_needed=SEMANTIC_ENRICHMENT_STEP in steps,+ statistics_needed=TABLE_STATISTICS_STEP in steps,+ steps=steps,)@@ -183,95 +385,17 @@ class PostImportWorkflow(PostHogWorkflow):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),+ step_keys = ctx.steps if ctx.steps is not None else _legacy_step_keys(ctx)+ for key in step_keys:+ step = _STEP_BY_KEY.get(key)+ if step is None:+ # A newer worker's resolve activity recorded a key this worker doesn't+ # know yet (rolling deploy). Skipping is safe for a fresh run; a replay+ # that recorded the step's commands fails non-deterministic as any+ # removed command would.+ workflow.logger.warning(+ "Unknown post-import step, skipping",+ extra={"step": key, "job_id": inputs.job_id},)- 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},- )+ continue+ await step.start(inputs, ctx)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 8c6fb8cdf846..64fca1905cc0 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@@ -241,6 +241,16 @@ async def test_post_import_fork(@pytest.mark.asyncio+ "steps_mode",+ [+ # New runs dispatch from the step list the resolve activity recorded.+ pytest.param("activity", id="activity_step_list"),+ # In-flight pre-deploy runs have a context without `steps`; the legacy fallback+ # must reproduce the old command sequence or their replay breaks on deploy.+ pytest.param("legacy", id="legacy_fallback"),+ ],+)@pytest.mark.parametrize("gates_on",[@@ -248,10 +258,16 @@ async def test_post_import_fork(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.+async def test_post_import_workflow_runs_moved_steps(gates_on: bool, steps_mode: str):+ # If a step is dropped from the registry, V3 syncs silently lose it (there is no+ # other place it runs); if the gates are ignored, disabled products run. Both+ # dispatch paths must issue the same commands for the same gating.from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ DUCKLAKE_COPY_STEP,+ EMIT_SIGNALS_STEP,+ SEMANTIC_ENRICHMENT_STEP,+ TABLE_SIZE_STEP,+ TABLE_STATISTICS_STEP,PostImportContext,PostImportWorkflow,PostImportWorkflowInputs,@@ -259,6 +275,9 @@ async def test_post_import_workflow_runs_moved_steps(gates_on: bool):executed: list[str] = []+ gated_steps = [EMIT_SIGNALS_STEP, SEMANTIC_ENRICHMENT_STEP, TABLE_STATISTICS_STEP] if gates_on else []+ steps = None if steps_mode == "legacy" else [*gated_steps, TABLE_SIZE_STEP, DUCKLAKE_COPY_STEP]+@activity.defn(name="resolve_post_import_context_activity")async def resolve_context(inputs: PostImportWorkflowInputs) -> PostImportContext:return PostImportContext(@@ -268,6 +287,7 @@ async def test_post_import_workflow_runs_moved_steps(gates_on: bool):emit_signals_enabled=gates_on,enrichment_needed=gates_on,statistics_needed=gates_on,+ steps=steps,)@activity.defn(name="calculate_table_size_activity")@@ -351,6 +371,8 @@ def test_resolve_context_uses_pre_sync_watermark_from_snapshot(team, _no_close_ofrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.temporal.data_imports.post_import_job import (+ DUCKLAKE_COPY_STEP,+ TABLE_SIZE_STEP,PostImportWorkflowInputs,resolve_post_import_context_activity,)@@ -372,13 +394,18 @@ def test_resolve_context_uses_pre_sync_watermark_from_snapshot(team, _no_close_oassert ctx.source_type == "Stripe"assert ctx.schema_name == "Customer"assert ctx.last_synced_at == pre_sync+ # The always-on steps must be recorded for a completed job (feature-gated steps are+ # off in the test environment); a None here would send new runs down the legacy path.+ assert ctx.steps is not None+ assert ctx.steps[-2:] == [TABLE_SIZE_STEP, DUCKLAKE_COPY_STEP]@pytest.mark.django_db@pytest.mark.parametrize("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.+ # must not fan out any step — steps=[] rather than None, or the workflow's legacy+ # fallback would still run table size and the DuckLake copy for it.from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.temporal.data_imports.post_import_job import (PostImportContext,@@ -398,4 +425,4 @@ def test_resolve_context_skips_all_steps_when_job_is_gone_or_not_completed(team,PostImportWorkflowInputs(team_id=team.pk, job_id=job_id, schema_id=str(schema.id), source_id=str(source.id)))- assert ctx == PostImportContext()+ assert ctx == PostImportContext(steps=[])