: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
fix(warehouse-sources): register the table when a zero-row run publishes files (#98676)
Daniel RCcdab7a866882
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 b653976ba043..9ffe2e07d8a5 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@@ -8,6 +8,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@@ -301,6 +302,12 @@ async def _run_delta_maintenance(logger.exception(f"Compaction failed: {e}", exc_info=e)+@frozen+class PublishedFiles:+ folder: str+ file_count: int++async def _publish_queryable_files(job: ExternalDataJob,schema: ExternalDataSchema,@@ -308,7 +315,7 @@ async def _publish_queryable_files(resource_name: str,is_cdc_companion: bool,logger: FilteringBoundLogger,-) -> str:+) -> PublishedFiles:from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import build_table_nameif is_cdc_companion:@@ -341,7 +348,7 @@ async def _publish_queryable_files(file_uris = await delta_table_ref.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():- return await prepare_s3_files_for_querying(+ folder = await prepare_s3_files_for_querying(await database_sync_to_async_pool(job.folder_path)(),resource_name,file_uris,@@ -350,6 +357,7 @@ async def _publish_queryable_files(logger=logger,refresh_file_uris=delta_table_ref.get_file_uris,)+ return PublishedFiles(folder=folder, file_count=len(file_uris))async def _finalize_sync_bookkeeping(@@ -381,7 +389,7 @@ async def _register_table(row_count: int,table_schema_dict: dict[str, str],resource: "Optional[SourceResponse]",- queryable_folder: str,+ published: PublishedFiles,logger: FilteringBoundLogger,) -> None:from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (@@ -396,9 +404,10 @@ async def _register_table(schema_id=schema.id,table_schema_dict=table_schema_dict,row_count=row_count,- queryable_folder=queryable_folder,+ queryable_folder=published.folder,table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,primary_keys=resource.primary_keys if resource is not None else None,+ published_file_count=published.file_count,)logger.debug("Finished validating schema and updating table")@@ -634,17 +643,20 @@ async def run_post_load_operations(is_initial_load = not schema.initial_sync_complete# Zero rows means the Delta table is untouched: nothing to compact, and republishing- # would only orphan a fresh copy of every parquet file. Registration already no-ops at- # zero rows. Bookkeeping and POST_LOAD_STEPS still run below, because those repair- # managed views and watermarks rather than describing what this run wrote. Opt-in- # because only the v2 pipeline's row_count is ground truth for what the run wrote; the- # v3 consumer's can read 0 for a batch that did write data.+ # would only orphan a fresh copy of every parquet file. A schema with a linked table+ # has nothing to repoint either. Bookkeeping and POST_LOAD_STEPS still run below,+ # because those repair managed views and watermarks rather than describing what this+ # run wrote. Opt-in because only the v2 pipeline's row_count is ground truth for what+ # the run wrote; the v3 consumer's can read 0 for a batch that did write data.if (allow_zero_row_skipand row_count == 0and not is_cdc_schemaand not is_cdc_companionand schema.initial_sync_complete+ # An unlinked schema has nothing queryable, and skipping registration strands it: the next+ # zero-row run skips again.+ and schema.table_id is not Noneand schema.repartition_pending is Noneand schema.repartition_swap is Noneand schema.delta_revive_required is None@@ -657,9 +669,8 @@ async def run_post_load_operations(await _run_delta_maintenance(schema, delta_table_ref, is_cdc_companion, logger)- queryable_folder = await _publish_queryable_files(- job, schema, delta_table_ref, resource_name, is_cdc_companion, logger- )+ published = await _publish_queryable_files(job, schema, delta_table_ref, resource_name, is_cdc_companion, logger)+ queryable_folder = published.folderawait _finalize_sync_bookkeeping(job, schema, resource, last_incremental_field_value, logger)@@ -669,7 +680,7 @@ async def run_post_load_operations(is_cdc_only_initial = cdc_write_mode is None and is_cdc_schema and schema.cdc_table_mode == "cdc_only"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 _register_table(job, schema, row_count, table_schema_dict, resource, published, logger)if is_cdc_companion or is_cdc_schema:await _run_cdc_post_load(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 ef179acd8132..8672daf97531 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@@ -1,5 +1,6 @@import uuidfrom datetime import UTC, datetime+from typing import Optionalimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch@@ -14,6 +15,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,+ PublishedFiles,get_incremental_field_value,notify_revenue_analytics_that_sync_has_completed,run_post_load_operations,@@ -30,6 +32,7 @@ _DB_RETRY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pip_PIPELINE_SYNC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync"_REPARTITION_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"_JOB_CREATED_AT = datetime(2026, 8, 19, 11, 0, tzinfo=UTC)+_A_LINKED_TABLE_ID = uuid.uuid4()def _make_schema(@@ -192,6 +195,8 @@ class TestZeroRowSkip:[("steady_state_zero_rows_skips", 0, "incremental", True, {}, True, True),("synced_rows_run_full_path", 5, "incremental", True, {}, True, False),+ # An unlinked schema has nothing queryable, and a skip here strands it forever.+ ("unlinked_schema_runs_full_path", 0, "incremental", True, {}, True, False, None),("caller_without_opt_in_runs_full_path", 0, "incremental", True, {}, False, False),("incomplete_initial_sync_runs_full_path", 0, "incremental", False, {}, True, False),("cdc_schema_runs_full_path", 0, "cdc", True, {}, True, False),@@ -253,6 +258,7 @@ class TestZeroRowSkip:sync_type_config: dict,allow_zero_row_skip: bool,expect_skip: bool,+ table_id: Optional[uuid.UUID] = _A_LINKED_TABLE_ID,):schema = ExternalDataSchema(id=uuid.uuid4(),@@ -260,6 +266,7 @@ class TestZeroRowSkip:sync_type=sync_type,initial_sync_complete=initial_sync_complete,sync_type_config=sync_type_config,+ table_id=table_id,)job = MagicMock()job.id = uuid.uuid4()@@ -267,7 +274,7 @@ class TestZeroRowSkip:job.created_at = _JOB_CREATED_ATmaintenance = AsyncMock()- publish = AsyncMock(return_value="folder")+ publish = AsyncMock(return_value=PublishedFiles(folder="folder", file_count=1))bookkeeping = AsyncMock()post_load_step = AsyncMock()with (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 4532b6136d94..d98443009524 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@@ -186,6 +186,7 @@ async def validate_schema_and_update_table(queryable_folder: str,table_schema_dict: Optional[dict[str, str]] = None,primary_keys: Optional[list[str]] = None,+ published_file_count: Optional[int] = None,) -> None:"""Async version of validate_schema_and_update_table_sync.@@ -200,6 +201,7 @@ async def validate_schema_and_update_table(row_count: The count of synced rowstable_format: The format of the tabletable_schema_dict: The schema of the table+ published_file_count: Files the publish step just made queryable, when the caller knows."""logger = LOGGER.bind(team_id=team_id)@@ -244,13 +246,24 @@ async def validate_schema_and_update_table(# exhausted the connection pool.table_created: DataWarehouseTable | None = external_data_schema.table- # A reported row_count of 0 does not always mean the run wrote nothing: the v3 load- # consumer reads it from a batch notification that can arrive as 0 on a redelivered final- # batch after a real write. Skip only when no table exists yet, so a genuinely empty first- # sync does not create an empty table. An existing table still gets repointed below at the- # freshly published files — stranding it on the previous queryable_folder would serve stale- # data under a green sync.- if row_count == 0 and table_created is None:+ if table_created is None:+ # The ServerException handler below can leave a created table unlinked, so look for+ # that orphan before the skip decides no table exists. Two schema names can resolve+ # to one table name, so require that no schema owns the row.+ table_created = DataWarehouseTable.objects.filter(+ team_id=team_id,+ name=table_name,+ external_data_source_id=job.pipeline.id,+ deleted=False,+ externaldataschema__isnull=True,+ ).first()+ if table_created is not None:+ logger.debug(f"Found existing table {table_created.id} - reusing it for schema {_schema_id}")++ # A reported row_count of 0 does not always mean the run wrote nothing: the v3 consumer+ # can read 0 on a redelivered final batch, and a resumed run counts only its own attempt.+ # A publish step with nothing to make queryable is what an empty first sync looks like.+ if row_count == 0 and table_created is None and not published_file_count:logger.warning("Skipping table creation: row_count is 0 and no table exists yet")return@@ -277,25 +290,19 @@ async def validate_schema_and_update_table())- if not table_created:- # Check if we already have an orphaned table that we can repurpose- existing_tables = DataWarehouseTable.objects.filter(- team_id=team_id, name=table_name, external_data_source_id=job.pipeline.id, deleted=False+ else:+ logger.debug(f"Creating table for schema: {str(schema_id)}")+ table = DataWarehouseTable.objects.create(+ external_data_source_id=job.pipeline.id,+ created_via=DataWarehouseTableCreatedVia.SOURCE,+ **table_params,)- existing_tables_count = existing_tables.count()- if existing_tables_count > 0:- table_created = existing_tables[0]- logger.debug(- f"Found {existing_tables_count} existing tables - skipping creating and using {table_created.id}"- )-- if not table_created:- logger.debug(f"Creating table for schema: {str(schema_id)}")- table_created = DataWarehouseTable.objects.create(- external_data_source_id=job.pipeline.id,- created_via=DataWarehouseTableCreatedVia.SOURCE,- **table_params,- )+ if row_count == 0:+ # table_params holds 0 for a table an earlier attempt already filled. get_count()+ # can block long enough for the pooled connection to go stale, as above.+ _refresh_cumulative_row_count(table, logger, f"{_schema_name} ({_schema_id})")+ retry_on_db_connection_drop(lambda: table.save(update_fields=["row_count"]))+ table_created = tableassert isinstance(table_created, DataWarehouseTable) and table_created is not Nonediff --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 3f24a28e7e8f..1f209529317c 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@@ -446,6 +446,7 @@ class PipelineNonDLT(Generic[ResumableData]):row_count=row_count,queryable_folder=queryable_folder,table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ published_file_count=len(new_file_uris),)async def _post_run_operations(self, row_count: int) -> str | None: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 b35d94bea9fa..e1df5bad0060 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@@ -394,6 +394,7 @@ async def _handle_partial_data_loading(queryable_folder=queryable_folder,table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,primary_keys=export_signal.primary_keys,+ published_file_count=len(new_file_uris),)logger.debug(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 ef931a31a7ce..284840b7bd6d 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@@ -404,14 +404,18 @@ class TestValidateSchemaAndUpdateTable:# A reported 0 must not zero a table that was just republished.assert table.row_count == 150- def test_zero_row_first_sync_creates_no_table(self, team):- # No table yet plus zero rows is a genuinely empty first sync - do not create an empty table.+ # Published files at zero rows mean a resumed or redelivered run counted only its own attempt.+ # Trusting row_count there left the data in S3 with no table to query it through.+ @pytest.mark.parametrize("published_file_count,expect_table", [(0, False), (18, True)])+ def test_zero_row_sync_creates_a_table_only_when_files_were_published(+ self, team, published_file_count: int, expect_table: bool+ ):schema, job = self._schema_and_job(team)assert schema.table is Nonewith (patch.object(DataWarehouseTable, "get_columns", return_value={}),- patch.object(DataWarehouseTable, "get_count", return_value=0),+ patch.object(DataWarehouseTable, "get_count", return_value=150),):async_to_sync(validate_schema_and_update_table)(run_id=str(job.id),@@ -420,11 +424,77 @@ class TestValidateSchemaAndUpdateTable:row_count=0,table_format=DataWarehouseTableFormat.DeltaS3Wrapper,queryable_folder="s3://bucket/orders",+ published_file_count=published_file_count,)schema.refresh_from_db()- assert schema.table is None- assert not DataWarehouseTable.objects.filter(external_data_source=schema.source, deleted=False).exists()+ tables = DataWarehouseTable.objects.filter(external_data_source=schema.source, deleted=False)+ if not expect_table:+ assert schema.table is None+ assert not tables.exists()+ else:+ assert schema.table_id == tables.get().id+ # A reported 0 must not register a table full of published files as empty.+ assert tables.get().row_count == 150++ def test_relinks_a_table_an_earlier_run_left_unlinked(self, team):+ # An orphan must be adopted and repointed, not left unlinked and not duplicated.+ schema, job = self._schema_and_job(team)+ orphan = self._linked_table(team, schema, job, queryable_folder="s3://bucket/orders_v1")+ ExternalDataSchema.objects.filter(id=schema.id).update(table=None)++ 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=0,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder="s3://bucket/orders_v2",+ published_file_count=18,+ )++ schema.refresh_from_db()+ orphan.refresh_from_db()+ assert schema.table_id == orphan.id+ assert orphan.queryable_folder == "s3://bucket/orders_v2"+ assert DataWarehouseTable.objects.filter(external_data_source=schema.source, deleted=False).count() == 1++ def test_does_not_adopt_a_table_another_schema_owns(self, team):+ # A pinned folder makes "public.orders" resolve to the same table name as "orders", so a+ # lookup on name alone would hand one schema the table its sibling is already using.+ owner, job = self._schema_and_job(team)+ owned = self._linked_table(team, owner, job, queryable_folder="s3://bucket/orders_v1")+ sibling = ExternalDataSchema.objects.create(+ name="public.orders", team=team, source=owner.source, s3_folder_name="orders"+ )+ sibling_job = ExternalDataJob.objects.create(+ team=team, pipeline=owner.source, schema=sibling, status=ExternalDataJobStatus.RUNNING, rows_synced=10+ )++ 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(sibling_job.id),+ team_id=team.pk,+ schema_id=sibling.id,+ row_count=0,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder="s3://bucket/orders_v2",+ published_file_count=18,+ )++ owner.refresh_from_db()+ sibling.refresh_from_db()+ owned.refresh_from_db()+ assert owner.table_id == owned.id+ assert sibling.table_id not in (None, owned.id)+ assert owned.queryable_folder == "s3://bucket/orders_v1"class TestUpdateLastSyncedAt: