: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
perf(data-warehouse): write the table size from the loader and drop the size activity (#113085)
Tom Owersd43f92fa2947
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 178f35c7ed61..189cfe8db486 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@@ -7,6 +7,7 @@ import pyarrow.compute as pcimport posthoganalyticsfrom structlog.types import FilteringBoundLogger+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.logger import get_logger@@ -45,6 +46,15 @@ if TYPE_CHECKING:LOGGER = get_logger(__name__)+@frozen+class PostLoadResult:+ #: The query folder the table now serves from. None when there is no Delta table.+ queryable_folder: str | None+ #: True when post-load recorded the table size from the Delta log. When False, the caller has+ #: to get the size measured in another way.+ table_size_written: bool = False++async def update_job_row_count(job_id: str, count: int, logger: FilteringBoundLogger) -> None:await logger.adebug(f"Updating rows_synced with +{count}")await database_sync_to_async_pool(@@ -409,7 +419,8 @@ async def _register_table(resource: "Optional[SourceResponse]",queryable_folder: str,logger: FilteringBoundLogger,-) -> None:+) -> bool:+ """Returns True when the table size from the Delta log went to the registration."""from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (validate_schema_and_update_table,)@@ -423,6 +434,9 @@ async def _register_table(live_row_count = (await delta_table_ref.get_live_row_count() if schema.table_row_count_is_cumulative or row_count == 0 else None)+ # Same handle, so the size is the size of the files the query folder now holds. Maintenance ran+ # before the publish step, so a compaction in this run is already in the number.+ live_size_mib = await delta_table_ref.get_live_size_mib()logger.debug("Validating schema and updating table")with POST_LOAD_DURATION_SECONDS.labels(operation="validate_schema").time():@@ -437,8 +451,10 @@ async def _register_table(primary_keys=resource.primary_keys if resource is not None else None,delta_schema_json=delta_schema_json,live_row_count=live_row_count,+ live_size_mib=live_size_mib,)logger.debug("Finished validating schema and updating table")+ return live_size_mib is not None@recorded_phase("cdc_post_load")@@ -474,6 +490,7 @@ async def _run_cdc_post_load(table_schema_dict=table_schema_dict,set_as_schema_table=schema.cdc_table_mode == "cdc_only",live_row_count=await delta_table_ref.get_live_row_count(),+ live_size_mib=await delta_table_ref.get_live_size_mib(),)logger.debug("Finished registering CDC companion table")return@@ -628,7 +645,7 @@ async def run_post_load_operations(last_incremental_field_value: Any = None,resource: "Optional[SourceResponse]" = None,cdc_write_mode: Optional[str] = None,-) -> Optional[str]:+) -> PostLoadResult:"""Orchestrator that runs all post-load operations, in order:1. Delta maintenance (compact when fragmented, otherwise vacuum on commit cadence)@@ -639,7 +656,8 @@ async def run_post_load_operations(6. POST_LOAD_STEPS: product side effects (revenue notification, revenue/engineeringanalytics views, repartition detection)- Returns the queryable folder the table now serves from, or None when there is no delta table.+ Returns the queryable folder the table now serves from (None when there is no delta table), and+ whether the register step recorded the table size."""if delta_table_ref is None or await delta_table_ref.get_delta_table() is None:# A clean run that wrote zero rows creates no delta table, so there is nothing to publish or@@ -648,7 +666,7 @@ async def run_post_load_operations(# initial-synced" on every subsequent run.logger.debug("No deltalake table; finalizing bookkeeping for a zero-row run")await _finalize_sync_bookkeeping(job, schema, resource, last_incremental_field_value, logger)- return None+ return PostLoadResult(queryable_folder=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@@ -672,8 +690,9 @@ async def run_post_load_operations(# 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"+ table_size_written = Falseif not is_cdc_companion and not is_cdc_only_initial:- await _register_table(+ table_size_written = await _register_table(job, schema, delta_table_ref, row_count, table_schema_dict, resource, queryable_folder, logger)@@ -695,4 +714,4 @@ async def run_post_load_operations(await _run_post_load_steps(job, schema, source, delta_table_ref, is_cdc_companion, logger)- return queryable_folder+ return PostLoadResult(queryable_folder=queryable_folder, table_size_written=table_size_written)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.pyindex 0655ebd27049..a3293026c75d 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@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.models.external_data_schema import Exterfrom products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errorsfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (IncrementalFieldMissingFromDataError,+ PostLoadResult,get_incremental_field_value,notify_revenue_analytics_that_sync_has_completed,run_post_load_operations,@@ -59,11 +60,14 @@ def _make_schema(return schema-def _make_helper(*, file_uris: list[str] | None = None, live_row_count: int | None = None) -> MagicMock:+def _make_helper(+ *, file_uris: list[str] | None = None, live_row_count: int | None = None, live_size_mib: float | None = None+) -> MagicMock:return MagicMock(get_delta_table=AsyncMock(return_value=MagicMock()),get_file_uris=AsyncMock(return_value=file_uris or []),get_live_row_count=AsyncMock(return_value=live_row_count),+ get_live_size_mib=AsyncMock(return_value=live_size_mib),)@@ -75,7 +79,9 @@ async def _run_post_load(resource: Optional[MagicMock] = None,stored_sync_type_config: dict | None = None,validate: AsyncMock | None = None,+ register_companion: AsyncMock | None = None,row_count: int = 10,+ results: list[PostLoadResult] | None = None,) -> tuple[AsyncMock, AsyncMock]:job = MagicMock()job.id = uuid.uuid4()@@ -95,10 +101,10 @@ async def _run_post_load(patch.object(DeltaMaintenance, "run_scheduled", run_scheduled),patch(f"{_PIPELINE_SYNC_MODULE}.update_last_synced_at", AsyncMock()),patch(f"{_PIPELINE_SYNC_MODULE}.validate_schema_and_update_table", validate or AsyncMock()),- patch(f"{_PIPELINE_SYNC_MODULE}.register_cdc_companion_table", AsyncMock()),+ patch(f"{_PIPELINE_SYNC_MODULE}.register_cdc_companion_table", register_companion or AsyncMock()),patch(f"{_REPARTITION_MODULE}.maybe_flag_for_repartition", AsyncMock()),):- await run_post_load_operations(+ result = await run_post_load_operations(job=job,schema=schema,source=MagicMock(),@@ -110,6 +116,8 @@ async def _run_post_load(resource=resource,cdc_write_mode=cdc_write_mode,)+ if results is not None:+ results.append(result)return run_scheduled, prepare_s3@@ -185,6 +193,57 @@ class TestRegisterTableRowCount:assert validate.await_args.kwargs["live_row_count"] == expected+class TestPostLoadTableSize:+ @parameterized.expand(+ [+ ("size_from_the_log", False, None, 12.5, True),+ ("empty_table", False, None, 0.0, True),+ # The post-import workflow must still measure a table whose log gave no size.+ ("no_size_from_the_log", False, None, None, False),+ ("cdc_main_table", True, "incremental_merge", 12.5, True),+ ]+ )+ @pytest.mark.asyncio+ async def test_registers_the_log_size_and_reports_whether_it_was_written(+ self, _name: str, is_cdc: bool, cdc_write_mode: str | None, live_size_mib: float | None, expect_written: bool+ ) -> None:+ schema = _make_schema(is_cdc=is_cdc)+ validate = AsyncMock()+ results: list[PostLoadResult] = []++ await _run_post_load(+ schema,+ _make_helper(live_size_mib=live_size_mib),+ cdc_write_mode=cdc_write_mode,+ validate=validate,+ results=results,+ )++ assert validate.await_args is not None+ assert validate.await_args.kwargs["live_size_mib"] == live_size_mib+ assert results == [PostLoadResult(queryable_folder="orders__query_1", table_size_written=expect_written)]++ @pytest.mark.asyncio+ async def test_a_companion_write_sizes_the_companion_and_not_the_main_table(self) -> None:+ # The companion is a different Delta table. Its size on the main table would replace the+ # size of the snapshot data.+ schema = _make_schema(is_cdc=True, cdc_table_mode="both")+ validate = AsyncMock()+ register_companion = AsyncMock()++ await _run_post_load(+ schema,+ _make_helper(live_size_mib=3.0),+ cdc_write_mode="scd2_append",+ validate=validate,+ register_companion=register_companion,+ )++ validate.assert_not_awaited()+ assert register_companion.await_args is not None+ assert register_companion.await_args.kwargs["live_size_mib"] == 3.0++_STEP_PHASES = ["notify_revenue_analytics","sync_revenue_analytics_views",@@ -354,7 +413,7 @@ class TestZeroRowRunFinalizesBookkeeping:logger=logger,)- assert result is None+ assert result == PostLoadResult(queryable_folder=None, table_size_written=False)set_complete.assert_awaited_once()synced.assert_awaited_once()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.pyindex 334a74f5cc9f..593feabc71b0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py@@ -176,6 +176,24 @@ def live_row_count(delta_table: deltalake.DeltaTable) -> int | None:return int(pc.sum(num_records).as_py() or 0)+def live_size_mib(delta_table: deltalake.DeltaTable) -> float | None:+ """Size of the table's live files in MiB, summed from the `size` of each Add action.++ The query folder holds a copy of exactly the live files, so this sum is the size of that folder,+ without a listing of it. The read takes the file sizes alone, not the per-column statistics.++ None when the log cannot give a size for each live file. The caller then leaves the recorded+ size as it is, because a partial sum would record a table as smaller than it is.+ """+ try:+ sizes = delta_table._table.get_add_file_sizes()+ except Exception:+ return None+ if any(size is None for size in sizes.values()):+ return None+ return sum(sizes.values()) / (1024 * 1024)++class DeltaTableRef:"""Handle to one schema's Delta table: uri/credentials, the cached open (with corrupt-tableauto-heal), corruption detection, reset, file listing, and the first-sync flag.@@ -470,3 +488,12 @@ class DeltaTableRef:if row_count is None:await self._logger.adebug("The Delta log has no complete row count, counting the published files")return row_count++ async def get_live_size_mib(self) -> float | None:+ """The size of the table's live files from the Delta log, or None when the log cannot give it+ (see `live_size_mib`)."""+ delta_table = await self.get_delta_table()+ if delta_table is None:+ return None++ return await asyncio.to_thread(live_size_mib, delta_table)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.pyindex 069dcad3b9d6..79786ec7647d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py@@ -28,11 +28,17 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delDeltaTableRef,_purge_s3_prefix,live_row_count,+ live_size_mib,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (make_local_table_ref,make_logger,)+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (+ _live_delta_size_mib,+)++_TABLE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table"def table_ref():@@ -578,6 +584,15 @@ def _upserted_with_deltalite(uri: str) -> None:deltalite.DeltaLiteTable.open(uri).upsert(_rows([3, 10, 11], "a"), primary_keys=["id"], partition_key="part")+def _overwritten_without_partitions(uri: str) -> None:+ deltalake.write_deltalake(uri, _rows([7], "c"), mode="overwrite")+++def _compacted_without_partitions(uri: str) -> None:+ deltalake.write_deltalake(uri, _rows([5, 6], "b"), mode="append")+ deltalake.DeltaTable(uri).optimize.compact()++def _compacted(uri: str) -> None:_appended(uri)deltalake.DeltaTable(uri).optimize.compact()@@ -655,6 +670,69 @@ class TestLiveRowCount:ref = make_local_table_ref(str(self.tmp_path / "missing"))assert await ref.get_live_row_count() is None+ assert await ref.get_live_size_mib() is None++ @parameterized.expand(+ [+ ("append_only", True, lambda uri: None),+ ("append", True, _appended),+ ("full_refresh", True, _overwritten),+ ("delete", True, _deleted_from),+ ("empty_table", True, _emptied),+ ("merge", True, _merged),+ ("deltalite_upsert", True, _upserted_with_deltalite),+ ("compaction", True, _compacted),+ ("vacuum", True, _vacuumed),+ ("unpartitioned", False, lambda uri: None),+ ("unpartitioned_full_refresh", False, _overwritten_without_partitions),+ ("unpartitioned_compaction", False, _compacted_without_partitions),+ ]+ )+ def test_size_matches_the_published_files_and_the_size_activity(+ self, _name: str, partitioned: bool, history: Callable[[str], None]+ ) -> None:+ # The loader records this number in place of the size activity, and billing sums it. It has+ # to be the bytes of the files the query folder holds, with no removed file counted.+ uri = self._create(self.tmp_path) if partitioned else self._create_unpartitioned(self.tmp_path)+ history(uri)+ table = deltalake.DeltaTable(uri)++ published_mib = sum(Path(path).stat().st_size for path in table.file_uris()) / (1024 * 1024)+ with patch(f"{_TABLE_MODULE}.delta_storage_options", return_value={}):+ activity_mib = _live_delta_size_mib(uri)++ assert live_size_mib(table) == published_mib == activity_mib++ @parameterized.expand(+ [+ ("a_file_without_a_size", MagicMock(return_value={"a.parquet": 10, "b.parquet": None})),+ ("an_unreadable_log", MagicMock(side_effect=Exception("Generic delta kernel error"))),+ ]+ )+ def test_no_size_when_the_log_cannot_give_every_file_size(self, _name: str, get_add_file_sizes: MagicMock) -> None:+ # None keeps the recorded size and leaves the measurement to the size activity. A partial+ # sum or a 0 would under-report the table.+ table = MagicMock()+ table._table.get_add_file_sizes = get_add_file_sizes++ assert live_size_mib(table) is None++ @pytest.mark.asyncio+ async def test_ref_reads_the_size_after_a_deltalite_commit(self) -> None:+ uri = self._create(self.tmp_path)+ ref = make_local_table_ref(uri)+ size_before = await ref.get_live_size_mib()++ deltalite.DeltaLiteTable.open(uri).upsert(_rows([10, 11], "a"), primary_keys=["id"], partition_key="part")+ ref.note_deltalite_commit(None)++ assert await ref.get_live_size_mib() == live_size_mib(deltalake.DeltaTable(uri)) != size_before++ @staticmethod+ def _create_unpartitioned(tmp_path: Path) -> str:+ uri = str(tmp_path / "t")+ deltalake.write_deltalake(uri, _rows([1, 2, 3, 4], "a"))+ return uri@pytest.fixture(autouse=True)def _tmp(self, tmp_path: Path) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.pyindex 9d92e7a127d8..b2fb23af79c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py@@ -8,6 +8,7 @@ from typing import Any, Optionalfrom django.db import transactionfrom django.db.models import Prefetch+from django.utils import timezoneimport dltimport pyarrow@@ -267,6 +268,28 @@ def _refresh_cumulative_row_count(logger.warning(f"Could not refresh cumulative row count for {context}, keeping previous value", exc_info=True)+def _storage_delta_mib(table: DataWarehouseTable | None, live_size_mib: Optional[float]) -> Optional[float]:+ if live_size_mib is None:+ return None+ previous_size_mib = (table.size_in_s3_mib or 0) if table is not None else 0+ return live_size_mib - previous_size_mib+++def _record_storage_delta(job: ExternalDataJob, storage_delta_mib: Optional[float]) -> None:+ if storage_delta_mib is None:+ return+ # One job can register more than once: a redelivered final batch runs post-load again, and a CDC+ # snapshot also seeds its companion table. Each registration adds its own change, so a second+ # pass that changes nothing does not erase the first.+ job.storage_delta_mib = (job.storage_delta_mib or 0) + storage_delta_mib+ # A queryset update does not raise when the job row was deleted during post-load.+ retry_on_db_connection_drop(+ lambda: ExternalDataJob.objects.filter(pk=job.pk).update(+ storage_delta_mib=job.storage_delta_mib, updated_at=timezone.now()+ )+ )++def own_linked_table(schema: ExternalDataSchema, pipeline: ExternalDataSource) -> DataWarehouseTable | None:"""The schema's linked table, unless the link is its `_cdc` companion.@@ -295,6 +318,7 @@ async def validate_schema_and_update_table(primary_keys: Optional[list[str]] = None,delta_schema_json: Optional[str] = None,live_row_count: Optional[int] = None,+ live_size_mib: Optional[float] = None,) -> None:"""Async version of validate_schema_and_update_table_sync.@@ -314,6 +338,9 @@ async def validate_schema_and_update_table(the column write are skipped; the pointer flip and the row count still happen.live_row_count: The row count of the published files, read from the Delta log. When given,it replaces the count of those files that a table needs when `row_count` is not its size.+ live_size_mib: The size of the published files, read from the Delta log. When given, it is+ recorded as the table's size and the change is added to the job's `storage_delta_mib`.+ When None, the recorded size stays as it is."""logger = LOGGER.bind(team_id=team_id)@@ -382,6 +409,7 @@ async def validate_schema_and_update_table(if table_created:table = table_createdprevious_queryable_folder = table.queryable_folder+ storage_delta_mib = _storage_delta_mib(table, live_size_mib)table.format = table_params["format"]table.url_pattern = new_url_patterntable.queryable_folder = queryable_folder@@ -396,12 +424,14 @@ async def validate_schema_and_update_table(# on a fresh connection rather than let this escape as error-tracking noise.# new_url_pattern above is derived from the job's own destination folder, not from# request input, so this sync is a trusted writer of a credential-less table's URL.+ update_fields = ["format", "url_pattern", "queryable_folder", "row_count"]+ if live_size_mib is not None:+ table.size_in_s3_mib = live_size_mib+ update_fields.append("size_in_s3_mib")retry_on_db_connection_drop(- lambda: table.save(- update_fields=["format", "url_pattern", "queryable_folder", "row_count"],- internally_computed_url_pattern=True,- )+ lambda: table.save(update_fields=update_fields, internally_computed_url_pattern=True))+ _record_storage_delta(job, storage_delta_mib)_record_query_folder_pointer(_schema_id, team_id, previous_queryable_folder, queryable_folder, run_id, logger)@@ -411,8 +441,10 @@ async def validate_schema_and_update_table(table = DataWarehouseTable.objects.create(external_data_source_id=job.pipeline.id,created_via=DataWarehouseTableCreatedVia.SOURCE,+ size_in_s3_mib=live_size_mib,**table_params,)+ _record_storage_delta(job, _storage_delta_mib(None, live_size_mib))_record_query_folder_pointer(_schema_id, team_id, None, queryable_folder, run_id, logger)if row_count == 0:# table_params holds 0 for a table an earlier attempt already filled. get_count()@@ -528,6 +560,7 @@ async def register_cdc_companion_table(table_schema_dict: Optional[dict[str, str]] = None,set_as_schema_table: bool = False,live_row_count: Optional[int] = None,+ live_size_mib: Optional[float] = None,) -> None:"""Create or update a standalone DataWarehouseTable for a CDC companion resource (e.g. `{schema_name}_cdc`).@@ -574,6 +607,7 @@ async def register_cdc_companion_table().first()previous_queryable_folder = companion_table.queryable_folder if companion_table else None+ storage_delta_mib = _storage_delta_mib(companion_table, live_size_mib)if companion_table:table = companion_tabletable.format = table_format@@ -587,19 +621,22 @@ async def register_cdc_companion_table(# on a fresh connection rather than let this escape as error-tracking noise.# new_url_pattern above is derived from the job's own destination folder, not from# request input, so this sync is a trusted writer of a credential-less table's URL.+ update_fields = ["format", "url_pattern", "queryable_folder", "row_count"]+ if live_size_mib is not None:+ table.size_in_s3_mib = live_size_mib+ update_fields.append("size_in_s3_mib")retry_on_db_connection_drop(- lambda: table.save(- update_fields=["format", "url_pattern", "queryable_folder", "row_count"],- internally_computed_url_pattern=True,- )+ lambda: table.save(update_fields=update_fields, internally_computed_url_pattern=True))else:logger.debug(f"Creating CDC companion table: {companion_table_name}")companion_table = DataWarehouseTable.objects.create(external_data_source_id=job.pipeline.id,created_via=DataWarehouseTableCreatedVia.SOURCE,+ size_in_s3_mib=live_size_mib,**table_params,)+ _record_storage_delta(job, storage_delta_mib)_record_query_folder_pointer(schema_id, team_id, previous_queryable_folder, queryable_folder, run_id, logger)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 4424a99973c5..d05974f96a94 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@@ -40,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.load_resolutioverify_delete_enrichment,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (+ PostLoadResult,run_post_load_operations,supports_partial_data_loading,)@@ -405,7 +406,7 @@ async def _handle_partial_data_loading()-def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessage) -> str | None:+def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessage) -> PostLoadResult:"""Run post-load operations for a final batch whose data was already written to Delta Lake.Two deliveries land here: a redelivered final row whose earlier attempt committed the write@@ -416,10 +417,10 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessagAll async operations are run within a single async_to_sync call to avoidevent loop lifecycle issues with aiohttp/s3fs clients.- Returns the prepared queryable_folder, or None if post-load couldn't run.+ Returns the post-load result, with no queryable folder if post-load couldn't run."""- async def _run() -> str | None:+ async def _run() -> PostLoadResult:job = await ExternalDataJob.objects.prefetch_related("schema", "schema__source", "schema__table").aget(id=export_signal.job_id)@@ -440,7 +441,7 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessagexternal_data_job_id=export_signal.job_id,batch_index=export_signal.batch_index,)- return None+ return PostLoadResult(queryable_folder=None)pa_table = read_parquet(export_signal.s3_path)internal_schema = HogQLSchema()@@ -449,7 +450,7 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessagtable_schema_dict = internal_schema.to_hogql_types()del pa_table- prepared_queryable_folder = await run_post_load_operations(+ post_load_result = await run_post_load_operations(job=job,schema=schema,source=schema.source,@@ -462,7 +463,7 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessag)logger.debug("post_load_operations_complete_for_already_processed_batch")- return prepared_queryable_folder+ return post_load_resultreturn async_to_sync(_run)()@@ -641,7 +642,7 @@ def _trigger_ducklake_register_data_imports(export_signal: ExportSignalMessage,capture_exception(e)-def _trigger_post_import_workflow(export_signal: ExportSignalMessage) -> None:+def _trigger_post_import_workflow(export_signal: ExportSignalMessage, table_size_written: bool = False) -> None:"""Fire-and-forget start of `data-import-post-import` after a V3 final batch lands.V2 starts the same workflow from `external-data-job` after the COMPLETED status@@ -686,6 +687,7 @@ def _trigger_post_import_workflow(export_signal: ExportSignalMessage) -> None:job_id=export_signal.job_id,schema_id=export_signal.schema_id,source_id=export_signal.source_id,+ table_size_written=table_size_written,),id=build_post_import_workflow_id(export_signal.job_id),id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,@@ -806,18 +808,18 @@ def _record_post_load_phases(run_signal: ExportSignalMessage) -> AbstractContext)-def _complete_run(run_signal: ExportSignalMessage, prepared_queryable_folder: str | None) -> None:+def _complete_run(run_signal: ExportSignalMessage, post_load_result: PostLoadResult) -> None:"""Mark the job completed, then start the DuckLake registration and post-import workflows."""report_phase("finalize")with post_load_phase("job_completion"):_mark_job_completed(run_signal)- if prepared_queryable_folder:+ if post_load_result.queryable_folder:with post_load_phase("ducklake_trigger"):- _trigger_ducklake_register_data_imports(run_signal, prepared_queryable_folder)+ _trigger_ducklake_register_data_imports(run_signal, post_load_result.queryable_folder)with post_load_phase("post_import_trigger"):- _trigger_post_import_workflow(run_signal)+ _trigger_post_import_workflow(run_signal, post_load_result.table_size_written)def _load_job(job_id: str) -> ExternalDataJob:@@ -856,7 +858,7 @@ def _finalize_run(with _record_post_load_phases(run_signal):report_phase("post_load")- prepared_queryable_folder = async_to_sync(run_post_load_operations)(+ post_load_result = async_to_sync(run_post_load_operations)(job=job,schema=schema,source=schema.source,@@ -873,7 +875,7 @@ def _finalize_run(if verify_ownership is not None:verify_ownership()- _complete_run(run_signal, prepared_queryable_folder)+ _complete_run(run_signal, post_load_result)logger.debug("post_load_operations_complete", external_data_job_id=run_signal.job_id)@@ -1138,12 +1140,12 @@ def _process_message_reported(verify_ownership()with _record_post_load_phases(export_signal):report_phase("post_load")- prepared_queryable_folder = _run_post_load_for_already_processed_batch(export_signal)+ post_load_result = _run_post_load_for_already_processed_batch(export_signal)# Post-load can run minutes (compaction, S3 prep) — re-check before# completion promotes the cursor and releases the lock under a new owner.if verify_ownership is not None:verify_ownership()- _complete_run(export_signal, prepared_queryable_folder)+ _complete_run(export_signal, post_load_result)returnlogger.debug(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 3ef4d4053d44..2f70a5007475 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@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importSCD2_VALID_TO_COLUMN,TOAST_OMITTED_COLUMN,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import PostLoadResultfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (make_local_table_ref,@@ -263,6 +264,7 @@ def _message(**overrides: Any) -> dict[str, Any]:_PROCESSOR = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor"+_POST_LOAD_RESULT = PostLoadResult(queryable_folder="folder", table_size_written=True)class TestProcessMessageOwnershipGate:@@ -500,7 +502,7 @@ class TestMarkJobCompleted:class TestRedeliveredFinalBatchPostLoad:@parameterized.expand([("companion", "scd2_append"), ("consolidated", "incremental_merge"), ("snapshot", None)])- @patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value="folder")+ @patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value=_POST_LOAD_RESULT)@patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")@@ -645,7 +647,7 @@ class TestProcessMessages:@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}.run_post_load_operations", new_callable=AsyncMock, return_value=_POST_LOAD_RESULT)@patch(f"{_PROCESSOR}.read_parquet")@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)@patch(f"{_PROCESSOR}.DeltaWriter")@@ -689,7 +691,9 @@ class TestProcessMessages:assert mock_post_load.await_args is not Noneassert mock_post_load.await_args.kwargs["row_count"] == 6mock_mark_completed.assert_called_once()- mock_trigger.assert_called_once()+ # Without the flag the post-import workflow opens the table again to measure a size that+ # post-load already recorded.+ mock_trigger.assert_called_once_with(ANY, True)@patch(f"{_PROCESSOR}.posthoganalytics")@patch(f"{_PROCESSOR}.read_parquet")@@ -780,7 +784,7 @@ class TestProcessMessages:@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}.run_post_load_operations", new_callable=AsyncMock, return_value=_POST_LOAD_RESULT)@patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)@patch(f"{_PROCESSOR}.DeltaWriter")@@ -933,7 +937,7 @@ class TestPostImportTrigger:@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}.run_post_load_operations", new_callable=AsyncMock, return_value=_POST_LOAD_RESULT)@patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)@patch(f"{_PROCESSOR}.DeltaWriter")@@ -969,7 +973,9 @@ class TestPostImportTrigger:@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}._run_post_load_for_already_processed_batch", return_value=PostLoadResult(queryable_folder=None)+ )@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")@@ -1111,6 +1117,22 @@ class TestPostImportTrigger:assert mock_connect.call_count == 2mock_capture.assert_not_called()+ @parameterized.expand([("size_written", True), ("size_not_written", False)])+ @patch("posthog.temporal.common.client.async_connect", new_callable=AsyncMock)+ def test_tells_the_workflow_whether_post_load_wrote_the_table_size(+ self, _case: str, table_size_written: bool, mock_connect: AsyncMock+ ) -> None:+ # The workflow skips its size activity on True. A dropped False would leave a table that+ # post-load could not size with no size at all.+ client = MagicMock()+ client.start_workflow = AsyncMock(return_value=None)+ mock_connect.return_value = client++ _trigger_post_import_workflow(self._signal(), table_size_written)++ assert client.start_workflow.await_args is not None+ assert client.start_workflow.await_args.args[1].table_size_written is table_size_written+@patch(f"{_PROCESSOR}.capture_exception")@patch("posthog.temporal.common.client.async_connect", new_callable=AsyncMock)def test_persistent_rpc_timeout_is_captured_after_retries_exhausted(@@ -1463,7 +1485,11 @@ class TestBatchPhaseReports:@patch(f"{_PROCESSOR}._trigger_post_import_workflow")@patch(f"{_PROCESSOR}.mark_batch_as_processed")@patch(f"{_PROCESSOR}._mark_job_completed")- @patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value=None)+ @patch(+ f"{_PROCESSOR}.run_post_load_operations",+ new_callable=AsyncMock,+ return_value=PostLoadResult(queryable_folder=None),+ )@patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)@patch(f"{_PROCESSOR}.DeltaWriter")@@ -1484,9 +1510,9 @@ class TestBatchPhaseReports:mock_report_phase: MagicMock,mock_logger: MagicMock,) -> None:- async def post_load(**_kwargs: Any) -> None:+ async def post_load(**_kwargs: Any) -> PostLoadResult:with post_load_phase("delta_maintenance"):- return None+ return PostLoadResult(queryable_folder=None)_post_load.side_effect = post_loaddelta_table = MagicMock()@@ -1514,7 +1540,9 @@ class TestBatchPhaseReports:@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}._run_post_load_for_already_processed_batch", return_value=PostLoadResult(queryable_folder=None)+ )@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.pyindex 9c2afcbfc543..80106a7daef8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py@@ -368,6 +368,38 @@ class TestRegisterCdcCompanionTableStamp:assert history.active == "orders_cdc__query_a"assert history.active_job_id == str(job.id)+ def test_records_the_companion_size_on_the_companion_table(self, team):+ # In `both` mode the schema's table is the snapshot table. The companion size must land on+ # the companion's own record, for a new record and for an existing one.+ source = ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=team, source_type="Postgres"+ )+ schema = ExternalDataSchema.objects.create(name="orders", team=team, source=source)+ job = ExternalDataJob.objects.create(+ team=team, pipeline=source, schema=schema, status=ExternalDataJobStatus.RUNNING, rows_synced=10+ )++ for live_size_mib in (3.0, 5.0):+ with (+ patch.object(DataWarehouseTable, "get_columns", return_value={}),+ patch.object(DataWarehouseTable, "get_count", return_value=100),+ ):+ async_to_sync(register_cdc_companion_table)(+ run_id=str(job.id),+ team_id=team.pk,+ schema_id=schema.id,+ resource_name="orders_cdc",+ row_count=100,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder="orders_cdc__query_a",+ live_size_mib=live_size_mib,+ )++ companion = DataWarehouseTable.objects.get(team_id=team.pk, external_data_source_id=source.pk, deleted=False)+ job.refresh_from_db()+ assert companion.size_in_s3_mib == 5.0+ assert job.storage_delta_mib == 5.0+# transaction=True: validate_schema_and_update_table writes to the DB from the async thread pool# (database_sync_to_async_pool), which can't see an atomic TestCase's uncommitted rows.@@ -466,6 +498,49 @@ class TestValidateSchemaAndUpdateTable:# A reported 0 must not zero a table that was just republished.assert table.row_count == 150+ @pytest.mark.parametrize(+ "previous_size_mib,live_size_mib,expected_size_mib,expected_delta_mib",+ [+ pytest.param("no_table", 12.5, 12.5, 12.5, id="new_table"),+ pytest.param(None, 12.5, 12.5, 12.5, id="table_without_a_size"),+ pytest.param(10.0, 12.5, 12.5, 2.5, id="growth"),+ pytest.param(10.0, 4.0, 4.0, -6.0, id="smaller_after_compaction_or_full_refresh"),+ pytest.param(10.0, 0.0, 0.0, -10.0, id="emptied_table"),+ pytest.param(10.0, None, 10.0, 0, id="no_size_from_the_log_keeps_the_recorded_size"),+ ],+ )+ def test_records_the_published_size_and_the_storage_change_of_the_job(+ self, team, previous_size_mib, live_size_mib, expected_size_mib, expected_delta_mib+ ):+ # Billing and the s3Cluster threshold read size_in_s3_mib. A missing size must not become 0,+ # and a second registration for the same job (a redelivered final batch) must not erase the+ # storage change that the first one recorded.+ schema, job = self._schema_and_job(team)+ if previous_size_mib != "no_table":+ table = self._linked_table(team, schema, job, queryable_folder="s3://bucket/orders_v1")+ DataWarehouseTable.objects.filter(id=table.id).update(size_in_s3_mib=previous_size_mib)++ for _ in range(2):+ with (+ patch.object(DataWarehouseTable, "get_columns", return_value={}),+ patch.object(DataWarehouseTable, "get_count", return_value=150),+ ):+ async_to_sync(validate_schema_and_update_table)(+ run_id=str(job.id),+ team_id=team.pk,+ schema_id=schema.id,+ row_count=10,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder="s3://bucket/orders_v2",+ live_size_mib=live_size_mib,+ )++ schema.refresh_from_db()+ job.refresh_from_db()+ assert schema.table is not None+ assert schema.table.size_in_s3_mib == expected_size_mib+ assert job.storage_delta_mib == expected_delta_mib+def test_a_schema_linked_to_its_cdc_companion_gets_its_own_table(self, team: Team) -> None:schema, job = self._schema_and_job(team)companion = self._linked_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.pyindex 15f2f3db9ba8..5ae1b5ee43b3 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@@ -78,6 +78,9 @@ class PostImportWorkflowInputs:job_id: strschema_id: strsource_id: str+ # True when the load consumer recorded the table size at post-load. The default keeps the size+ # activity for a run that a starter without this field began.+ table_size_written: bool = False@propertydef properties_to_log(self) -> dict[str, typing.Any]:@@ -124,6 +127,7 @@ class PostImportGateContext:source_type: strteam: Team | Noneai_data_processing_approved: bool+ table_size_written: bool = False@dataclasses.dataclass(frozen=True)@@ -161,10 +165,16 @@ def _always(gate: PostImportGateContext) -> bool:return True-def _wrote_rows_gate(gate: PostImportGateContext) -> bool:- """Table size describes the rows this run loaded, so a run that wrote none leaves it- unchanged. `None` predates row counting, so it runs the step."""- return gate.job.rows_synced != 0+def _table_size_gate(gate: PostImportGateContext) -> bool:+ """The load consumer records the table size from the Delta snapshot it publishes, so this step+ is the fallback for a run where it did not: an older consumer, or a log that could not give a+ size for each file. The fallback follows the rows written. Table size describes the rows this+ run loaded, so a run that wrote none leaves it unchanged. `None` predates row counting, so it+ runs the step.++ The step stays in POST_IMPORT_STEPS because recorded runs name its key.+ """+ return not gate.table_size_written and gate.job.rows_synced != 0def _data_quality_gate(gate: PostImportGateContext) -> bool:@@ -307,7 +317,7 @@ 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=_wrote_rows_gate, start=_start_table_size),+ PostImportStep(key=TABLE_SIZE_STEP, enabled=_table_size_gate, start=_start_table_size),PostImportStep(key=DUCKLAKE_COPY_STEP, enabled=_always, start=_start_ducklake_copy),PostImportStep(key=DATA_QUALITY_CHECKS_STEP, enabled=_data_quality_gate, start=_start_data_quality_checks),)@@ -382,6 +392,7 @@ def resolve_post_import_context_activity(inputs: PostImportWorkflowInputs) -> Posource_type=source_type,team=team,ai_data_processing_approved=ai_data_processing_approved,+ table_size_written=inputs.table_size_written,)steps = [step.key for step in POST_IMPORT_STEPS if step.enabled(gate_ctx)]diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/queue_replay.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/queue_replay.pyindex 91f95f1d22eb..17ff427cdd1f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/queue_replay.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/queue_replay.py@@ -21,10 +21,6 @@ from products.warehouse_sources.backend.facade.models import ExternalDataJobfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (process_message,)-from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (- CalculateTableSizeActivityInputs,- calculate_table_size_activity,-)from products.warehouse_sources.backend.types import ExternalDataJobStatusfrom products.warehouse_sources_queue.backend.core.jobs_db import BATCH_TABLE, PendingBatchfrom products.warehouse_sources_queue.backend.testing import ensure_queue_tables, get_test_database_url@@ -168,12 +164,4 @@ async def replay_v3_consumer(for run_uuid in run_uuids:await sync_to_async(replay.replay_batches_for_run)(run_uuid)- await sync_to_async(calculate_table_size_activity)(- CalculateTableSizeActivityInputs(- team_id=team_id,- schema_id=str(schema_id),- job_id=job_id,- )- )-replay.clear()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 f9849a0a395b..6471a59ecc5d 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@@ -585,15 +585,19 @@ def test_resolve_context_uses_pre_sync_watermark_from_snapshot(team, _no_close_o@pytest.mark.django_db@pytest.mark.parametrize(- "rows_synced,expect_steps",+ "rows_synced,table_size_written,expect_steps",[- pytest.param(5, True, id="rows_written"),- pytest.param(0, False, id="zero_rows"),- pytest.param(None, True, id="row_count_unknown"),+ pytest.param(5, False, True, id="rows_written"),+ pytest.param(0, False, False, id="zero_rows"),+ pytest.param(None, False, True, id="row_count_unknown"),+ # The load consumer recorded the size from the Delta log, so the activity that opens the+ # table again must not run.+ pytest.param(5, True, False, id="size_written_by_the_loader"),+ pytest.param(None, True, False, id="size_written_by_the_loader_row_count_unknown"),],)-def test_table_size_tracks_rows_written_while_ducklake_copy_always_runs(- team, rows_synced, expect_steps, _no_close_old_connections+def test_table_size_runs_only_as_the_fallback_while_ducklake_copy_always_runs(+ team, rows_synced, table_size_written, expect_steps, _no_close_old_connections):from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.temporal.data_imports.post_import_job import (@@ -613,7 +617,11 @@ def test_table_size_tracks_rows_written_while_ducklake_copy_always_runs(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)+ team_id=team.pk,+ job_id=str(job.id),+ schema_id=str(schema.id),+ source_id=str(source.id),+ table_size_written=table_size_written,))