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.

fix(warehouse-sources): store the table size after a multi-attempt sync (#116147)

Daniel RC8a53776d4d5e
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index b0820ac2a388..7b0f001884f1 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -586,7 +586,8 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
def table_row_count_is_cumulative(self) -> bool:
# These sync types append/merge into the warehouse table across runs, so its true size is the
# full table count — not the latest run's row_count, which is only that run's delta. Full refresh
- # replaces the whole table, so there the run's row_count already equals the table size.
+ # replaces the whole table, so there the run's row_count equals the table size unless the run
+ # resumed: a resumed run counts only the rows of its last attempt.
return self.should_use_incremental_field or self.is_cdc or self.is_xmin
@property
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 3cdba7aafdd4..e58e64c17435 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
@@ -456,11 +456,10 @@ async def _register_table(
# snapshot rather than from another log read.
delta_table = await delta_table_ref.get_delta_table()
delta_schema_json = delta_table.schema().to_json() if delta_table is not None else None
- # Only a table whose run count is not its size reads the count. The handle is the one the publish
- # step listed, so the count matches the files the query folder now holds.
- live_row_count = (
- await delta_table_ref.get_live_row_count() if schema.table_row_count_is_cumulative or row_count == 0 else None
- )
+ # The run count is not the table size, even for a full refresh: a run that resumes counts only
+ # the rows of its last attempt. The handle is the one the publish step listed, so the count
+ # matches the files the query folder now holds.
+ live_row_count = await delta_table_ref.get_live_row_count()
# 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()
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 cc7bde35773c..c3e97c31f7d3 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
@@ -192,28 +192,19 @@ class TestRunPostLoadDeltaMaintenance:
class TestRegisterTableRowCount:
- @parameterized.expand(
- [
- ("cumulative", True, 10, 40_000_000),
- ("full_refresh_with_rows", False, 10, None),
- ("full_refresh_reporting_zero", False, 0, 40_000_000),
- ]
- )
+ @parameterized.expand([("log_count", 40_000_000), ("log_without_statistics", None)])
@pytest.mark.asyncio
- async def test_passes_the_delta_log_count_when_the_run_count_is_not_the_table_size(
- self, _name: str, cumulative: bool, row_count: int, expected: int | None
- ) -> None:
+ async def test_passes_the_delta_log_count_to_the_registration(self, _name: str, live_row_count: int | None) -> None:
# Without the log count, registration counts every published file through chdb or the
- # ClickHouse cluster on each sync of an incremental table.
- schema = _make_schema(is_cdc=False)
- schema.table_row_count_is_cumulative = cumulative
+ # ClickHouse cluster on each sync of an incremental table, and a full refresh that ran over
+ # several attempts stores the rows of its last attempt as the table size.
validate = AsyncMock()
- await _run_post_load(schema, _make_helper(live_row_count=40_000_000), validate=validate, row_count=row_count)
+ await _run_post_load(_make_schema(is_cdc=False), _make_helper(live_row_count=live_row_count), validate=validate)
validate.assert_awaited_once()
assert validate.await_args is not None
- assert validate.await_args.kwargs["live_row_count"] == expected
+ assert validate.await_args.kwargs["live_row_count"] == live_row_count
class TestPostLoadTableSize:
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.py
index 271620622644..725e2d81fba5 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
@@ -160,13 +160,13 @@ def live_row_count(delta_table: deltalake.DeltaTable) -> int | None:
because the copied files also keep every physical row.
None when a live file has no statistic or the log cannot give the statistics. The caller then
- counts the files instead.
+ counts the files, or keeps the run count for a full refresh.
"""
try:
add_actions = pa.table(delta_table.get_add_actions(flatten=False))
except Exception:
# The stats of a large table can overflow Arrow's 32-bit string offsets (see
- # repartition.measure_partition_bytes), and the fallback count gives the same number.
+ # repartition.measure_partition_bytes), and the caller has a fallback.
return None
if "num_records" not in add_actions.column_names:
return None
@@ -578,7 +578,7 @@ class DeltaTableRef:
row_count = await asyncio.to_thread(live_row_count, delta_table)
if row_count is None:
- await self._logger.adebug("The Delta log has no complete row count, counting the published files")
+ await self._logger.adebug("The Delta log has no complete row count")
return row_count
async def get_live_size_mib(self) -> float | 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.py
index 6ed03eabc5ab..62d7c0bcf713 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
@@ -378,7 +378,7 @@ async def validate_schema_and_update_table(
last registered (together with the projection inputs), the ClickHouse introspection and
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.
+ it is the table size. `row_count` is the fallback, and can be only the last attempt's rows.
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.
@@ -407,14 +407,17 @@ async def validate_schema_and_update_table(
new_url_pattern = job.url_pattern_by_schema(names.folder_name)
try:
- logger.info(f"Row count for {_schema_name} ({_schema_id}) is {row_count}")
+ logger.info(
+ f"Run row count for {_schema_name} ({_schema_id}) is {row_count}, "
+ f"Delta log row count is {live_row_count}"
+ )
table_params = {
"name": table_name,
"format": table_format,
"url_pattern": new_url_pattern,
"team_id": team_id,
- "row_count": row_count,
+ "row_count": live_row_count if live_row_count is not None else row_count,
"queryable_folder": queryable_folder,
}
@@ -447,11 +450,15 @@ async def validate_schema_and_update_table(
table.format = table_params["format"]
table.url_pattern = new_url_pattern
table.queryable_folder = queryable_folder
- if external_data_schema.table_row_count_is_cumulative or row_count == 0:
+ if live_row_count is not None:
+ table.row_count = live_row_count
+ elif external_data_schema.table_row_count_is_cumulative or row_count == 0:
# A reported 0 can under-count a real write (see above), so read the true count
# from the just-published files rather than zero a table we are republishing.
- _refresh_cumulative_row_count(table, logger, f"{_schema_name} ({_schema_id})", live_row_count)
+ _refresh_cumulative_row_count(table, logger, f"{_schema_name} ({_schema_id})")
else:
+ # A count of the files on each full refresh costs more than this statistic is
+ # worth, so a run that resumed stores only the rows of its last attempt here.
table.row_count = row_count
# get_count() above can retry against a degraded ClickHouse cluster for minutes, long
# enough for the pooled Postgres connection to be recycled underneath us. Retry once
@@ -480,11 +487,6 @@ async def validate_schema_and_update_table(
)
_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()
- # can block long enough for the pooled connection to go stale, as above.
- _refresh_cumulative_row_count(table, logger, f"{_schema_name} ({_schema_id})", live_row_count)
- retry_on_db_connection_drop(lambda: table.save(update_fields=["row_count"]))
table_created = table
assert isinstance(table_created, DataWarehouseTable) and table_created is not None
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.py
index 80106a7daef8..4078ef2e0565 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
@@ -498,6 +498,62 @@ class TestValidateSchemaAndUpdateTable:
# A reported 0 must not zero a table that was just republished.
assert table.row_count == 150
+ @pytest.mark.parametrize(
+ "table_exists,sync_type,live_row_count,expected_row_count,counts_files",
+ [
+ pytest.param(
+ False, ExternalDataSchema.SyncType.FULL_REFRESH, 1_200, 1_200, False, id="first_sync_full_refresh"
+ ),
+ pytest.param(
+ False, ExternalDataSchema.SyncType.INCREMENTAL, 1_200, 1_200, False, id="first_sync_incremental"
+ ),
+ pytest.param(True, ExternalDataSchema.SyncType.FULL_REFRESH, 1_200, 1_200, False, id="later_full_refresh"),
+ pytest.param(
+ True,
+ ExternalDataSchema.SyncType.FULL_REFRESH,
+ None,
+ 200,
+ False,
+ id="full_refresh_falls_back_to_run_count",
+ ),
+ pytest.param(
+ True,
+ ExternalDataSchema.SyncType.INCREMENTAL,
+ None,
+ 5_000,
+ True,
+ id="incremental_falls_back_to_file_count",
+ ),
+ ],
+ )
+ def test_stores_the_delta_log_count_and_never_counts_the_files_of_a_full_refresh(
+ self, team, table_exists, sync_type, live_row_count, expected_row_count, counts_files
+ ):
+ schema, job = self._schema_and_job(team)
+ schema.sync_type = sync_type
+ schema.save()
+ if table_exists:
+ self._linked_table(team, schema, job, queryable_folder="s3://bucket/orders_v1")
+
+ with (
+ patch.object(DataWarehouseTable, "get_columns", return_value={}),
+ patch.object(DataWarehouseTable, "get_count", return_value=5_000) as get_count,
+ ):
+ async_to_sync(validate_schema_and_update_table)(
+ run_id=str(job.id),
+ team_id=team.pk,
+ schema_id=schema.id,
+ row_count=200,
+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,
+ queryable_folder="s3://bucket/orders_v2",
+ live_row_count=live_row_count,
+ )
+
+ assert get_count.called is counts_files
+ schema.refresh_from_db()
+ assert schema.table is not None
+ assert schema.table.row_count == expected_row_count
+
@pytest.mark.parametrize(
"previous_size_mib,live_size_mib,expected_size_mib,expected_delta_mib",
[