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.

perf(data-warehouse): count delta rows from the log instead of a chdb scan (#111439)

Tom Owers71cee884bee1
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 8cd2fd575c74..ec18f8897c38 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
@@ -409,6 +409,11 @@ 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
+ )
logger.debug("Validating schema and updating table")
with POST_LOAD_DURATION_SECONDS.labels(operation="validate_schema").time():
@@ -422,6 +427,7 @@ async def _register_table(
table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
primary_keys=resource.primary_keys if resource is not None else None,
delta_schema_json=delta_schema_json,
+ live_row_count=live_row_count,
)
logger.debug("Finished validating schema and updating table")
@@ -457,6 +463,7 @@ async def _run_cdc_post_load(
queryable_folder=queryable_folder,
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(),
)
logger.debug("Finished registering CDC companion table")
return
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 329a323713ec..d53aa066a800 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
@@ -57,10 +57,11 @@ def _make_schema(
return schema
-def _make_helper(*, file_uris: list[str] | None = None) -> MagicMock:
+def _make_helper(*, file_uris: list[str] | None = None, live_row_count: int | 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),
)
@@ -71,6 +72,8 @@ async def _run_post_load(
cdc_write_mode: str | None = None,
resource: Optional[MagicMock] = None,
stored_sync_type_config: dict | None = None,
+ validate: AsyncMock | None = None,
+ row_count: int = 10,
) -> tuple[AsyncMock, AsyncMock]:
job = MagicMock()
job.id = uuid.uuid4()
@@ -89,7 +92,7 @@ async def _run_post_load(
patch(f"{_LOAD_MODULE}.set_initial_sync_complete", AsyncMock()),
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", 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"{_REPARTITION_MODULE}.maybe_flag_for_repartition", AsyncMock()),
):
@@ -98,7 +101,7 @@ async def _run_post_load(
schema=schema,
source=MagicMock(),
delta_table_ref=helper,
- row_count=10,
+ row_count=row_count,
table_schema_dict={},
resource_name="orders",
logger=logger,
@@ -172,6 +175,31 @@ class TestRunPostLoadDeltaMaintenance:
assert prepare_s3.await_args.args[2] == post_maintenance_uris
+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),
+ ]
+ )
+ @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:
+ # 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
+ validate = AsyncMock()
+
+ await _run_post_load(schema, _make_helper(live_row_count=40_000_000), validate=validate, row_count=row_count)
+
+ validate.assert_awaited_once()
+ assert validate.await_args is not None
+ assert validate.await_args.kwargs["live_row_count"] == expected
+
+
class TestPublishQueryableFilesDoubleBuffer:
_STATE = {
"query_folder_state": {
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 7de69e30510f..334a74f5cc9f 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
@@ -3,7 +3,9 @@ from typing import Any
from django.conf import settings
+import pyarrow as pa
import deltalake as deltalake
+import pyarrow.compute as pc
import deltalake.exceptions
from structlog.types import FilteringBoundLogger
@@ -150,6 +152,30 @@ def delta_storage_options() -> dict[str, str]:
return options
+def live_row_count(delta_table: deltalake.DeltaTable) -> int | None:
+ """Rows in the table's live files, summed from the `numRecords` statistic of each Add action.
+
+ The query folder holds a copy of exactly the live files, so this sum is the number a `count()`
+ over that folder returns, without a read of any data file. Deletion vectors do not change this,
+ 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.
+ """
+ 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.
+ return None
+ if "num_records" not in add_actions.column_names:
+ return None
+ num_records = add_actions.column("num_records")
+ if num_records.null_count:
+ return None
+ return int(pc.sum(num_records).as_py() or 0)
+
+
class DeltaTableRef:
"""Handle to one schema's Delta table: uri/credentials, the cached open (with corrupt-table
auto-heal), corruption detection, reset, file listing, and the first-sync flag.
@@ -432,3 +458,15 @@ class DeltaTableRef:
return []
return await asyncio.to_thread(delta_table.file_uris)
+
+ async def get_live_row_count(self) -> int | None:
+ """The table's row count from the Delta log, or None when the log cannot give it (see
+ `live_row_count`)."""
+ delta_table = await self.get_delta_table()
+ if delta_table is None:
+ return None
+
+ 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")
+ return row_count
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.py
index b82b63daaae6..069dcad3b9d6 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
@@ -1,3 +1,6 @@
+import json
+from collections.abc import Callable
+from pathlib import Path
from typing import cast
import pytest
@@ -5,7 +8,10 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.test import override_settings
+import pyarrow as pa
import deltalake
+import deltalite
+import pyarrow.parquet as pq
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.deltalite_handles import (
@@ -21,8 +27,12 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
_PURGE_S3_PREFIX_MAX_ATTEMPTS,
DeltaTableRef,
_purge_s3_prefix,
+ live_row_count,
+)
+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.pipelines.core.delta.test.helpers import make_logger
def table_ref():
@@ -532,3 +542,120 @@ class TestInvalidateDropsTheDeltaliteHandle:
ref.invalidate_cached_table()
assert "s3://bucket/team/job/t" not in cache
+
+
+def _rows(ids: list[int], partition: str) -> pa.Table:
+ return pa.table({"id": pa.array(ids, pa.int64()), "part": [partition] * len(ids)})
+
+
+def _appended(uri: str) -> None:
+ deltalake.write_deltalake(uri, _rows([5, 6], "b"), mode="append", partition_by=["part"])
+
+
+def _overwritten(uri: str) -> None:
+ deltalake.write_deltalake(uri, _rows([7], "c"), mode="overwrite", partition_by=["part"])
+
+
+def _deleted_from(uri: str) -> None:
+ deltalake.DeltaTable(uri).delete("id = 1")
+
+
+def _emptied(uri: str) -> None:
+ deltalake.DeltaTable(uri).delete("id > 0")
+
+
+def _merged(uri: str) -> None:
+ (
+ deltalake.DeltaTable(uri)
+ .merge(_rows([2, 9], "a"), predicate="t.id = s.id", source_alias="s", target_alias="t")
+ .when_matched_update_all()
+ .when_not_matched_insert_all()
+ .execute()
+ )
+
+
+def _upserted_with_deltalite(uri: str) -> None:
+ deltalite.DeltaLiteTable.open(uri).upsert(_rows([3, 10, 11], "a"), primary_keys=["id"], partition_key="part")
+
+
+def _compacted(uri: str) -> None:
+ _appended(uri)
+ deltalake.DeltaTable(uri).optimize.compact()
+
+
+def _vacuumed(uri: str) -> None:
+ _deleted_from(uri)
+ deltalake.DeltaTable(uri).vacuum(retention_hours=0, enforce_retention_duration=False, dry_run=False)
+
+
+def _strip_add_stats(uri: str) -> None:
+ for commit in sorted((Path(uri) / "_delta_log").glob("*.json")):
+ actions = [json.loads(line) for line in commit.read_text().splitlines() if line]
+ for action in actions:
+ action.get("add", {}).pop("stats", None)
+ commit.write_text("\n".join(json.dumps(action) for action in actions) + "\n")
+
+
+class TestLiveRowCount:
+ @staticmethod
+ def _create(tmp_path: Path) -> str:
+ uri = str(tmp_path / "t")
+ deltalake.write_deltalake(uri, _rows([1, 2, 3, 4], "a"), partition_by=["part"])
+ return uri
+
+ @parameterized.expand(
+ [
+ ("append_only", lambda uri: None),
+ ("append", _appended),
+ ("overwrite", _overwritten),
+ ("delete", _deleted_from),
+ ("delete_every_row", _emptied),
+ ("merge", _merged),
+ ("deltalite_upsert", _upserted_with_deltalite),
+ ("compaction", _compacted),
+ ("vacuum", _vacuumed),
+ ]
+ )
+ def test_matches_a_count_of_the_published_files(self, _name: str, history: Callable[[str], None]) -> None:
+ # The query folder is a copy of file_uris(), so a count over it is the sum of their rows.
+ uri = self._create(self.tmp_path)
+ history(uri)
+ table = deltalake.DeltaTable(uri)
+
+ published_rows = sum(pq.read_metadata(path).num_rows for path in table.file_uris())
+
+ assert live_row_count(table) == published_rows == table.to_pyarrow_table().num_rows
+
+ def test_files_without_stats_fall_back_to_a_file_count(self) -> None:
+ uri = self._create(self.tmp_path)
+ _strip_add_stats(uri)
+
+ assert live_row_count(deltalake.DeltaTable(uri)) is None
+
+ def test_unreadable_add_actions_fall_back_to_a_file_count(self) -> None:
+ table = MagicMock()
+ table.get_add_actions.side_effect = Exception("Offset overflow error: 2229224676")
+
+ assert live_row_count(table) is None
+
+ @pytest.mark.asyncio
+ async def test_ref_reads_the_count_after_a_deltalite_commit(self) -> None:
+ # deltalite commits outside the cached delta-rs handle, so a stale handle would miss its rows.
+ uri = self._create(self.tmp_path)
+ ref = make_local_table_ref(uri)
+ assert await ref.get_live_row_count() == 4
+
+ 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_row_count() == 6
+
+ @pytest.mark.asyncio
+ async def test_ref_without_a_table_has_no_count(self) -> None:
+ ref = make_local_table_ref(str(self.tmp_path / "missing"))
+
+ assert await ref.get_live_row_count() is None
+
+ @pytest.fixture(autouse=True)
+ def _tmp(self, tmp_path: Path) -> None:
+ self.tmp_path = tmp_path
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 7c98815649a4..7af00cea767f 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
@@ -248,7 +248,15 @@ async def set_initial_sync_complete(schema_id: str, team_id: int, logger: Filter
)
-def _refresh_cumulative_row_count(table: DataWarehouseTable, logger: FilteringBoundLogger, context: str) -> None:
+def _refresh_cumulative_row_count(
+ table: DataWarehouseTable, logger: FilteringBoundLogger, context: str, live_row_count: Optional[int] = None
+) -> None:
+ # The Delta log gives the same number as a count of the published files, without the chdb
+ # subprocess or the ClickHouse cluster read of every file that get_count() needs.
+ if live_row_count is not None:
+ table.row_count = live_row_count
+ return
+
# Counting the full S3 dataset can exceed both the chdb and ClickHouse-cluster timeouts on a
# large table (get_count() then raises). That's only a display stat, not the synced data itself
# (already written successfully by this point) — keep the previous row_count rather than let it
@@ -286,6 +294,7 @@ async def validate_schema_and_update_table(
table_schema_dict: Optional[dict[str, str]] = None,
primary_keys: Optional[list[str]] = None,
delta_schema_json: Optional[str] = None,
+ live_row_count: Optional[int] = None,
) -> None:
"""
Async version of validate_schema_and_update_table_sync.
@@ -303,6 +312,8 @@ async def validate_schema_and_update_table(
delta_schema_json: The Delta table's schema. When given and unchanged since the columns were
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.
"""
logger = LOGGER.bind(team_id=team_id)
@@ -377,7 +388,7 @@ async def validate_schema_and_update_table(
if 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})")
+ _refresh_cumulative_row_count(table, logger, f"{_schema_name} ({_schema_id})", live_row_count)
else:
table.row_count = row_count
# get_count() above can retry against a degraded ClickHouse cluster for minutes, long
@@ -406,7 +417,7 @@ async def validate_schema_and_update_table(
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})")
+ _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
@@ -516,6 +527,7 @@ async def register_cdc_companion_table(
queryable_folder: str,
table_schema_dict: Optional[dict[str, str]] = None,
set_as_schema_table: bool = False,
+ live_row_count: Optional[int] = None,
) -> None:
"""Create or update a standalone DataWarehouseTable for a CDC companion resource (e.g. `{schema_name}_cdc`).
@@ -567,7 +579,7 @@ async def register_cdc_companion_table(
table.format = table_format
table.url_pattern = new_url_pattern
table.queryable_folder = queryable_folder
- _refresh_cumulative_row_count(table, logger, companion_table_name)
+ _refresh_cumulative_row_count(table, logger, companion_table_name, live_row_count)
# Scope to the fields changed here so this out-of-transaction save doesn't rewrite
# `columns` with its pre-merge value before the column save below.
# get_count() above can retry against a degraded ClickHouse cluster for minutes, long
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 234e6a57cc6a..6184385b5be3 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
@@ -108,13 +108,21 @@ class TestResolveTableAndFolderNames:
class TestRefreshCumulativeRowCount:
- def test_updates_row_count_on_success(self) -> None:
+ @parameterized.expand(
+ [
+ ("counts_the_files_without_a_log_count", None, 42, True),
+ ("uses_the_log_count", 40_000_000, 40_000_000, False),
+ ("uses_a_log_count_of_zero", 0, 0, False),
+ ]
+ )
+ def test_updates_row_count(self, _name: str, live_row_count: int | None, expected: int, counts_files: bool) -> None:
table = MagicMock(row_count=1)
table.get_count.return_value = 42
- _refresh_cumulative_row_count(table, MagicMock(), "orders (schema-1)")
+ _refresh_cumulative_row_count(table, MagicMock(), "orders (schema-1)", live_row_count)
- assert table.row_count == 42
+ assert table.row_count == expected
+ assert table.get_count.called is counts_files
def test_keeps_previous_row_count_when_get_count_fails(self) -> None:
# get_count() raises when both the chdb and ClickHouse-cluster reads of the S3 dataset