: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): recover account-property staging from a reset delta table (#109120)
Tom Owers9aefa2a6ebde
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.pyindex 8b8290859806..fc59ea922012 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink.py@@ -7,6 +7,7 @@ from django.conf import settingsimport pyarrow as paimport deltalakeimport pyarrow.fs as pa_fs+import deltalake.exceptionsfrom pyarrow.parquet import ParquetFile, write_tablefrom structlog.types import FilteringBoundLogger@@ -37,11 +38,25 @@ _PARQUET_BATCH_SIZE = 50_000# workflow_activities/repartition_table.py._MISSING_OBJECT_ERROR_NEEDLE = "the specified key does not exist"+# delta-rs raises this DeltaError, instead of the OSError above, when the pinned version wasn't+# vacuumed but the whole table was reset and recommitted from scratch by a later materialize run+# (data-modeling's reset_table/full_refresh purges the table's _delta_log along with its data) — the+# log the reader replays now ends at the fresh table's latest commit, which is lower than the version+# pinned before the reset. Same queued-for-hours race as the vacuum case above, different delta-rs+# entry point.+_LOG_SEGMENT_VERSION_MISMATCH_NEEDLE = "not the same as the specified end version"+def _is_missing_object_error(error: BaseException) -> bool:return isinstance(error, OSError) and _MISSING_OBJECT_ERROR_NEEDLE in str(error).lower()+def _is_stale_pinned_version_error(error: BaseException) -> bool:+ if _is_missing_object_error(error):+ return True+ return isinstance(error, deltalake.exceptions.DeltaError) and _LOG_SEGMENT_VERSION_MISMATCH_NEEDLE in str(error)++class AccountPropertyRowSink:"""Projects a committed materialized-view Delta snapshot into job-scoped Parquet files."""@@ -146,18 +161,20 @@ class AccountPropertyRowSink:await self.clear()try:await self._stage_committed_files(table_uri, delta_version)- except OSError as error:- if not _is_missing_object_error(error):+ except (OSError, deltalake.exceptions.DeltaError) as error:+ if not _is_stale_pinned_version_error(error):raise# `delta_version` was pinned right after the materialize run that produced it, but the# staging child workflow that calls this can sit queued for hours before it actually# runs. If the same view gets materialized again in the meantime, that run's vacuum# (DELTA_TABLE_RETENTION_HOURS) can reclaim the pinned version's files before we read- # them. Re-stage from whatever is committed now instead: vacuum never removes a file the- # current version still references, so this snapshot can't be pulled out from under us- # the same way.+ # them, or a full refresh can reset the table and recommit it from scratch, leaving the+ # pinned version behind entirely. Re-stage from whatever is committed now instead: vacuum+ # never removes a file the current version still references, and a freshly reset table's+ # latest version is by definition still there, so this snapshot can't be pulled out from+ # under us the same way.await self.logger.awarning(- f"Delta version {delta_version} was vacuumed before staging read it; "+ f"Delta version {delta_version} was vacuumed or superseded before staging read it; ""re-staging the current committed snapshot instead")await self.clear()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.pyindex 67a45f32fe22..c4bd893cf8bb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/account_property_row_sink_test.py@@ -9,6 +9,7 @@ from django.db import OperationalErrorimport pyarrow as paimport pyarrow.parquet as pq+import deltalake.exceptionsfrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (AccountPropertySourceProjection,@@ -223,6 +224,65 @@ async def test_stage_delta_snapshot_falls_back_to_latest_version_after_a_vacuum_assert stage_chunk.await_args.args[1].to_pydict() == fresh_table.to_pydict()+async def test_stage_delta_snapshot_falls_back_to_latest_version_after_a_full_refresh_race() -> None:+ # Same queued-for-hours race as the vacuum test above, but the intervening materialize run did a+ # full refresh instead: it reset the table and recommitted it from scratch, so the pinned version+ # isn't just missing its files — the log itself no longer reaches that version. delta-rs surfaces+ # that as a DeltaError ("LogSegment end version ... not the same as the specified end version ...")+ # rather than the OSError the vacuum case raises.+ sink = _sink()+ fresh_table = pa.table({"organization_id": ["org-1"], "mrr": [100]})+ fresh_output = pa.BufferOutputStream()+ pq.write_table(fresh_table, fresh_output)++ current_delta_table = MagicMock()+ current_delta_table.file_uris.return_value = ["s3://data-warehouse/dlt/current.parquet"]++ def _open_delta_table(table_uri, version, storage_options):+ if version == 7:+ raise deltalake.exceptions.DeltaError(+ "Kernel error: Generic delta kernel error: LogSegment end version 0 not the same "+ "as the specified end version 7"+ )+ return current_delta_table++ filesystem = MagicMock()+ filesystem.open_input_file.return_value = pa.BufferReader(fresh_output.getvalue())++ with (+ patch.object(+ sink,+ "_get_projection",+ new=AsyncMock(+ return_value=[+ AccountPropertySourceProjection(+ key_column="organization_id",+ columns=frozenset({"organization_id", "mrr"}),+ )+ ]+ ),+ ),+ patch.object(sink, "clear", new=AsyncMock()) as clear,+ patch.object(sink, "stage_chunk", new=AsyncMock()) as stage_chunk,+ patch.object(sink, "_get_fs", return_value=filesystem),+ patch(f"{_MODULE}.deltalake.DeltaTable", side_effect=_open_delta_table) as open_delta,+ patch(f"{_MODULE}.delta_storage_options", return_value={"region_name": "us-east-1"}),+ ):+ staged = await sink.stage_delta_snapshot("s3://data-warehouse/dlt/table", 7)++ assert staged is True+ assert clear.await_count == 2+ cast(AsyncMock, sink.logger.awarning).assert_awaited_once()+ assert open_delta.call_args_list == [+ call("s3://data-warehouse/dlt/table", version=7, storage_options={"region_name": "us-east-1"}),+ call("s3://data-warehouse/dlt/table", version=None, storage_options={"region_name": "us-east-1"}),+ ]+ stage_chunk.assert_awaited_once()+ assert stage_chunk.await_args is not None+ assert stage_chunk.await_args.args[1].to_pydict() == fresh_table.to_pydict()++@pytest.mark.asyncioasync def test_retry_clears_its_staged_files_and_sweeps_abandoned_jobs() -> None:sink = _sink()