: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): read delta snapshots with deltalite where a caller only reads (#113098)
Tom Owers84a0cd8a0fe8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.pyindex 4949f1766478..4c1f9bd67146 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py@@ -34,6 +34,7 @@ import posthoganalyticsfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Teamfrom posthog.sync import database_sync_to_async@@ -450,9 +451,9 @@ def _fold_commit_stats(}-def _delta_schema_fields(delta_table: Any) -> dict[str, Any]:+def _delta_schema_fields(schema_json: str) -> dict[str, Any]:"""Column name to Delta type: a string for a primitive, a dict for a nested type."""- schema = json.loads(delta_table.schema().to_json())+ schema = json.loads(schema_json)return {field["name"]: field["type"] for field in schema.get("fields", [])}@@ -544,12 +545,24 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[stdelta_table_ref = DeltaTableRef(resource_name=resource_name, job=job, logger=log, expect_missing=schema.table_id is None)- delta_table = async_to_sync(delta_table_ref.get_delta_table)()- if delta_table is None:- emit_completed("skipped", reason="no_delta_table")- return {"status": "skipped", "reason": "no_delta_table"}+ # The version gate and the fold read only the version and the schema, which the deltalite open+ # gives for fewer requests. A run that is certain to need the full scan opens with delta-rs at+ # once, so no run opens the table twice unless a fold fails.+ delta_table: Any = None+ log_snapshot = _open_log_snapshot(delta_table_ref) if _fold_is_possible(existing, columns) else None+ if log_snapshot is None:+ delta_table = async_to_sync(delta_table_ref.get_delta_table)()+ if delta_table is None:+ emit_completed("skipped", reason="no_delta_table")+ return {"status": "skipped", "reason": "no_delta_table"}+ delta_version = delta_table.version()+ table_uri = delta_table.table_uri+ read_schema_json = _delta_rs_schema_reader(delta_table)+ else:+ delta_version = log_snapshot.version+ table_uri = log_snapshot.table_uri+ read_schema_json = _constant(log_snapshot.schema_json)- delta_version = delta_table.version()stored_version = _most_recent_computed_version(existing, columns)# Delta versions are only monotonic within one incarnation (see decide_vacuum's identical# caveat): reset_table() purges the log and restarts numbering at 0 for full-refresh/reset tables,@@ -574,7 +587,8 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[streturn {"status": "skipped", "reason": "no_columns"}folded = _fold_since_stored_version(- delta_table=delta_table,+ table_uri=table_uri,+ read_schema_json=read_schema_json,storage_options=delta_table_ref.get_storage_options(),existing=existing,columns=columns,@@ -585,6 +599,15 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[strow_count, stats_by_column = foldedbasis = "incremental"else:+ if delta_table is None:+ # The fold failed, and the full scan needs the per-file statistics that only the+ # delta-rs handle holds. That handle can be at a later version than the snapshot above,+ # so the statistics are stored for the version that was scanned.+ delta_table = async_to_sync(delta_table_ref.get_delta_table)()+ if delta_table is None:+ emit_completed("skipped", reason="no_delta_table")+ return {"status": "skipped", "reason": "no_delta_table"}+ delta_version = delta_table.version()add_actions = delta_table.get_add_actions(flatten=True)if add_actions.num_rows == 0:emit_completed("skipped", reason="no_files")@@ -612,9 +635,62 @@ def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[streturn {"status": "done", "columns": len(stats_by_column), "row_count": row_count, "basis": basis}+def _fold_is_possible(existing: dict[str, WarehouseColumnStatistics], columns: dict[str, Any]) -> bool:+ """Whether the stored statistics can take an incremental fold at all (see `_fold_since_stored_version`)."""+ base_version = _most_recent_computed_version(existing, columns)+ last_full_scan = _most_recent_full_scan_at(existing, columns)+ return (+ base_version is not None+ and last_full_scan is not None+ and timezone.now() - last_full_scan < MAX_RECOMPUTE_INTERVAL+ )+++@frozen+class _LogSnapshot:+ table_uri: str+ version: int+ schema_json: str+++def _open_log_snapshot(delta_table_ref: Any) -> _LogSnapshot | None:+ """The table URI, the latest version and the schema JSON, read through a deltalite open, or None.++ deltalite loads the same snapshot as delta-rs (the newest commit at the time of the open) and+ reads the checkpoint in one request. The handle is released here, so its file list does not+ stay in memory. None covers a missing table, a log that deltalite cannot load, and a table that+ deltalite does not support. The caller then opens with delta-rs, which keeps the handling of+ those cases where it was.+ """+ import deltalite # noqa: PLC0415 — heavy dep kept off this module's flag-check import path+ from asgiref.sync import async_to_sync # noqa: PLC0415++ try:+ table_uri = async_to_sync(delta_table_ref.get_table_uri)()+ table = deltalite.DeltaLiteTable.open(table_uri, delta_table_ref.get_storage_options())+ return _LogSnapshot(table_uri=table_uri, version=table.version(), schema_json=table.schema_json())+ except Exception:+ return None+++def _delta_rs_schema_reader(delta_table: Any) -> Callable[[], str]:+ def read() -> str:+ return delta_table.schema().to_json()++ return read+++def _constant(value: str) -> Callable[[], str]:+ def read() -> str:+ return value++ return read++def _fold_since_stored_version(*,- delta_table: Any,+ table_uri: str,+ read_schema_json: Callable[[], str],storage_options: dict[str, str],existing: dict[str, WarehouseColumnStatistics],columns: dict[str, Any],@@ -630,17 +706,16 @@ def _fold_since_stored_version(would never fall back to a full scan at all."""base_version = _most_recent_computed_version(existing, columns)- last_full_scan = _most_recent_full_scan_at(existing, columns)- if base_version is None or last_full_scan is None or timezone.now() - last_full_scan >= MAX_RECOMPUTE_INTERVAL:+ if base_version is None or not _fold_is_possible(existing, columns):return Nonetry:return _fold_commit_stats(existing=existing,columns=columns,- delta_schema_fields=_delta_schema_fields(delta_table),+ delta_schema_fields=_delta_schema_fields(read_schema_json()),base_version=base_version,delta_version=delta_version,- read_commit_actions=lambda version: _read_commit_actions(delta_table.table_uri, storage_options, version),+ read_commit_actions=lambda version: _read_commit_actions(table_uri, storage_options, version),)except Exception as e:# A commit file the log retention already removed is expected; anything else is adiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.pyindex 8fa7b9981c4f..423bd3d3df83 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py@@ -1,6 +1,7 @@import jsonimport uuidimport datetime as dt+import tempfileimport threadingfrom decimal import Decimalfrom typing import Any@@ -13,6 +14,8 @@ from django.test.utils import CaptureQueriesContextfrom django.utils import timezoneimport pyarrow as pa+import deltalake+import deltalitefrom parameterized import parameterizedfrom temporalio.testing import ActivityEnvironment@@ -34,6 +37,8 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitieComputeTableStatisticsInputs,ComputeTableStatisticsWorkflow,_aggregate_add_action_stats,+ _LogSnapshot,+ _open_log_snapshot,_parse_commit_actions,_parse_log_value,compute_table_statistics_activity,@@ -178,6 +183,55 @@ class TestParseLogValue:assert _parse_log_value("decimal(10,2)", Decimal("1.505")) == Decimal("1.50")+def _local_ref(uri: str) -> MagicMock:+ ref = MagicMock()+ ref.get_table_uri = AsyncMock(return_value=uri)+ ref.get_storage_options.return_value = {}+ return ref+++class TestOpenLogSnapshot:+ @parameterized.expand([("one_commit", 1), ("checkpoint_and_later_commits", 14)])+ def test_matches_the_delta_rs_snapshot(self, _name: str, commits: int) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ uri = f"{tmp}/table"+ for index in range(commits):+ deltalake.write_deltalake(+ uri,+ pa.table({"id": [index], "amount": [Decimal("1.50")]}),+ mode="append",+ configuration={"delta.checkpointInterval": "10"},+ )++ snapshot = _open_log_snapshot(_local_ref(uri))+ expected = deltalake.DeltaTable(uri)++ assert snapshot is not None+ assert (snapshot.table_uri, snapshot.version) == (uri, expected.version())+ assert json.loads(snapshot.schema_json) == json.loads(expected.schema().to_json())++ deltalake.write_deltalake(uri, pa.table({"id": [99], "amount": [Decimal("2.50")]}), mode="append")+ later = _open_log_snapshot(_local_ref(uri))+ assert later is not None and later.version == expected.version() + 1++ @parameterized.expand(+ [+ ("missing_table", None),+ ("table_deltalite_does_not_support", deltalite.DeltaLiteUnsupportedTableError("deletion vectors")),+ ("object_store_error", OSError("Generic S3 error: operation timed out")),+ ]+ )+ def test_gives_no_snapshot_so_the_caller_opens_with_delta_rs(self, _name: str, error: Exception | None) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ uri = f"{tmp}/table"+ if error is None:+ assert _open_log_snapshot(_local_ref(uri)) is None+ return+ deltalake.write_deltalake(uri, pa.table({"id": [1]}))+ with patch.object(deltalite.DeltaLiteTable, "open", side_effect=error):+ assert _open_log_snapshot(_local_ref(uri)) is None++@pytest.mark.django_dbclass TestComputeTableStatisticsSync:def _team(self, *, ai_approved: bool = False) -> Team:@@ -296,6 +350,63 @@ class TestComputeTableStatisticsSync:assert stat.has_min_max is Trueassert stat.computed_for_delta_version == 9+ @parameterized.expand(+ [+ # (name, stored statistics exist, snapshot version, commit files are readable,+ # expected status, expected basis, version the statistics are stored for, delta-rs opens)+ ("fold_needs_no_delta_rs_open", True, 9, True, "done", "incremental", 9, 0),+ ("unchanged_version_needs_no_delta_rs_open", True, 7, True, "skipped", None, 7, 0),+ ("failed_fold_scans_the_delta_rs_snapshot", True, 9, False, "done", "full", 10, 1),+ ("first_computation_opens_with_delta_rs_only", False, None, True, "done", "full", 10, 1),+ ]+ )+ def test_table_opens_by_path(+ self,+ _name: str,+ has_stored: bool,+ snapshot_version: int | None,+ commits_readable: bool,+ expected_status: str,+ expected_basis: str | None,+ expected_version: int,+ delta_rs_opens: int,+ ) -> None:+ team = self._team()+ schema, table, _ = self._schema_table_job(team)+ if has_stored:+ self._stored(team, table)+ commits = {+ 8: [{"commitInfo": {"operation": "WRITE"}}, self._add(10, amount=(1, 60, 1))],+ 9: [{"commitInfo": {"operation": "WRITE"}}, self._add(5, amount=(3, 7, 0))],+ }++ def read_commit(_uri: str, _options: dict, version: int) -> list[dict[str, Any]]:+ if not commits_readable:+ raise FileNotFoundError("no commit")+ return commits[version]++ add_actions = pa.table({"num_records": [99], "null_count.amount": [0], "min.amount": [1], "max.amount": [1]})+ helper = self._mock_delta(add_actions, version=10)+ schema_json = json.dumps({"type": "struct", "fields": [{"name": "amount", "type": "long"}]})+ snapshot = (+ _LogSnapshot(table_uri="s3://bucket/data/stripe_charge", version=snapshot_version, schema_json=schema_json)+ if snapshot_version is not None+ else None+ )+ with (+ patch.object(comp, "_read_commit_actions", side_effect=read_commit),+ patch.object(comp, "_open_log_snapshot", return_value=snapshot) as open_snapshot,+ patch(DELTA_HELPER_PATH, return_value=helper),+ ):+ result = compute_table_statistics_sync(team.id, schema.id)++ assert result["status"] == expected_status+ assert result.get("basis") == expected_basis+ assert open_snapshot.call_count == int(has_stored)+ assert helper.get_delta_table.await_count == delta_rs_opens+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")+ assert stat.computed_for_delta_version == expected_version+def test_a_fold_does_not_reset_the_full_scan_clock(self) -> None:# Regression: the fold gate must read the age of the last *full scan*, not the age of the# last write. If a fold bumped the same clock a full scan does, folding more often than