: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(data-imports): recover account-property staging from a vacuumed delta snapshot (#108356)
Tom Owers787dba633e83
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 7c8ca7700a6f..8b8290859806 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@@ -32,6 +32,15 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delABANDONED_STAGED_PREFIX_TTL = timedelta(days=7)_PARQUET_BATCH_SIZE = 50_000+# Same fixed AWS message pyarrow's S3FileSystem surfaces as a bare OSError for a GetObject against a+# key that no longer exists — matched the same way as the equivalent NoSuchKey race in+# workflow_activities/repartition_table.py.+_MISSING_OBJECT_ERROR_NEEDLE = "the specified key does not exist"+++def _is_missing_object_error(error: BaseException) -> bool:+ return isinstance(error, OSError) and _MISSING_OBJECT_ERROR_NEEDLE in str(error).lower()+class AccountPropertyRowSink:"""Projects a committed materialized-view Delta snapshot into job-scoped Parquet files."""@@ -135,6 +144,27 @@ class AccountPropertyRowSink:return Falseawait self.clear()+ try:+ await self._stage_committed_files(table_uri, delta_version)+ except OSError as error:+ if not _is_missing_object_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.+ await self.logger.awarning(+ f"Delta version {delta_version} was vacuumed before staging read it; "+ "re-staging the current committed snapshot instead"+ )+ await self.clear()+ await self._stage_committed_files(table_uri, delta_version=None)+ return True++ async def _stage_committed_files(self, table_uri: str, delta_version: int | None) -> None:delta_table = await asyncio.to_thread(deltalake.DeltaTable,table_uri,@@ -152,7 +182,6 @@ class AccountPropertyRowSink:chunk += 1finally:await asyncio.to_thread(input_file.close)- return Trueasync def clear(self) -> None:"""Drop this job's prior attempt and sweep abandoned sibling jobs."""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 865e4169d77c..67a45f32fe22 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@@ -1,7 +1,8 @@from datetime import UTC, datetime, timedelta+from typing import castimport pytest-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, call, patchfrom django.conf import settingsfrom django.db import OperationalError@@ -29,6 +30,7 @@ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.codef _sink() -> AccountPropertyRowSink:logger = MagicMock()logger.adebug = AsyncMock()+ logger.awarning = AsyncMock()return AccountPropertyRowSink(team_id=7,binding=saved_query_binding("019f0000-0000-7000-8000-000000000001"),@@ -158,6 +160,69 @@ async def test_stages_an_exact_delta_snapshot_after_materialization() -> None:assert stage_chunk.await_args.args[1].to_pydict() == table.to_pydict()+async def test_stage_delta_snapshot_falls_back_to_latest_version_after_a_vacuum_race() -> None:+ # The pinned delta_version can sit queued behind the staging child workflow for hours. If the+ # same view materializes again in the meantime, its vacuum can reclaim that version's files+ # before we read them (AWS NO_SUCH_KEY). Staging must recover by re-reading whatever is+ # committed now instead of failing the whole sync.+ sink = _sink()+ fresh_table = pa.table({"organization_id": ["org-1"], "mrr": [100]})+ fresh_output = pa.BufferOutputStream()+ pq.write_table(fresh_table, fresh_output)++ vacuumed_delta_table = MagicMock()+ vacuumed_delta_table.file_uris.return_value = ["s3://data-warehouse/dlt/vacuumed.parquet"]+ 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):+ return vacuumed_delta_table if version == 7 else current_delta_table++ def _open_input_file(path):+ if path == "data-warehouse/dlt/vacuumed.parquet":+ raise OSError(+ "AWS Error NO_SUCH_KEY during GetObject operation: The specified key does not "+ "exist. (Request ID: TESTREQUESTID)"+ )+ return pa.BufferReader(fresh_output.getvalue())++ filesystem = MagicMock()+ filesystem.open_input_file.side_effect = _open_input_file++ 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()