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.

fix(data-imports): bound the queryable-files copy retry to survive a longer vacuum race (#75927)

Tom Owers2f5e0aa3cff5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py
index 03286464762d..7df20ffdedbe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py
@@ -80,6 +80,63 @@ class TestPrepareS3FilesForQuerying:
refresh_file_uris.assert_awaited_once()
assert cp_file.await_args_list[-1].args[0] == "s3://bucket/job/my_table/part-1.parquet"
+ async def test_retries_past_a_second_consecutive_vanished_file(self):
+ # Regression for a race where a zombie compact/vacuum pass outlived a single retry:
+ # the source file vanished on both the first attempt and the retry (a different file
+ # each time), which a retry-once loop would give up on instead of trying a third time.
+ cp_file = AsyncMock(
+ side_effect=[
+ FileNotFoundError("s3://bucket/job/my_table/part-0.parquet"),
+ FileNotFoundError("s3://bucket/job/my_table/part-1.parquet"),
+ None,
+ ]
+ )
+ s3 = _fake_s3(_cp_file=cp_file)
+ refresh_file_uris = AsyncMock(
+ side_effect=[
+ ["s3://bucket/job/my_table/part-1.parquet"],
+ ["s3://bucket/job/my_table/part-2.parquet"],
+ ]
+ )
+
+ with (
+ patch.object(util_module, "aget_s3_client", return_value=_FakeS3CM(s3)),
+ patch("asyncio.sleep", new_callable=AsyncMock),
+ ):
+ await prepare_s3_files_for_querying(
+ folder_path="job",
+ table_name="my_table",
+ file_uris=["s3://bucket/job/my_table/part-0.parquet"],
+ delete_existing=False,
+ refresh_file_uris=refresh_file_uris,
+ )
+
+ assert refresh_file_uris.await_count == 2
+ assert cp_file.await_args_list[-1].args[0] == "s3://bucket/job/my_table/part-2.parquet"
+
+ async def test_gives_up_after_max_attempts_exhausted(self):
+ # The retry loop is bounded: a source file that keeps vanishing on every attempt must
+ # eventually raise instead of retrying forever.
+ cp_file = AsyncMock(side_effect=FileNotFoundError("s3://bucket/job/my_table/part-0.parquet"))
+ s3 = _fake_s3(_cp_file=cp_file)
+ refresh_file_uris = AsyncMock(return_value=["s3://bucket/job/my_table/part-0.parquet"])
+
+ with (
+ patch.object(util_module, "aget_s3_client", return_value=_FakeS3CM(s3)),
+ patch("asyncio.sleep", new_callable=AsyncMock),
+ ):
+ with pytest.raises(FileNotFoundError):
+ await prepare_s3_files_for_querying(
+ folder_path="job",
+ table_name="my_table",
+ file_uris=["s3://bucket/job/my_table/part-0.parquet"],
+ delete_existing=False,
+ refresh_file_uris=refresh_file_uris,
+ )
+
+ assert cp_file.await_count == util_module._COPY_FILES_MAX_ATTEMPTS
+ assert refresh_file_uris.await_count == util_module._COPY_FILES_MAX_ATTEMPTS - 1
+
async def test_propagates_vanished_source_file_without_refresh_callback(self):
# Callers that don't pass refresh_file_uris keep today's behavior: the race still
# surfaces as an error instead of being retried blindly.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/util.py b/products/warehouse_sources/backend/temporal/data_imports/util.py
index 9d9e3fbb76ac..4e13dcbbf653 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/util.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/util.py
@@ -57,6 +57,12 @@ class PostHogInternalDatabaseError(Exception):
# 10 mins buffer to avoid deleting files Clickhouse may be reading
S3_DELETE_TIME_BUFFER = 600
+# A zombie compaction+vacuum pass (a heartbeat-timed-out activity attempt still running) can keep
+# deleting source files for as long as its own rewrite takes - documented up to ~45s for a
+# fragmented table in delta_table_helper.py - which can outlive a single retry. Bound the retries
+# with backoff instead, mirroring _purge_s3_prefix's approach to the same class of race.
+_COPY_FILES_MAX_ATTEMPTS = 4
+
def is_posthog_team(team_id: int) -> bool:
DEBUG: bool = get_from_env("DEBUG", False, type_cast=str_to_bool)
@@ -184,18 +190,27 @@ async def prepare_s3_files_for_querying(
# S3's SlowDown rate limiting on the destination prefix.
await s3._cp_file(file, f"{s3_path_for_querying}/{file_name}")
- try:
- await asyncio.gather(*[copy_file(file) for file in file_uris])
- except FileNotFoundError as e:
- if refresh_file_uris is None:
- raise
- # A concurrent compact/vacuum pass on the same Delta table (e.g. a zombie attempt
- # from a heartbeat timeout still running) can physically delete a source file
- # between our listing and this copy. Re-listing picks up wherever that pass left
- # the table and retries once against the current file set.
- await _log(f"Source file vanished mid-copy, retrying with a fresh file listing: {e}", level="error")
- file_uris = await refresh_file_uris()
- await asyncio.gather(*[copy_file(file) for file in file_uris])
+ attempt = 0
+ while True:
+ attempt += 1
+ try:
+ await asyncio.gather(*[copy_file(file) for file in file_uris])
+ break
+ except FileNotFoundError as e:
+ if refresh_file_uris is None or attempt >= _COPY_FILES_MAX_ATTEMPTS:
+ raise
+ # A concurrent compact/vacuum pass on the same Delta table (e.g. a zombie attempt
+ # from a heartbeat timeout still running) can physically delete a source file
+ # between our listing and this copy. Re-listing picks up wherever that pass left
+ # the table; back off first so a still-running pass has time to finish before we
+ # retry against it again.
+ await _log(
+ f"Source file vanished mid-copy (attempt {attempt}/{_COPY_FILES_MAX_ATTEMPTS}), "
+ f"retrying with a fresh file listing: {e}",
+ level="error",
+ )
+ await asyncio.sleep(2**attempt)
+ file_uris = await refresh_file_uris()
# Delete existing files after copying new ones
if delete_existing and files_to_delete: