: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
chore(warehouse-sources): route v2 pipeline post-load through shared orchestrator (#74746)
estefania2cc80c523cef
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.pyindex 319c9753fb4b..70ee1b491ebb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py@@ -1,4 +1,4 @@-from typing import TYPE_CHECKING, Any, Literal, Optional+from typing import TYPE_CHECKING, Any, Literal, Optional, Protocolfrom django.conf import settingsfrom django.db.models import F@@ -383,7 +383,6 @@ async def _publish_queryable_files(async def _finalize_sync_bookkeeping(job: ExternalDataJob,schema: ExternalDataSchema,- source: "ExternalDataSource",resource: "Optional[SourceResponse]",last_incremental_field_value: Any,logger: FilteringBoundLogger,@@ -396,9 +395,6 @@ async def _finalize_sync_bookkeeping(logger.debug("Updating last synced at timestamp on schema")await update_last_synced_at(job_id=str(job.id), schema_id=str(schema.id), team_id=job.team_id)- logger.debug("Notifying revenue analytics that sync has completed")- await notify_revenue_analytics_that_sync_has_completed(schema, source, logger)-if not schema.initial_sync_complete:await logger.adebug("Setting initial_sync_complete on schema")await set_initial_sync_complete(schema_id=schema.id, team_id=job.team_id)@@ -407,7 +403,35 @@ async def _finalize_sync_bookkeeping(await finalize_desc_sort_incremental_value(resource, schema, last_incremental_field_value, logger)-async def _register_tables_and_seed(+async def _register_table(+ job: ExternalDataJob,+ schema: ExternalDataSchema,+ row_count: int,+ table_schema_dict: dict[str, str],+ resource: "Optional[SourceResponse]",+ queryable_folder: str,+ logger: FilteringBoundLogger,+) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (+ validate_schema_and_update_table,+ )++ logger.debug("Validating schema and updating table")+ with POST_LOAD_DURATION_SECONDS.labels(operation="validate_schema").time():+ await validate_schema_and_update_table(+ run_id=str(job.id),+ team_id=job.team_id,+ schema_id=schema.id,+ table_schema_dict=table_schema_dict,+ row_count=row_count,+ queryable_folder=queryable_folder,+ table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ primary_keys=resource.primary_keys if resource is not None else None,+ )+ logger.debug("Finished validating schema and updating table")+++async def _run_cdc_post_load(job: ExternalDataJob,schema: ExternalDataSchema,source: "ExternalDataSource",@@ -415,7 +439,6 @@ async def _register_tables_and_seed(row_count: int,table_schema_dict: dict[str, str],resource_name: str,- resource: "Optional[SourceResponse]",queryable_folder: str,cdc_write_mode: Optional[str],is_cdc_companion: bool,@@ -423,7 +446,6 @@ async def _register_tables_and_seed() -> None:from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (register_cdc_companion_table,- validate_schema_and_update_table,)if is_cdc_companion:@@ -443,38 +465,10 @@ async def _register_tables_and_seed(logger.debug("Finished registering CDC companion table")return- # For cdc_only mode during the initial load, skip registering the consolidated- # DataWarehouseTable — only the _cdc companion table should be visible.- # The DeltaLake files still exist on S3 for the seeding step to read from.- is_cdc_only_initial = (- cdc_write_mode is None- and schema.sync_type == ExternalDataSchema.SyncType.CDC- and schema.cdc_table_mode == "cdc_only"- )-- if not is_cdc_only_initial:- logger.debug("Validating schema and updating table")- with POST_LOAD_DURATION_SECONDS.labels(operation="validate_schema").time():- await validate_schema_and_update_table(- run_id=str(job.id),- team_id=job.team_id,- schema_id=schema.id,- table_schema_dict=table_schema_dict,- row_count=row_count,- queryable_folder=queryable_folder,- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,- primary_keys=resource.primary_keys if resource is not None else None,- )- logger.debug("Finished validating schema and updating table")-# After the initial snapshot load for a CDC schema, seed the companion _cdc table# with the snapshot rows as synthetic INSERT events. Only fires when cdc_write_mode# is None (initial non-CDC load), NOT on every CDC consolidated streaming batch.- should_seed = (- cdc_write_mode is None- and schema.sync_type == ExternalDataSchema.SyncType.CDC- and schema.cdc_table_mode in ("cdc_only", "both")- )+ should_seed = cdc_write_mode is None and schema.cdc_table_mode in ("cdc_only", "both")logger.info("cdc_seed_check",should_seed=should_seed,@@ -494,17 +488,60 @@ async def _register_tables_and_seed(logger.info("Finished seeding CDC companion table from snapshot")-async def _sync_dependent_views(- schema: ExternalDataSchema, source: "ExternalDataSource", logger: FilteringBoundLogger+class PostLoadStep(Protocol):+ async def __call__(+ self,+ *,+ job: ExternalDataJob,+ schema: ExternalDataSchema,+ source: "ExternalDataSource",+ delta_table_helper: "DeltaTableHelper",+ is_cdc_companion: bool,+ logger: FilteringBoundLogger,+ ) -> None: ...+++async def _notify_revenue_analytics_step(+ *,+ job: ExternalDataJob,+ schema: ExternalDataSchema,+ source: "ExternalDataSource",+ delta_table_helper: "DeltaTableHelper",+ is_cdc_companion: bool,+ logger: FilteringBoundLogger,+) -> None:+ logger.debug("Notifying revenue analytics that sync has completed")+ await notify_revenue_analytics_that_sync_has_completed(schema, source, logger)+++async def _sync_revenue_analytics_views_step(+ *,+ job: ExternalDataJob,+ schema: ExternalDataSchema,+ source: "ExternalDataSource",+ delta_table_helper: "DeltaTableHelper",+ is_cdc_companion: bool,+ logger: FilteringBoundLogger,) -> None:logger.debug("Syncing revenue analytics views if needed")await database_sync_to_async_pool(sync_revenue_analytics_views)(schema, source)++async def _sync_engineering_analytics_views_step(+ *,+ job: ExternalDataJob,+ schema: ExternalDataSchema,+ source: "ExternalDataSource",+ delta_table_helper: "DeltaTableHelper",+ is_cdc_companion: bool,+ logger: FilteringBoundLogger,+) -> None:logger.debug("Syncing engineering analytics views if needed")await database_sync_to_async_pool(sync_engineering_analytics_views)(schema, source)-async def _maybe_flag_repartition(+async def _maybe_flag_repartition_step(+ *,job: ExternalDataJob,schema: ExternalDataSchema,source: "ExternalDataSource",@@ -527,6 +564,17 @@ async def _maybe_flag_repartition(await maybe_flag_for_repartition(schema, source, job, delta_table, logger)+# Product-facing side effects outside the core publish/register flow. Entries share the PostLoadStep+# signature so other products can eventually register theirs here instead of editing this module+# (see external_product_hooks.py for the registry pattern).+POST_LOAD_STEPS: tuple[PostLoadStep, ...] = (+ _notify_revenue_analytics_step,+ _sync_revenue_analytics_views_step,+ _sync_engineering_analytics_views_step,+ _maybe_flag_repartition_step,+)++async def run_post_load_operations(job: ExternalDataJob,schema: ExternalDataSchema,@@ -544,11 +592,11 @@ async def run_post_load_operations(Orchestrator that runs all post-load operations, in order:1. Delta maintenance (threshold-based for CDC schemas, unconditional compaction otherwise)2. Prepare S3 files for querying- 3. Sync bookkeeping (last_synced_at, revenue-ready notification, initial_sync_complete,- desc-sort incremental finalization)- 4. Validate schema and update table (or register/seed the CDC companion table)- 5. Sync dependent product views (revenue/engineering analytics)- 6. Repartition detection+ 3. Sync bookkeeping (last_synced_at, initial_sync_complete, desc-sort incremental finalization)+ 4. Register the table (skipped for CDC companion writes and cdc_only initial loads)+ 5. CDC post-load (companion registration or snapshot seeding), for CDC schemas only+ 6. POST_LOAD_STEPS: product side effects (revenue notification, revenue/engineering+ analytics views, repartition detection)Returns the queryable folder the table now serves from, or None when there is no delta table."""@@ -560,6 +608,7 @@ async def run_post_load_operations(# In this case we must NOT touch schema.table (the snapshot table) and must register the companion# table independently, otherwise we overwrite the snapshot queryable_folder with the SCD2 path.is_cdc_companion = cdc_write_mode == "scd2_append"+ is_cdc_schema = schema.sync_type == ExternalDataSchema.SyncType.CDCawait _run_delta_maintenance(schema, delta_table_helper, is_cdc_companion, logger)@@ -567,25 +616,39 @@ async def run_post_load_operations(job, schema, delta_table_helper, resource_name, is_cdc_companion, logger)- await _finalize_sync_bookkeeping(job, schema, source, resource, last_incremental_field_value, logger)+ await _finalize_sync_bookkeeping(job, schema, resource, last_incremental_field_value, logger)- await _register_tables_and_seed(- job=job,- schema=schema,- source=source,- delta_table_helper=delta_table_helper,- row_count=row_count,- table_schema_dict=table_schema_dict,- resource_name=resource_name,- resource=resource,- queryable_folder=queryable_folder,- cdc_write_mode=cdc_write_mode,- is_cdc_companion=is_cdc_companion,- logger=logger,- )+ # For cdc_only mode during the initial load, skip registering the consolidated+ # DataWarehouseTable — only the _cdc companion table should be visible.+ # The DeltaLake files still exist on S3 for the seeding step to read from.+ is_cdc_only_initial = cdc_write_mode is None and is_cdc_schema and schema.cdc_table_mode == "cdc_only"- await _sync_dependent_views(schema, source, logger)+ if not is_cdc_companion and not is_cdc_only_initial:+ await _register_table(job, schema, row_count, table_schema_dict, resource, queryable_folder, logger)- await _maybe_flag_repartition(job, schema, source, delta_table_helper, is_cdc_companion, logger)+ if is_cdc_companion or is_cdc_schema:+ await _run_cdc_post_load(+ job=job,+ schema=schema,+ source=source,+ delta_table_helper=delta_table_helper,+ row_count=row_count,+ table_schema_dict=table_schema_dict,+ resource_name=resource_name,+ queryable_folder=queryable_folder,+ cdc_write_mode=cdc_write_mode,+ is_cdc_companion=is_cdc_companion,+ logger=logger,+ )++ for step in POST_LOAD_STEPS:+ await step(+ job=job,+ schema=schema,+ source=source,+ delta_table_helper=delta_table_helper,+ is_cdc_companion=is_cdc_companion,+ logger=logger,+ )return queryable_folderdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.pyindex 2336c0b2bf3a..532cc8993735 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py@@ -22,7 +22,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.eadvance_xmin_state,cdp_producer_clear_chunks,cleanup_memory,- finalize_desc_sort_incremental_value,handle_corrupted_delta_log,handle_reset_or_full_refresh,persist_primary_keys,@@ -39,7 +38,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.ewrite_chunk_for_cdp_producer,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (- notify_revenue_analytics_that_sync_has_completed,+ run_post_load_operations,supports_partial_data_loading,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (@@ -54,10 +53,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.async_iterate import async_iteratefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducer-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import (- DeltaTableHelper,- is_transient_object_store_error,-)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import DeltaTableHelperfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.hogql_schema import HogQLSchemafrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import setup_partitioningfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (@@ -65,13 +61,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.per)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import record_source_item_statsfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult-from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (- sync_engineering_analytics_views,- sync_revenue_analytics_views,-)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (- set_initial_sync_complete,- update_last_synced_at,validate_schema_and_update_table,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -444,100 +434,19 @@ class PipelineNonDLT(Generic[ResumableData]):)async def _post_run_operations(self, row_count: int) -> str | None:- delta_table = await self._delta_table_helper.get_delta_table()-- if delta_table is None:- await self._logger.adebug("No deltalake table, not continuing with post-run ops")- return None-- await self._logger.adebug("Triggering compaction and vacuuming on delta table")- try:- await self._delta_table_helper.compact_table()- except Exception as e:- if is_transient_object_store_error(e):- # A rate-limited or connectivity blip compacting/vacuuming our own S3 bucket isn't a- # bug - the next sync's post-run compaction retries the same idempotent cleanup.- await self._logger.awarning(f"Compaction skipped: transient object-store error: {e}")- else:- capture_exception(e)- await self._logger.aexception(f"Compaction failed: {e}", exc_info=e)-- file_uris = await self._delta_table_helper.get_file_uris()- await self._logger.adebug(f"Preparing S3 files - total parquet files: {len(file_uris)}")-- folder_path = await database_sync_to_async_pool(self._job.folder_path)()- existing_queryable_folder = self._table.queryable_folder if self._table else None- queryable_folder = await prepare_s3_files_for_querying(- folder_path,- self._resource_name,- file_uris,- delete_existing=True,- existing_queryable_folder=existing_queryable_folder,+ return await run_post_load_operations(+ job=self._job,+ schema=self._schema,+ source=self._source,+ delta_table_helper=self._delta_table_helper,+ row_count=row_count,+ table_schema_dict=self._internal_schema.to_hogql_types(),+ resource_name=self._resource_name,logger=self._logger,+ last_incremental_field_value=self._last_incremental_field_value,+ resource=self._resource,)- await self._logger.adebug("Updating last synced at timestamp on schema")- await update_last_synced_at(job_id=self._job.id, schema_id=self._schema.id, team_id=self._job.team_id)-- if not self._schema.initial_sync_complete:- await self._logger.adebug("Setting initial_sync_complete on schema")- await set_initial_sync_complete(schema_id=self._schema.id, team_id=self._job.team_id)-- await self._logger.adebug("Notifying revenue analytics that sync has completed")- await notify_revenue_analytics_that_sync_has_completed(self._schema, self._source, self._logger)-- await finalize_desc_sort_incremental_value(- self._resource, self._schema, self._last_incremental_field_value, self._logger- )-- # For cdc_only mode, skip registering the consolidated DataWarehouseTable — only the- # _cdc companion table should be visible. The DeltaLake files still exist on S3 for- # the seeding step to read from.- if not (- self._schema.sync_type == ExternalDataSchema.SyncType.CDC and self._schema.cdc_table_mode == "cdc_only"- ):- await self._logger.adebug("Validating schema and updating table")- await validate_schema_and_update_table(- run_id=str(self._job.id),- team_id=self._job.team_id,- schema_id=self._schema.id,- table_schema_dict=self._internal_schema.to_hogql_types(),- row_count=row_count,- queryable_folder=queryable_folder,- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,- primary_keys=self._resource.primary_keys,- )- await self._logger.adebug("Finished validating schema and updating table")-- # Seed the _cdc companion table for CDC schemas (same logic as in run_post_load_operations- # for the V3 pipeline — the V2 pipeline calls validate_schema_and_update_table directly- # and doesn't go through run_post_load_operations).- if self._schema.sync_type == ExternalDataSchema.SyncType.CDC and self._schema.cdc_table_mode in (- "cdc_only",- "both",- ):- from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (- _seed_cdc_companion_from_snapshot,- )-- await self._logger.ainfo("Seeding CDC companion table from snapshot (V2 pipeline)")- await _seed_cdc_companion_from_snapshot(- schema=self._schema,- job=self._job,- source=self._source,- snapshot_delta_table_helper=self._delta_table_helper,- logger=self._logger,- )- await self._logger.ainfo("Finished seeding CDC companion table from snapshot")-- await self._logger.adebug("Syncing revenue analytics views")- await database_sync_to_async_pool(sync_revenue_analytics_views)(self._schema, self._source)-- await self._logger.adebug("Syncing engineering analytics views")- await database_sync_to_async_pool(sync_engineering_analytics_views)(self._schema, self._source)-- return queryable_folder-def _estimate_size(obj: Any) -> int:if isinstance(obj, dict):diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.pyindex f3b891e33149..afc783978a7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py@@ -4,9 +4,6 @@ from typing import castimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch-from parameterized import parameterized--from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLTfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -52,64 +49,30 @@ async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_impordelta_table_helper.get_delta_table.cache_pop.assert_called_once_with(delta_table_helper)-def _make_pipeline_for_post_run_operations() -> PipelineNonDLT:+async def test_post_run_operations_routes_through_shared_post_load():+ # The e2e tests mock `_post_run_operations`, so nothing else notices if this wrapper stops+ # returning the orchestrator's queryable folder (ducklake registration silently loses+ # `prepared_queryable_folder`) or stops forwarding the resource and last incremental value+ # (desc-sort cursor finalization silently skips).pipeline = PipelineNonDLT.__new__(PipelineNonDLT)pipeline._logger = AsyncMock()pipeline._delta_table_helper = AsyncMock()- pipeline._delta_table_helper.get_delta_table.return_value = MagicMock()- pipeline._delta_table_helper.get_file_uris.return_value = []pipeline._job = MagicMock(id=uuid.uuid4(), team_id=1)- pipeline._table = Nonepipeline._resource_name = "orders"pipeline._schema = MagicMock()- pipeline._schema.initial_sync_complete = True- # Non-CDC skips the CDC-companion-seeding block, so only validate_schema_and_update_table- # (mocked below) needs to be reachable.- pipeline._schema.sync_type = ExternalDataSchema.SyncType.INCREMENTAL- pipeline._schema.cdc_table_mode = "consolidated"pipeline._source = MagicMock()pipeline._resource = MagicMock()pipeline._internal_schema = MagicMock()- pipeline._last_incremental_field_value = None- return pipeline---def _fake_database_sync_to_async_pool(fn):- async def _inner(*args, **kwargs):- return fn(*args, **kwargs)-- return _inner---class TestPostRunOperationsCompactionErrorHandling:- # Regression: `_post_run_operations` used to call `capture_exception` for every compaction- # failure, including transient S3 rate-limit/connectivity blips that are already non-fatal- # (the sync completes regardless) — flooding error tracking with noise. A genuine compaction- # bug must still be captured.- @parameterized.expand(- [- ("transient_s3_slowdown", OSError("Generic S3 error: Please reduce your request rate."), False),- ("genuine_bug", OSError("Access Denied: not authorized"), True),- ]- )- @pytest.mark.asyncio- async def test_compaction_error_handling(self, _name: str, error: Exception, expect_capture: bool):- pipeline = _make_pipeline_for_post_run_operations()- cast(AsyncMock, pipeline._delta_table_helper.compact_table).side_effect = error-- with (- patch(f"{_PIPELINE_MODULE}.capture_exception") as mock_capture,- patch(f"{_PIPELINE_MODULE}.database_sync_to_async_pool", _fake_database_sync_to_async_pool),- patch(f"{_PIPELINE_MODULE}.prepare_s3_files_for_querying", AsyncMock(return_value="orders__query_1")),- patch(f"{_PIPELINE_MODULE}.update_last_synced_at", AsyncMock()),- patch(f"{_PIPELINE_MODULE}.notify_revenue_analytics_that_sync_has_completed", AsyncMock()),- patch(f"{_PIPELINE_MODULE}.finalize_desc_sort_incremental_value", AsyncMock()),- patch(f"{_PIPELINE_MODULE}.validate_schema_and_update_table", AsyncMock()),- ):- await pipeline._post_run_operations(row_count=10)-- assert mock_capture.called is expect_capture- if expect_capture:- cast(AsyncMock, pipeline._logger.aexception).assert_awaited_once()- else:- cast(AsyncMock, pipeline._logger.awarning).assert_awaited_once()+ pipeline._last_incremental_field_value = 5++ post_load = AsyncMock(return_value="orders__query_2")+ with patch(f"{_PIPELINE_MODULE}.run_post_load_operations", post_load):+ result = await pipeline._post_run_operations(row_count=10)++ assert result == "orders__query_2"+ assert post_load.await_args is not None+ kwargs = post_load.await_args.kwargs+ assert kwargs["resource"] is pipeline._resource+ assert kwargs["last_incremental_field_value"] == 5+ assert kwargs["row_count"] == 10