: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(customer-analytics): tolerate snapshot files removed by compaction (#104751)
posthog[bot]396935b02a12
diff --git a/products/customer_analytics/backend/logic/account_property_sync.py b/products/customer_analytics/backend/logic/account_property_sync.pyindex 2083600da5e5..f7df3d0cbe23 100644--- a/products/customer_analytics/backend/logic/account_property_sync.py+++ b/products/customer_analytics/backend/logic/account_property_sync.py@@ -7,7 +7,7 @@ from dataclasses import fieldfrom datetime import date, datetime, timefrom decimal import Decimalfrom enum import StrEnum-from typing import Any+from typing import Any, Protocolfrom uuid import UUIDimport pyarrow as pa@@ -74,6 +74,22 @@ class AppliedSourceValues:failed: bool+class _SnapshotS3Client(Protocol):+ async def _ls(self, path: str, *, detail: bool) -> dict[str, dict[str, Any]] | list[dict[str, Any]]: ...++ async def _cat_file(self, path: str) -> bytes: ...++ async def _pipe_file(self, path: str, data: bytes) -> None: ...++ async def _rm(self, paths: str | list[str], *, recursive: bool = False) -> None: ...+++@frozen+class _SnapshotMerge:+ hashes: dict[str, str]+ complete: bool++@frozen(frozen=False)class SourceSyncState:source: CustomPropertySource@@ -160,31 +176,58 @@ async def _iter_parquet_row_batches(entries = listing.values() if isinstance(listing, dict) else listingfile_paths = sorted(entry["Key"] for entry in entries if entry.get("type") != "directory")for file_path in file_paths:- uri = file_path if file_path.startswith("s3://") else f"s3://{file_path}"- data = await s3_client._cat_file(uri)+ data = await s3_client._cat_file(_s3_uri(file_path))batches = await asyncio.to_thread(_parquet_batches, data)while (batch := await asyncio.to_thread(next, batches, None)) is not None:yield await asyncio.to_thread(batch.to_pylist)+def _s3_uri(key: str) -> str:+ return key if key.startswith("s3://") else f"s3://{key}"+++def _s3_key(key: str) -> str:+ return key.removeprefix("s3://").lstrip("/")+++async def _list_snapshot_files(s3_client: _SnapshotS3Client, prefix: str) -> list[str]:+ try:+ listing = await s3_client._ls(f"s3://{prefix}/", detail=True)+ except FileNotFoundError:+ return []+ entries = listing.values() if isinstance(listing, dict) else listing+ entries_by_key = sorted(+ (entry for entry in entries if entry.get("type") != "directory"), key=lambda entry: entry["Key"]+ )+ entries_without_timestamp = [entry for entry in entries_by_key if entry.get("LastModified") is None]+ entries_with_timestamp = sorted(+ (entry for entry in entries_by_key if entry.get("LastModified") is not None),+ key=lambda entry: entry["LastModified"],+ )+ return [entry["Key"] for entry in [*entries_without_timestamp, *entries_with_timestamp]]+++async def _merge_snapshot_files(s3_client: _SnapshotS3Client, file_keys: list[str]) -> _SnapshotMerge:+ hashes: dict[str, str] = {}+ complete = True+ for key in file_keys:+ try:+ data = await s3_client._cat_file(_s3_uri(key))+ except FileNotFoundError:+ complete = False+ continue+ for row in await asyncio.to_thread(_decode_parquet_rows, data):+ hashes[str(row["external_id"])] = str(row["value_hash"])+ return _SnapshotMerge(hashes=hashes, complete=complete)++async def _read_snapshot_hashes(team_id: int, binding: WarehouseBinding, source_id: str, segment: AccountPropertySyncSegment) -> dict[str, str]:prefix = account_property_snapshot_prefix(team_id, binding, source_id, segment.value)- hashes: dict[str, str] = {}async with aget_s3_client() as s3_client:- try:- listing = await s3_client._ls(f"s3://{prefix}/", detail=True)- except FileNotFoundError:- return hashes- entries = listing.values() if isinstance(listing, dict) else listing- files = sorted(entry["Key"] for entry in entries if entry.get("type") != "directory")- for file_path in files:- uri = file_path if file_path.startswith("s3://") else f"s3://{file_path}"- data = await s3_client._cat_file(uri)- for row in await asyncio.to_thread(_decode_parquet_rows, data):- hashes[str(row["external_id"])] = str(row["value_hash"])- return hashes+ merge = await _merge_snapshot_files(s3_client, await _list_snapshot_files(s3_client, prefix))+ return merge.hashes if merge.complete else {}async def _write_snapshot_hashes(@@ -201,26 +244,24 @@ async def _write_snapshot_hashes(prefix = account_property_snapshot_prefix(team_id, binding, source_id, segment.value)path = f"{prefix}/{job_id}.parquet"async with aget_s3_client() as s3_client:- try:- listing = await s3_client._ls(f"s3://{prefix}/", detail=True)- except FileNotFoundError:- listing = []- entries = listing.values() if isinstance(listing, dict) else listing- existing_files = sorted(entry["Key"] for entry in entries if entry.get("type") != "directory")- merged: dict[str, str] = {}- for file_path in existing_files:- uri = file_path if file_path.startswith("s3://") else f"s3://{file_path}"- data = await s3_client._cat_file(uri)- for row in await asyncio.to_thread(_decode_parquet_rows, data):- merged[str(row["external_id"])] = str(row["value_hash"])- merged.update(hashes)+ existing_files = await _list_snapshot_files(s3_client, prefix)+ merge = await _merge_snapshot_files(s3_client, existing_files)+ merged = {**merge.hashes, **hashes} if merge.complete else hashessnapshot = await asyncio.to_thread(_encode_snapshot, merged)- await s3_client._pipe_file(f"s3://{path}", snapshot)- stale = [file_path for file_path in existing_files if not file_path.endswith(f"/{job_id}.parquet")]+ await s3_client._pipe_file(_s3_uri(path), snapshot)+ if not merge.complete:+ return+ stale = [file_path for file_path in existing_files if _s3_key(file_path) != _s3_key(path)]if stale:- await s3_client._rm(- [file_path if file_path.startswith("s3://") else f"s3://{file_path}" for file_path in stale]- )+ stale_uris = [_s3_uri(file_path) for file_path in stale]+ try:+ await s3_client._rm(stale_uris)+ except FileNotFoundError:+ for stale_uri in stale_uris:+ try:+ await s3_client._rm(stale_uri)+ except FileNotFoundError:+ continuedef _matching_account_ids(diff --git a/products/customer_analytics/backend/logic/account_property_sync_test.py b/products/customer_analytics/backend/logic/account_property_sync_test.pyindex 51cf2f8f0c63..c0e31fda93fb 100644--- a/products/customer_analytics/backend/logic/account_property_sync_test.py+++ b/products/customer_analytics/backend/logic/account_property_sync_test.py@@ -1,4 +1,7 @@+from collections.abc import AsyncIterator+from contextlib import AbstractContextManagerfrom datetime import UTC, datetime+from typing import Any, Generic, TypeVarfrom uuid import uuid4import pytest@@ -11,6 +14,7 @@ import pyarrow as paimport pyarrow.parquet as pqfrom asgiref.sync import async_to_sync+from products.customer_analytics.backend.logic import account_property_sync as apsfrom products.customer_analytics.backend.logic.account_property_runs import (AccountPropertySyncRunContext,start_account_property_sync_runs,@@ -20,17 +24,24 @@ from products.customer_analytics.backend.logic.account_property_sync import (AccountPropertySyncSegment,AppliedSourceValues,_iter_parquet_row_batches,+ _list_snapshot_files,_mark_completed_and_maybe_cleanup,_matching_account_ids,+ _merge_snapshot_files,+ _read_snapshot_hashes,_source_values,_value_hash,+ _write_snapshot_hashes,run_account_property_segment_sync,)from products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRunfrom products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixinfrom products.customer_analytics.backend.test.factories import create_account, create_custom_property_definitionfrom products.warehouse_sources.backend.facade.hooks import saved_query_binding-from products.warehouse_sources.backend.facade.temporal import account_property_job_staged_prefix+from products.warehouse_sources.backend.facade.temporal import (+ account_property_job_staged_prefix,+ account_property_snapshot_prefix,+)_MODULE = "products.customer_analytics.backend.logic.account_property_sync"DataWarehouseSavedQuery = apps.get_model("data_modeling", "DataWarehouseSavedQuery")@@ -113,6 +124,48 @@ class AccountPropertySegmentTest(TeamScopedTestMixin, BaseTest):assert (run.status, run.phase) == ("completed", "completed")assert (run.rows_read, run.changed, run.existing, run.produced) == (1, 1, 1, 1)+ def test_segment_sync_completes_when_snapshot_file_disappears_after_listing(self) -> None:+ source = self._create_source()+ source.consecutive_failures = 4+ source.save(update_fields=["consecutive_failures"])+ start_account_property_sync_runs(+ AccountPropertySyncRunContext(+ team_id=self.team.id,+ saved_query_id=str(source.saved_query_id),+ job_id="job-1",+ ),+ workflow_id="stage-workflow-job-1",+ workflow_run_id="00000000-0000-4000-8000-000000000001",+ )+ client = MagicMock()+ client._ls = AsyncMock(return_value=[{"Key": "prefix/deleted.parquet", "type": "file"}])+ client._cat_file = AsyncMock(side_effect=FileNotFoundError())++ async def no_batches(*args: object) -> AsyncIterator[list[dict[str, Any]]]:+ for _ in range(0):+ yield []++ with (+ patch(f"{_MODULE}._segment_already_completed", new=AsyncMock(return_value=False)),+ patch(f"{_MODULE}._enabled_sources", return_value=[source]),+ patch(f"{_MODULE}.aget_s3_client", return_value=_S3ClientContext(client)),+ patch(f"{_MODULE}._iter_parquet_row_batches", side_effect=no_batches),+ patch(f"{_MODULE}._mark_completed_and_maybe_cleanup", new=AsyncMock()),+ ):+ async_to_sync(run_account_property_segment_sync)(+ team_id=self.team.id,+ binding=saved_query_binding(str(source.saved_query_id)),+ job_id="job-1",+ segment=AccountPropertySyncSegment.TRACKED,+ final_attempt=True,+ )++ run = CustomPropertySyncRun.objects.for_team(self.team.id).get(source=source, segment="tracked")+ source.refresh_from_db()+ assert run.status == "completed"+ assert source.consecutive_failures == 4+ assert source.is_enabled+def test_final_attempt_persists_a_failed_run(self) -> None:source = self._create_source()start_account_property_sync_runs(@@ -208,14 +261,17 @@ class AccountPropertySegmentTest(TeamScopedTestMixin, BaseTest):assert run.finished_at is not None-class _S3ClientContext:- def __init__(self, client: MagicMock) -> None:+_T = TypeVar("_T")+++class _S3ClientContext(Generic[_T]):+ def __init__(self, client: _T) -> None:self.client = client- async def __aenter__(self) -> MagicMock:+ async def __aenter__(self) -> _T:return self.client- async def __aexit__(self, *args) -> bool:+ async def __aexit__(self, *args: object) -> bool:return False@@ -366,3 +422,178 @@ async def test_staged_parquet_is_deleted_only_after_both_segments_complete() ->f"s3://{account_property_job_staged_prefix(7, binding, 'job-1')}/",recursive=True,)+++class _FakeS3:+ def __init__(self) -> None:+ self.store: dict[str, bytes] = {}+ self.times: dict[str, int] = {}+ self._clock = 0++ async def _ls(self, path: str, *, detail: bool = True) -> list[dict[str, Any]]:+ del detail+ prefix = aps._s3_key(path).rstrip("/") + "/"+ entries = [+ {"Key": key, "type": "file", "LastModified": self.times[key]}+ for key in self.store+ if key.startswith(prefix)+ ]+ if not entries:+ raise FileNotFoundError(path)+ return entries++ async def _cat_file(self, path: str) -> bytes:+ key = aps._s3_key(path)+ if key not in self.store:+ raise FileNotFoundError(path)+ return self.store[key]++ async def _pipe_file(self, path: str, data: bytes) -> None:+ self._clock += 1+ key = aps._s3_key(path)+ self.store[key] = data+ self.times[key] = self._clock++ async def _rm(self, paths: str | list[str], *, recursive: bool = False) -> None:+ del recursive+ for path in [paths] if isinstance(paths, str) else paths:+ key = aps._s3_key(path)+ self.store.pop(key, None)+ self.times.pop(key, None)+++def _fake_s3_patch(fake: _FakeS3) -> AbstractContextManager[object]:+ return patch(f"{_MODULE}.aget_s3_client", lambda: _S3ClientContext(fake))+++_SNAPSHOT_BINDING = saved_query_binding("019f0000-0000-7000-8000-000000000002")+_SEGMENT = AccountPropertySyncSegment.TRACKED+++async def _write(fake: _FakeS3, job_id: str, hashes: dict[str, str]) -> None:+ with _fake_s3_patch(fake):+ await _write_snapshot_hashes(7, _SNAPSHOT_BINDING, "src", _SEGMENT, job_id, hashes)+++async def _read(fake: _FakeS3) -> dict[str, str]:+ with _fake_s3_patch(fake):+ return await _read_snapshot_hashes(7, _SNAPSHOT_BINDING, "src", _SEGMENT)+++async def test_snapshot_files_without_timestamps_merge_before_dated_files() -> None:+ client = MagicMock()+ client._ls = AsyncMock(+ return_value=[+ {"Key": "prefix/dated-new.parquet", "type": "file", "LastModified": datetime(2026, 1, 2, tzinfo=UTC)},+ {"Key": "prefix/undated.parquet", "type": "file"},+ {"Key": "prefix/dated-old.parquet", "type": "file", "LastModified": datetime(2026, 1, 1, tzinfo=UTC)},+ ]+ )++ files = await _list_snapshot_files(client, "prefix")++ assert files == ["prefix/undated.parquet", "prefix/dated-old.parquet", "prefix/dated-new.parquet"]+++async def test_snapshot_write_compacts_prior_files_newest_hash_winning() -> None:+ fake = _FakeS3()+ await _write(fake, "job-1", {"a": "h1", "b": "h1"})+ await _write(fake, "job-2", {"b": "h2", "c": "h2"})++ assert len(fake.store) == 1+ assert await _read(fake) == {"a": "h1", "b": "h2", "c": "h2"}+++async def test_snapshot_read_skips_file_deleted_by_concurrent_compaction() -> None:+ fake = _FakeS3()+ await _write(fake, "job-1", {"a": "h1"})+ prefix = account_property_snapshot_prefix(7, _SNAPSHOT_BINDING, "src", _SEGMENT.value)+ listed = await _list_snapshot_files(fake, prefix)+ await fake._rm(listed)++ merge = await _merge_snapshot_files(fake, listed)++ assert merge.hashes == {}+ assert not merge.complete+++async def test_snapshot_read_discards_partial_hashes_when_a_newer_file_disappears() -> None:+ fake = _FakeS3()+ prefix = account_property_snapshot_prefix(7, _SNAPSHOT_BINDING, "src", _SEGMENT.value)+ await fake._pipe_file(f"{prefix}/job-1.parquet", aps._encode_snapshot({"account": "old"}))+ await fake._pipe_file(f"{prefix}/job-2.parquet", aps._encode_snapshot({"account": "new"}))+ original_cat_file = fake._cat_file++ async def _cat_with_missing_newer_file(path: str) -> bytes:+ if path.endswith("/job-2.parquet"):+ raise FileNotFoundError(path)+ return await original_cat_file(path)++ with patch.object(fake, "_cat_file", _cat_with_missing_newer_file):+ hashes = await _read(fake)++ assert hashes == {}+++async def test_snapshot_write_persists_only_current_hashes_after_an_incomplete_merge() -> None:+ fake = _FakeS3()+ prefix = account_property_snapshot_prefix(7, _SNAPSHOT_BINDING, "src", _SEGMENT.value)+ job_1 = f"{prefix}/job-1.parquet"+ job_2 = f"{prefix}/job-2.parquet"+ replacement = f"{prefix}/concurrent.parquet"+ await fake._pipe_file(job_1, aps._encode_snapshot({"account": "old"}))+ await fake._pipe_file(job_2, aps._encode_snapshot({"account": "new"}))+ original_cat_file = fake._cat_file++ async def _cat_then_compact(path: str) -> bytes:+ data = await original_cat_file(path)+ if path.endswith("/job-1.parquet"):+ await fake._pipe_file(replacement, aps._encode_snapshot({"account": "new"}))+ await fake._rm([job_1, job_2])+ return data++ with patch.object(fake, "_cat_file", _cat_then_compact):+ await _write(fake, "job-3", {"other": "value"})++ assert f"{prefix}/job-3.parquet" in fake.store+ assert await _read(fake) == {"account": "new", "other": "value"}+++async def test_snapshot_cleanup_retries_files_after_batch_delete_race() -> None:+ fake = _FakeS3()+ prefix = account_property_snapshot_prefix(7, _SNAPSHOT_BINDING, "src", _SEGMENT.value)+ await fake._pipe_file(f"{prefix}/job-1.parquet", aps._encode_snapshot({"a": "h1"}))+ await fake._pipe_file(f"{prefix}/job-2.parquet", aps._encode_snapshot({"b": "h2"}))+ original_rm = fake._rm+ batch_failed = False++ async def _rm_with_batch_race(paths: str | list[str], *, recursive: bool = False) -> None:+ nonlocal batch_failed+ if isinstance(paths, list) and not batch_failed:+ batch_failed = True+ raise FileNotFoundError(paths[0])+ await original_rm(paths, recursive=recursive)++ with patch.object(fake, "_rm", _rm_with_batch_race):+ await _write(fake, "job-3", {"c": "h3"})++ assert set(fake.store) == {f"{prefix}/job-3.parquet"}+ assert await _read(fake) == {"a": "h1", "b": "h2", "c": "h3"}+++async def test_snapshot_read_propagates_non_missing_file_errors() -> None:+ fake = _FakeS3()+ await _write(fake, "job-1", {"a": "h1"})++ async def _raise_s3_error(path: str) -> bytes:+ raise OSError(f"S3 unavailable: {path}")++ with patch.object(fake, "_cat_file", _raise_s3_error), pytest.raises(OSError, match="S3 unavailable"):+ await _read(fake)