Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(warehouse-sources): split run_post_load_operations into steps (#74671)

estefania5378395a4bed
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.py
index 56918abdaaeb..53f1b2ef2f1f 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
@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.metrics import POST_LOAD_DURATION_SECONDS
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import normalize_column_name
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (
sync_engineering_analytics_views,
@@ -250,15 +251,12 @@ async def _seed_cdc_companion_from_snapshot(
if total_rows == 0:
return
- file_uris = await companion_helper.get_file_uris()
-
await run_post_load_operations(
job=job,
schema=schema,
source=source,
delta_table_helper=companion_helper,
row_count=total_rows,
- file_uris=file_uris,
table_schema_dict=hogql_schema.to_hogql_types(),
resource_name=companion_resource_name,
logger=logger,
@@ -266,55 +264,15 @@ async def _seed_cdc_companion_from_snapshot(
)
-async def run_post_load_operations(
- job: ExternalDataJob,
+async def _run_delta_maintenance(
schema: ExternalDataSchema,
- source: "ExternalDataSource",
- delta_table_helper: "Optional[DeltaTableHelper]",
- row_count: int,
- file_uris: list[str],
- table_schema_dict: dict[str, str],
- resource_name: str,
+ delta_table_helper: "DeltaTableHelper",
+ is_cdc_companion: bool,
logger: FilteringBoundLogger,
- last_incremental_field_value: Any = None,
- resource: "Optional[SourceResponse]" = None,
- cdc_table_mode: Optional[str] = None,
- cdc_write_mode: Optional[str] = None,
) -> None:
- """
- Orchestrator function that runs all post-load operations:
- 1. Compact delta table (if exists)
- 2. Prepare S3 files for querying
- 3. Update last_synced_at timestamp
- 4. Notify revenue analytics (if applicable)
- 5. Finalize incremental field values
- 6. Validate schema and update table (or register CDC companion table)
- 7. Sync revenue analytics views (if applicable)
- """
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
- finalize_desc_sort_incremental_value,
- )
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import ( # noqa: PLC0415 — keeps the heavy deltalake dep off this module's top-level import path
is_transient_object_store_error,
)
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import build_table_name
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
- register_cdc_companion_table,
- update_last_synced_at,
- validate_schema_and_update_table,
- )
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
- POST_LOAD_DURATION_SECONDS,
- )
-
- if delta_table_helper is None or await delta_table_helper.get_delta_table() is None:
- logger.debug("No deltalake table, not continuing with post-run ops")
- return
-
- # Detect CDC companion writes — scd2_append writes always go to the companion _cdc resource.
- # 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"
if schema.is_cdc:
# CDC finals land once per tick per changed schema, so unconditional compaction would run
@@ -368,6 +326,17 @@ async def run_post_load_operations(
capture_exception(e)
logger.exception(f"Compaction failed: {e}", exc_info=e)
+
+async def _publish_queryable_files(
+ job: ExternalDataJob,
+ schema: ExternalDataSchema,
+ delta_table_helper: "DeltaTableHelper",
+ resource_name: str,
+ is_cdc_companion: bool,
+ logger: FilteringBoundLogger,
+) -> str:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import build_table_name
+
if is_cdc_companion:
# Look up the existing companion table's queryable_folder (not the main schema.table).
# build_table_name accesses job.pipeline (FK), so do it inside the sync wrapper.
@@ -393,9 +362,12 @@ async def run_post_load_operations(
lambda: schema.table.queryable_folder if schema.table else None
)()
+ # File URIs are listed after delta maintenance so the queryable folder serves the compacted
+ # layout rather than the pre-compaction small files.
+ file_uris = await delta_table_helper.get_file_uris()
logger.debug(f"Preparing S3 files - total parquet files: {len(file_uris)}")
with POST_LOAD_DURATION_SECONDS.labels(operation="prepare_s3").time():
- queryable_folder = await prepare_s3_files_for_querying(
+ return await prepare_s3_files_for_querying(
await database_sync_to_async_pool(job.folder_path)(),
resource_name,
file_uris,
@@ -404,6 +376,20 @@ async def run_post_load_operations(
logger=logger,
)
+
+async def _finalize_sync_bookkeeping(
+ job: ExternalDataJob,
+ schema: ExternalDataSchema,
+ source: "ExternalDataSource",
+ resource: "Optional[SourceResponse]",
+ last_incremental_field_value: Any,
+ logger: FilteringBoundLogger,
+) -> None:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
+ finalize_desc_sort_incremental_value,
+ )
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import update_last_synced_at
+
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)
@@ -417,6 +403,26 @@ async def run_post_load_operations(
if resource is not None:
await finalize_desc_sort_incremental_value(resource, schema, last_incremental_field_value, logger)
+
+async def _register_tables_and_seed(
+ job: ExternalDataJob,
+ schema: ExternalDataSchema,
+ source: "ExternalDataSource",
+ delta_table_helper: "DeltaTableHelper",
+ 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,
+ logger: FilteringBoundLogger,
+) -> 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:
logger.debug("Registering CDC companion table")
with POST_LOAD_DURATION_SECONDS.labels(operation="validate_schema").time():
@@ -432,73 +438,151 @@ async def run_post_load_operations(
set_as_schema_table=schema.cdc_table_mode == "cdc_only",
)
logger.debug("Finished registering CDC companion table")
- else:
- # 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"
- )
+ return
- 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")
- and delta_table_helper is not None
- )
- logger.info(
- "cdc_seed_check",
- should_seed=should_seed,
- cdc_write_mode=cdc_write_mode,
- sync_type=schema.sync_type,
- cdc_table_mode=schema.cdc_table_mode,
- has_delta_table_helper=delta_table_helper is not None,
- )
- if should_seed:
- logger.info("Seeding CDC companion table from snapshot")
- await _seed_cdc_companion_from_snapshot(
- schema=schema,
- job=job,
- source=source,
- snapshot_delta_table_helper=delta_table_helper,
- 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 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.info("Finished seeding CDC companion table from snapshot")
+ 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")
+ )
+ logger.info(
+ "cdc_seed_check",
+ should_seed=should_seed,
+ cdc_write_mode=cdc_write_mode,
+ sync_type=schema.sync_type,
+ cdc_table_mode=schema.cdc_table_mode,
+ )
+ if should_seed:
+ logger.info("Seeding CDC companion table from snapshot")
+ await _seed_cdc_companion_from_snapshot(
+ schema=schema,
+ job=job,
+ source=source,
+ snapshot_delta_table_helper=delta_table_helper,
+ logger=logger,
+ )
+ logger.info("Finished seeding CDC companion table from snapshot")
+
+async def _sync_dependent_views(
+ schema: ExternalDataSchema, source: "ExternalDataSource", logger: FilteringBoundLogger
+) -> None:
logger.debug("Syncing revenue analytics views if needed")
await database_sync_to_async_pool(sync_revenue_analytics_views)(schema, source)
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(
+ job: ExternalDataJob,
+ schema: ExternalDataSchema,
+ source: "ExternalDataSource",
+ delta_table_helper: "DeltaTableHelper",
+ is_cdc_companion: bool,
+ logger: FilteringBoundLogger,
+) -> None:
# Measure partition sizes and flag the table for an in-place repartition if a partition has grown
# past the memory-safe budget. CDC tables are excluded for now (their companion-table semantics
# need separate validation). Detection never raises — it must not break post-load.
- if not is_cdc_companion and schema.sync_type != ExternalDataSchema.SyncType.CDC:
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (
- maybe_flag_for_repartition,
- )
+ if is_cdc_companion or schema.sync_type == ExternalDataSchema.SyncType.CDC:
+ return
+
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (
+ maybe_flag_for_repartition,
+ )
+
+ delta_table = await delta_table_helper.get_delta_table()
+ if delta_table is not None:
+ await maybe_flag_for_repartition(schema, source, job, delta_table, logger)
+
+
+async def run_post_load_operations(
+ job: ExternalDataJob,
+ schema: ExternalDataSchema,
+ source: "ExternalDataSource",
+ delta_table_helper: "Optional[DeltaTableHelper]",
+ row_count: int,
+ table_schema_dict: dict[str, str],
+ resource_name: str,
+ logger: FilteringBoundLogger,
+ last_incremental_field_value: Any = None,
+ resource: "Optional[SourceResponse]" = None,
+ cdc_write_mode: Optional[str] = None,
+) -> Optional[str]:
+ """
+ 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
+
+ Returns the queryable folder the table now serves from, or None when there is no delta table.
+ """
+ if delta_table_helper is None or await delta_table_helper.get_delta_table() is None:
+ logger.debug("No deltalake table, not continuing with post-run ops")
+ return None
+
+ # Detect CDC companion writes — scd2_append writes always go to the companion _cdc resource.
+ # 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"
+
+ await _run_delta_maintenance(schema, delta_table_helper, is_cdc_companion, logger)
+
+ queryable_folder = await _publish_queryable_files(
+ 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 _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,
+ )
+
+ await _sync_dependent_views(schema, source, logger)
+
+ await _maybe_flag_repartition(job, schema, source, delta_table_helper, is_cdc_companion, logger)
- delta_table = await delta_table_helper.get_delta_table()
- if delta_table is not None:
- await maybe_flag_for_repartition(schema, source, job, delta_table, logger)
+ return queryable_folder
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/metrics.py
new file mode 100644
index 000000000000..35a876084ca0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/metrics.py
@@ -0,0 +1,8 @@
+from prometheus_client import Histogram
+
+POST_LOAD_DURATION_SECONDS = Histogram(
+ "warehouse_load_post_load_duration_seconds",
+ "Duration of post-load operations",
+ labelnames=["operation"],
+ buckets=(0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),
+)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
index aec4417cf55c..8c465534e2cb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
@@ -73,7 +73,6 @@ async def _run_post_load(
source=MagicMock(),
delta_table_helper=helper,
row_count=10,
- file_uris=["s3://bucket/orders/1.parquet"],
table_schema_dict={},
resource_name="orders",
logger=logger,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
index 94488cf2408b..3d29224a8082 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
@@ -25,13 +25,6 @@ PARQUET_READ_DURATION_SECONDS = Histogram(
buckets=(0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0),
)
-POST_LOAD_DURATION_SECONDS = Histogram(
- "warehouse_load_post_load_duration_seconds",
- "Duration of post-load operations",
- labelnames=["operation"],
- buckets=(0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),
-)
-
# TODO: the `team_id`/`schema_id` labels below are high cardinality — keep only for the gated rollout
# so we can debug per-team behaviour, then drop them before fully rolling out (per-team diagnosability
# is also covered by the `warehouse_repartition_*` capture events).
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.py
index 5d24175ce9c9..d550ec93b968 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
@@ -365,7 +365,6 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessag
source=schema.source,
delta_table_helper=delta_table_helper,
row_count=export_signal.total_rows or 0,
- file_uris=delta_table.file_uris(),
table_schema_dict=table_schema_dict,
resource_name=export_signal.resource_name,
logger=logger,
@@ -710,11 +709,9 @@ def process_message(
source=schema.source,
delta_table_helper=delta_table_helper,
row_count=export_signal.total_rows or 0,
- file_uris=delta_table.file_uris(),
table_schema_dict=internal_schema.to_hogql_types(),
resource_name=export_signal.resource_name,
logger=logger,
- cdc_table_mode=export_signal.cdc_table_mode,
cdc_write_mode=export_signal.cdc_write_mode,
)