: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-warehouse): publish query folders with fewer s3 requests (#113081)
Tom Owers0eae0270c3c0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 6216703a78a5..83c3e1047566 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -172,7 +172,7 @@ That transport was removed; see git history for the old procedure.HogQL does not read a table's Delta log. Post-load copies the live parquet files into a query folder under the schema's S3 prefix, and `DataWarehouseTable.queryable_folder` names the folder ClickHouse globs (`<folder>/**.parquet`). Readers must always see one complete generation, and S3 has no atomic multi-object update, so a folder is never rewritten while the pointer is on it.- **Timestamped folders.** A sync copies every live file into a fresh `<table>__query_<epoch>_<hex>` folder and moves the pointer. Timestamped folders older than `S3_DELETE_TIME_BUFFER` are removed on later syncs. The cost scales with the table's file count, not with what the sync changed. Warehouse source syncs use this path only as the fallback described below; other callers of `prepare_s3_files_for_querying` (for example data modeling) use it by default.-- **Rotating slots** (every warehouse source sync). The table rotates through `<table>__query_a`, `__query_b` and `__query_c`. A sync picks the slot that stopped being the pointer longest ago, lists it, copies in the live files it lacks, removes the files that are no longer live, and returns it for the pointer flip. The diff is against the listing, so a missed sync or a crash mid-reconcile heals on the next pass. A populated slot is rewritten only when it stopped being the pointer at least `S3_DELETE_TIME_BUFFER` ago; with three slots that instant is one whole sync interval before the current slot took over, so a table synced more often than the buffer still takes the incremental path. Every pointer move is recorded in `sync_type_config["query_folder_state"]` (the active folder, the job that published it, when each slot stopped being the pointer, and since when the record is contiguous). A move the record missed (a crash between the pointer write and the record, or a schema reset) restarts the record, and until it is older than the buffer only an empty slot is used; when no slot is safe the sync falls back to a fresh timestamped folder. A table's first syncs on the slots fill the empty slots in full, and reconciliation takes over from there. The age-based cleanup still removes the timestamped folders a table used before it moved onto the slots, and it never matches the slot names. DuckLake registration tells generations on a reused slot name apart by the job that published them, read from the same record.+- **Rotating slots** (every warehouse source sync). The table rotates through `<table>__query_a`, `__query_b` and `__query_c`. A sync picks the slot that stopped being the pointer longest ago, lists it, copies in the live files it lacks, removes the files that are no longer live, and returns it for the pointer flip. The diff is against the listing, so a missed sync or a crash mid-reconcile heals on the next pass. A populated slot is rewritten only when it stopped being the pointer at least `S3_DELETE_TIME_BUFFER` ago; with three slots that instant is one whole sync interval before the current slot took over, so a table synced more often than the buffer still takes the incremental path. Every pointer move is recorded in `sync_type_config["query_folder_state"]` (the active folder, the job that published it, when each slot stopped being the pointer, and since when the record is contiguous). A move the record missed (a crash between the pointer write and the record, or a schema reset) restarts the record, and until it is older than the buffer only an empty slot is used; when no slot is safe the sync falls back to a fresh timestamped folder. A table's first syncs on the slots fill the empty slots in full, and reconciliation takes over from there. The age-based cleanup still removes the timestamped folders a table used before it moved onto the slots, and it never matches the slot names. A publish into a slot runs that cleanup only while a timestamped folder can exist: after the record shows a timestamped folder as the pointer or a missed pointer move, until one scan ran at least `S3_DELETE_TIME_BUFFER` later, and on the first publish of each daily window. A folder that no record shows (a publish that failed after its copy, or a delete that failed) thus stays for at most one day plus one sync interval. A fallback publish always runs the cleanup. A slot that the record shows as the pointer within the buffer is not listed, because the listing could only confirm that it is not usable. The copy step takes each file's size from the Delta log, so a file at or below the s3fs managed-copy threshold is one CopyObject with no HEAD of the source. DuckLake registration tells generations on a reused slot name apart by the job that published them, read from the same record.## How to clean up orphaned S3 datadiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.pyindex 189cfe8db486..751dfd3c80c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py@@ -1,3 +1,4 @@+import asynciofrom typing import TYPE_CHECKING, Any, Literal, Optional, Protocolfrom django.db.models import F@@ -320,6 +321,22 @@ def _stored_sync_type_config(schema_id: Any, team_id: int) -> Any:)+async def _live_file_sizes(delta_table_ref: "DeltaTableRef") -> dict[str, int]:+ """The size of each live file from the Delta log, keyed by its path relative to the table folder.++ Read from the same cached handle as the file URIs, so the two describe one snapshot. Empty when+ the log cannot give the sizes; the publish step then reads each size from S3 as before.+ """+ delta_table = await delta_table_ref.get_delta_table()+ if delta_table is None:+ return {}+ try:+ sizes = await asyncio.to_thread(delta_table._table.get_add_file_sizes)+ except Exception:+ return {}+ return {path: size for path, size in sizes.items() if isinstance(size, int)}++@recorded_phase("publish")async def _publish_queryable_files(job: ExternalDataJob,@@ -366,8 +383,17 @@ async def _publish_queryable_files(# File URIs are listed after delta maintenance so the queryable folder serves the compacted# layout rather than the pre-compaction small files.+ file_sizes: dict[str, int] = {}++ async def _list_live_files() -> list[str]:+ uris = await delta_table_ref.get_file_uris()+ sizes = await _live_file_sizes(delta_table_ref)+ file_sizes.clear()+ file_sizes.update(sizes)+ return uris+with post_load_phase("list_live_files"):- file_uris = await delta_table_ref.get_file_uris()+ file_uris = await _list_live_files()note_post_load_phase(live_files=len(file_uris))logger.debug(f"Preparing S3 files - total parquet files: {len(file_uris)}")with POST_LOAD_DURATION_SECONDS.labels(operation="prepare_s3").time():@@ -378,9 +404,10 @@ async def _publish_queryable_files(delete_existing=True,existing_queryable_folder=existing_queryable_folder,logger=logger,- refresh_file_uris=delta_table_ref.get_file_uris,+ refresh_file_uris=_list_live_files,double_buffer=True,pointer_history=pointer_history,+ file_sizes=file_sizes,)return folderdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.pyindex a3293026c75d..cc7bde35773c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py@@ -61,10 +61,16 @@ def _make_schema(def _make_helper(- *, file_uris: list[str] | None = None, live_row_count: int | None = None, live_size_mib: float | None = None+ *,+ file_uris: list[str] | None = None,+ live_row_count: int | None = None,+ live_size_mib: float | None = None,+ file_sizes: dict[str, int] | None = None,) -> MagicMock:+ delta_table = MagicMock()+ delta_table._table.get_add_file_sizes.return_value = file_sizes or {}return MagicMock(- get_delta_table=AsyncMock(return_value=MagicMock()),+ get_delta_table=AsyncMock(return_value=delta_table),get_file_uris=AsyncMock(return_value=file_uris or []),get_live_row_count=AsyncMock(return_value=live_row_count),get_live_size_mib=AsyncMock(return_value=live_size_mib),@@ -159,13 +165,30 @@ class TestRunPostLoadDeltaMaintenance:# was called with that stale snapshot, raising FileNotFoundError on files maintenance just removed.schema = _make_schema(is_cdc=is_cdc)post_maintenance_uris = ["s3://bucket/orders/compacted.parquet"]- helper = _make_helper(file_uris=post_maintenance_uris)+ helper = _make_helper(file_uris=post_maintenance_uris, file_sizes={"compacted.parquet": 123})_, prepare_s3 = await _run_post_load(schema, helper, cdc_write_mode="incremental" if is_cdc else None)prepare_s3.assert_awaited_once()assert prepare_s3.await_args is not Noneassert prepare_s3.await_args.args[2] == post_maintenance_uris+ assert prepare_s3.await_args.kwargs["file_sizes"] == {"compacted.parquet": 123}++ @pytest.mark.asyncio+ async def test_a_refreshed_file_listing_also_refreshes_the_file_sizes(self) -> None:+ # A retry after a vanished source file copies the files a compaction just wrote. Their sizes+ # must reach the copy step with them, or the old snapshot's sizes select the copy path.+ helper = _make_helper(file_uris=["s3://bucket/orders/p0.parquet"], file_sizes={"p0.parquet": 1})++ _, prepare_s3 = await _run_post_load(_make_schema(is_cdc=False), helper)++ assert prepare_s3.await_args is not None+ helper.get_file_uris.return_value = ["s3://bucket/orders/compacted.parquet"]+ helper.get_delta_table.return_value._table.get_add_file_sizes.return_value = {"compacted.parquet": 2}+ refreshed = await prepare_s3.await_args.kwargs["refresh_file_uris"]()++ assert refreshed == ["s3://bucket/orders/compacted.parquet"]+ assert prepare_s3.await_args.kwargs["file_sizes"] == {"compacted.parquet": 2}class TestRegisterTableRowCount:diff --git a/products/warehouse_sources/backend/temporal/data_imports/query_folder_state.py b/products/warehouse_sources/backend/temporal/data_imports/query_folder_state.pyindex 624503f0488e..d7f4f08a7c40 100644--- a/products/warehouse_sources/backend/temporal/data_imports/query_folder_state.py+++ b/products/warehouse_sources/backend/temporal/data_imports/query_folder_state.py@@ -13,8 +13,8 @@ from typing import Anyfrom posthog.dataclasses import frozen# `sync_type_config` key: {<table prefix>: {"active": str, "active_since": iso, "active_job_id": str,-# "history_since": iso, "inactive_since": {<folder>: iso}}}, one entry per table under the schema-# (the snapshot table and a CDC companion have different prefixes).+# "history_since": iso, "inactive_since": {<folder>: iso}, "non_slot_active_until": iso}}, one entry+# per table under the schema (the snapshot table and a CDC companion have different prefixes).QUERY_FOLDER_STATE_KEY = "query_folder_state"# The fixed slots a table rotates through under the double-buffer flag. Three rather than two, so the@@ -56,6 +56,9 @@ class QueryFolderPointerHistory:history_since: datetime | None# When each folder last stopped being the pointer.inactive_since: dict[str, datetime]+ # When a folder that is not a slot last stopped being the pointer. Such a folder is not reused,+ # so the publish step deletes it. None when the record saw no such move.+ non_slot_active_until: datetime | None = None@classmethoddef from_config(cls, sync_type_config: Any, table_prefix: str) -> QueryFolderPointerHistory | None:@@ -80,6 +83,7 @@ class QueryFolderPointerHistory:active_job_id=active_job_id if isinstance(active_job_id, str) else None,history_since=_parse_instant(state.get("history_since")),inactive_since=inactive_since,+ non_slot_active_until=_parse_instant(state.get("non_slot_active_until")),)def stopped_being_active(self, folder: str) -> datetime | None:@@ -122,6 +126,9 @@ def advance_query_folder_pointer(inactive_since[previous_folder] = atinactive_since.pop(queryable_folder, None)slot_names = query_folder_slot_names(table_prefix)+ non_slot_active_until = previous.non_slot_active_until if previous is not None else None+ if previous_folder is not None and previous_folder != queryable_folder and previous_folder not in slot_names:+ non_slot_active_until = atstates = sync_type_config.get(QUERY_FOLDER_STATE_KEY)if not isinstance(states, dict):@@ -134,5 +141,6 @@ def advance_query_folder_pointer("inactive_since": {folder: instant.isoformat() for folder, instant in inactive_since.items() if folder in slot_names},+ "non_slot_active_until": non_slot_active_until.isoformat() if non_slot_active_until is not None else None,}sync_type_config[QUERY_FOLDER_STATE_KEY] = statesdiff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.pyindex 28ac854b77e8..178b7f86e8df 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@@ -22,7 +22,10 @@ from parameterized import parameterizedfrom posthog.temporal.common.errors import NonReportableErrorfrom products.warehouse_sources.backend.temporal.data_imports import util as util_module-from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import QueryFolderPointerHistory+from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import (+ QueryFolderPointerHistory,+ advance_query_folder_pointer,+)from products.warehouse_sources.backend.temporal.data_imports.util import (_INTERNAL_DB_MAX_ATTEMPTS,NonRetryableException,@@ -64,6 +67,7 @@ def _fake_s3(**kwargs):"_exists": AsyncMock(return_value=False),"_find": AsyncMock(return_value={}),"_cp_file": AsyncMock(),+ "_copy_basic": AsyncMock(),"_copy": AsyncMock(),"_rm": AsyncMock(),}@@ -326,6 +330,87 @@ class TestPrepareS3FilesForQuerying:assert "example-bucket" not in str(raised.value)assert raised.value.__cause__ is fatal_error+ @parameterized.expand(+ [+ ("small_file", {"part-0.parquet": 1024}, "_copy_basic"),+ ("file_at_the_threshold", {"part-0.parquet": util_module.MANAGED_COPY_THRESHOLD}, "_copy_basic"),+ ("file_above_the_threshold", {"part-0.parquet": util_module.MANAGED_COPY_THRESHOLD + 1}, "_cp_file"),+ ("file_missing_from_the_sizes", {"other.parquet": 1024}, "_cp_file"),+ ("no_sizes", None, "_cp_file"),+ ]+ )+ async def test_copies_without_a_size_lookup_only_when_the_size_allows_a_single_copy(+ self, _name: str, file_sizes: dict[str, int] | None, expected_method: str+ ):+ # `_cp_file` reads the size with a HEAD before each copy. A file above the threshold, or with+ # no known size, must keep that path: a single CopyObject of a large object can time out.+ s3 = _fake_s3()+ source = f"{settings.BUCKET_URL}/job/my_table/part-0.parquet"++ with patch.object(util_module, "aget_s3_client", return_value=_FakeS3CM(s3)):+ folder = await prepare_s3_files_for_querying(+ folder_path="job",+ table_name="my_table",+ file_uris=[source],+ delete_existing=False,+ file_sizes=file_sizes,+ )++ unexpected_method = "_cp_file" if expected_method == "_copy_basic" else "_copy_basic"+ getattr(s3, expected_method).assert_awaited_once_with(+ source, f"{settings.BUCKET_URL}/job/{folder}/part-0.parquet"+ )+ getattr(s3, unexpected_method).assert_not_awaited()++ @parameterized.expand(+ [+ ("source_reported_as_not_found", FileNotFoundError("part-0.parquet"), None, True),+ # A store that answers a copy of a missing source with another error must reach the same+ # retry, so the copy that reads the source first gives the verdict.+ (+ "source_gone_on_a_store_with_another_error",+ OSError(errno.EINVAL, "Copy Source must mention the source bucket and key"),+ FileNotFoundError("part-0.parquet"),+ True,+ ),+ # A throttled store must get the backoff, not a second request at once.+ ("throttled", OSError(errno.EBUSY, "Reduce your request rate for this prefix."), None, False),+ ]+ )+ async def test_a_failed_single_copy_reaches_the_same_retry_as_before(+ self, _name: str, single_copy_error: Exception, cp_file_error: Exception | None, expect_refresh: bool+ ):+ copy_basic = AsyncMock(side_effect=[single_copy_error, None])+ s3 = _fake_s3(_copy_basic=copy_basic, _cp_file=AsyncMock(side_effect=cp_file_error))+ file_sizes = {"part-0.parquet": 1024}+ original = f"{settings.BUCKET_URL}/job/my_table/part-0.parquet"+ compacted = f"{settings.BUCKET_URL}/job/my_table/compacted.parquet"++ async def refresh() -> list[str]:+ file_sizes.clear()+ file_sizes["compacted.parquet"] = 2048+ return [compacted]++ 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=[original],+ delete_existing=False,+ refresh_file_uris=refresh,+ file_sizes=file_sizes,+ )++ # The retry copies the refreshed file by its refreshed size, with no size lookup.+ assert [call.args[0] for call in copy_basic.await_args_list] == [+ original,+ compacted if expect_refresh else original,+ ]+ assert s3._cp_file.await_count == (1 if cp_file_error is not None else 0)+async def test_tolerates_job_folder_missing_on_first_materialization(self):# A brand new table/model has no prior content in S3, so listing the job folder to# find old timestamped query folders to clean up raises FileNotFoundError (s3fs's@@ -393,12 +478,42 @@ def _history()+def _rotation(+ *,+ fallback_at: datetime | None = None,+ back_on_slots_at: datetime | None = None,+ missed_move_at: datetime | None = None,+ last_move: datetime = _MOMENTS_AGO,+) -> dict:+ """The stored record of a table that has rotated through its slots for 30 days, built through the+ same function that table registration calls. Ends on slot c, unless a fallback changes the path."""+ config: dict = {}++ def move(previous: str | None, folder: str, at: datetime) -> None:+ advance_query_folder_pointer(config, previous_folder=previous, queryable_folder=folder, job_id="job", now=at)++ start = _NOW - timedelta(days=30)+ move(None, _SLOT_A, start)+ move(_SLOT_A, _SLOT_B, start + timedelta(hours=1))+ if missed_move_at is not None:+ move(_SLOT_C, _SLOT_A, missed_move_at)+ return config+ if fallback_at is None:+ move(_SLOT_B, _SLOT_C, last_move)+ return config+ timestamped = f"my_table__query_{int(fallback_at.timestamp())}_0badf00d"+ move(_SLOT_B, timestamped, fallback_at)+ if back_on_slots_at is not None:+ move(timestamped, _SLOT_A, back_on_slots_at)+ if last_move > back_on_slots_at:+ move(_SLOT_A, _SLOT_B, last_move)+ return config++def _find_returning(listings: dict[str, dict[str, dict]]) -> AsyncMock:- async def _find(path: str, detail: bool = True) -> dict[str, dict]:- folder = path.rstrip("/").split("/")[-1]- if folder not in listings:- raise FileNotFoundError(path)- return listings[folder]+ async def _find(path: str, prefix: str = "", detail: bool = True) -> dict[str, dict]:+ assert path == _JOB_URI+ return listings.get(prefix.rstrip("/"), {})return AsyncMock(side_effect=_find)@@ -505,9 +620,12 @@ class TestDoubleBufferedQueryFolders:if expected_slot is None:assert _TIMESTAMPED_FOLDER.match(folder)assert self._copied(s3) == {f"{_JOB_URI}/{folder}/p1", f"{_JOB_URI}/{folder}/p2"}+ # Both slots are on record as read within the buffer, so a listing cannot make one usable.+ s3._find.assert_not_awaited()else:assert folder == expected_slotassert self._copied(s3) == {f"{_JOB_URI}/{expected_slot}/p2"}+ assert s3._find.await_count == 1async def test_skips_a_recently_read_populated_slot_for_an_empty_one(self):# After an unrecorded pointer move the history restarts, so a populated slot with no record@@ -590,6 +708,71 @@ class TestDoubleBufferedQueryFolders:assert folder == _SLOT_Bs3._rm.assert_awaited_once_with(f"{_JOB_KEY}/{stale}", recursive=True)+ @parameterized.expand(+ [+ # A table that stays on its slots has no timestamped folder, so most publishes do not scan.+ ("steady_rotation_on_the_slots", _rotation(), _SLOT_C, False),+ ("first_publish_of_a_daily_window", _rotation(last_move=_NOW - timedelta(days=2)), _SLOT_C, True),+ # A fallback folder stays until a scan runs after it has been unread for the buffer.+ ("pointer_on_a_timestamped_folder", _rotation(fallback_at=_MOMENTS_AGO, back_on_slots_at=None), None, True),+ (+ "timestamped_folder_just_stopped_being_read",+ _rotation(fallback_at=_NOW - timedelta(minutes=5), back_on_slots_at=_MOMENTS_AGO),+ _SLOT_A,+ True,+ ),+ (+ "no_scan_yet_since_the_timestamped_folder_became_deletable",+ _rotation(fallback_at=_NOW - timedelta(days=3), back_on_slots_at=_NOW - timedelta(hours=1)),+ _SLOT_A,+ True,+ ),+ (+ "a_scan_ran_after_the_timestamped_folder_became_deletable",+ _rotation(+ fallback_at=_NOW - timedelta(days=3),+ back_on_slots_at=_NOW - timedelta(hours=3),+ last_move=_MOMENTS_AGO,+ ),+ _SLOT_B,+ False,+ ),+ ("pointer_move_that_the_record_missed", _rotation(missed_move_at=_MOMENTS_AGO), _SLOT_A, True),+ ("no_record", None, _SLOT_C, True),+ ]+ )+ async def test_scans_for_timestamped_folders_only_while_one_can_exist(+ self, _name: str, config: dict | None, existing: str | None, expect_scan: bool+ ):+ # The scan lists the whole job folder. A table that never leaves its slots must not pay for+ # it on each publish, and a table that fell back must not keep its full copy forever.+ history = QueryFolderPointerHistory.from_config(config, "my_table__query")+ existing = existing or (history.active if history is not None else None)+ s3 = _fake_s3(_find=_find_returning({}))++ folder = await _prepare_double_buffered(s3, existing=existing, history=history, file_uris=_live("p1"))++ assert folder in (_SLOT_A, _SLOT_B, _SLOT_C)+ assert s3._ls.await_count == (1 if expect_scan else 0)++ async def test_a_fallback_publish_scans_even_on_a_steady_record(self):+ # A table that syncs faster than the buffer falls back on most publishes. Each fallback+ # leaves a full copy, so each one must also remove the copies that are old enough.+ stale = f"my_table__query_{_stale_epoch()}_0badf00d"+ s3 = _fake_s3(_ls=AsyncMock(return_value=_job_folder_listing(_SLOT_A, _SLOT_B, _SLOT_C, stale)))+ history = QueryFolderPointerHistory(+ active=_SLOT_C,+ active_since=_MOMENTS_AGO,+ active_job_id="job",+ history_since=_NOW - timedelta(days=30),+ inactive_since={_SLOT_A: _MOMENTS_AGO, _SLOT_B: _MOMENTS_AGO},+ )++ folder = await _prepare_double_buffered(s3, existing=_SLOT_C, history=history, file_uris=_live("p1"))++ assert _TIMESTAMPED_FOLDER.match(folder)+ s3._rm.assert_awaited_once_with(f"{_JOB_KEY}/{stale}", recursive=True)+async def test_a_failed_stale_file_delete_raises_instead_of_returning_the_standby(self):# The old-folder cleanup is best effort because nobody is pointed at those folders. A stale# file left in the standby is different: the caller flips readers to it next, so swallowingdiff --git a/products/warehouse_sources/backend/temporal/data_imports/util.py b/products/warehouse_sources/backend/temporal/data_imports/util.pyindex c796360aa0a0..fbd054f5a745 100644--- a/products/warehouse_sources/backend/temporal/data_imports/util.py+++ b/products/warehouse_sources/backend/temporal/data_imports/util.py@@ -1,9 +1,10 @@import reimport time+import zlibimport errnoimport asyncio-from collections.abc import Awaitable, Callable-from datetime import UTC, datetime+from collections.abc import Awaitable, Callable, Mapping+from datetime import UTC, datetime, timedeltafrom functools import wrapsfrom typing import TYPE_CHECKING, Literal, Optional, ParamSpec, TypeVarfrom uuid import uuid4@@ -13,6 +14,7 @@ from django.db import OperationalError as DjangoOperationalErrorimport psycopgimport botocore.exceptions+from s3fs.core import MANAGED_COPY_THRESHOLDfrom structlog.types import FilteringBoundLoggerfrom posthog.exceptions import capture_exception@@ -259,6 +261,11 @@ _COPY_FILES_MAX_ATTEMPTS = 6# cumulative backoff (2+4+8s), the same budget `_purge_s3_prefix` uses against the same condition._DELETE_FOLDER_MAX_ATTEMPTS = 4+# The longest time one publish is expected to take between its scan for old timestamped folders and+# its pointer write. A publish that takes longer can leave a folder for the daily scan.+_FOLDER_SCAN_SETTLE_SECONDS = 3600+_FOLDER_SCAN_INTERVAL_SECONDS = 24 * 3600+def is_posthog_team(team_id: int) -> bool:DEBUG: bool = get_from_env("DEBUG", False, type_cast=str_to_bool)@@ -277,14 +284,55 @@ def _unread_long_enough(stopped_being_active: Optional[datetime]) -> bool:return (datetime.now(UTC) - stopped_being_active).total_seconds() >= S3_DELETE_TIME_BUFFER+def _folder_scan_window(table_folder_uri: str, at: datetime) -> int:+ """The daily window `at` falls in. The window boundary differs for each table, so the daily scans+ of all tables do not start at the same time."""+ offset = zlib.crc32(table_folder_uri.encode()) % _FOLDER_SCAN_INTERVAL_SECONDS+ return int((at.timestamp() + offset) // _FOLDER_SCAN_INTERVAL_SECONDS)+++def _timestamped_folder_scan_due(+ pointer_history: Optional[QueryFolderPointerHistory],+ existing_queryable_folder: Optional[str],+ table_folder_uri: str,+ slot_names: tuple[str, ...],+) -> bool:+ """Whether a publish into a slot must look for old timestamped folders of this table.++ A table that stays on its slots has none, so the listing of the job folder finds nothing to+ delete. The record shows when a timestamped folder was last the pointer, or when a pointer move+ was last missed. From that instant the scan runs on each publish, until one publish scanned at+ least `S3_DELETE_TIME_BUFFER` after it, which is the first scan that can delete the folder.++ The record cannot show a folder that a failed publish left behind, or a delete that failed. One+ scan in each daily window finds those: the first publish of a window always scans.+ """+ if pointer_history is None or pointer_history.active_since is None or pointer_history.history_since is None:+ return True+ if existing_queryable_folder not in slot_names or pointer_history.active != existing_queryable_folder:+ return True+ last_unsettled = max(+ pointer_history.history_since, pointer_history.non_slot_active_until or pointer_history.history_since+ )+ settled_after = last_unsettled + timedelta(seconds=S3_DELETE_TIME_BUFFER + _FOLDER_SCAN_SETTLE_SECONDS)+ if pointer_history.active_since < settled_after:+ return True+ return _folder_scan_window(table_folder_uri, datetime.now(UTC)) != _folder_scan_window(+ table_folder_uri, pointer_history.active_since+ )++async def _list_query_folder_files(s3: "S3FileSystem", folder_uri: str) -> dict[str, str]:"""Map each file under `folder_uri` from its folder-relative path to its full `s3://` URI.Recursive because a partitioned table keeps its parquet files under `key=value/` subfolders,which the copy step mirrors into the query folder."""+ parent_uri, _, folder_name = folder_uri.rstrip("/").rpartition("/")try:- found = await s3._find(folder_uri, detail=True)+ # With a key prefix, `_find` is one flat listing. Without it, an empty folder costs two more+ # requests, because `_find` then probes whether the path is a file.+ found = await s3._find(parent_uri, prefix=f"{folder_name}/", detail=True)except FileNotFoundError:return {}entries = found.values() if isinstance(found, dict) else found@@ -313,6 +361,9 @@ async def _pick_standby_slot(when it is empty (no prefix in S3, so nothing can be reading it) or when it stopped being thepointer at least `S3_DELETE_TIME_BUFFER` ago. A slot with no pointer record is treated as unreadsince the record began; with no record at all, only an empty slot is usable.++ A slot that the record shows as the pointer within the buffer is not listed: it held a generation+ moments ago, so the listing could only confirm that it is not usable."""slot_names = query_folder_slot_names(f"{normalized_table_name}__query")recorded_active = pointer_history.active if pointer_history is not None else None@@ -323,6 +374,13 @@ async def _pick_standby_slot(candidates.sort(key=lambda name: (stopped_at(name) is None, stopped_at(name) or datetime.min.replace(tzinfo=UTC)))for name in candidates:+ if (+ pointer_history is not None+ and name in pointer_history.inactive_since+ and not _unread_long_enough(stopped_at(name))+ ):+ await log(f"Standby query folder {name} stopped being read at {stopped_at(name)}, too recent to rewrite")+ continuelisted = await _list_query_folder_files(s3, f"{s3_folder_for_job}/{name}")if not listed or _unread_long_enough(stopped_at(name)):await log(f"Reconciling standby query folder {name} holding {len(listed)} files")@@ -376,6 +434,7 @@ async def prepare_s3_files_for_querying(refresh_file_uris: Optional[Callable[[], Awaitable[list[str]]]] = None,double_buffer: bool = False,pointer_history: Optional[QueryFolderPointerHistory] = None,+ file_sizes: Optional[Mapping[str, int]] = None,) -> str:"""Publish the table's live parquet files into a folder readers glob, and return that folder's name.@@ -393,6 +452,12 @@ async def prepare_s3_files_for_querying(range, so a missed sync or a crash mid-reconcile heals on the next pass. A populated slot thatstopped being the pointer within `S3_DELETE_TIME_BUFFER`, or whose last use is unknown, is nottouched; the sync falls back to the default path.++ `file_sizes`: the size in bytes of each live file, keyed by its path relative to the table folder,+ as the Delta log records it. A file with a known size at or below the s3fs managed-copy threshold+ is copied with one CopyObject. Without a size, s3fs reads the size with a HEAD of the source+ first. The mapping is read at copy time, so a `refresh_file_uris` that updates it keeps the sizes+ current across a retry."""async def _log(msg: str, level: Optional[Literal["debug", "error"]] = "debug") -> None:@@ -446,9 +511,22 @@ async def prepare_s3_files_for_querying(s3_path_for_querying = f"{s3_path_for_querying}_{folder_suffix}"s3_folder_for_querying = f"{s3_folder_for_querying}_{folder_suffix}"+ scan_for_old_folders = (+ standby_files is None+ or pointer_history is None+ or _timestamped_folder_scan_due(+ pointer_history,+ existing_queryable_folder,+ f"{s3_folder_for_job}/{normalized_table_name}",+ query_folder_slot_names(f"{normalized_table_name}__query"),+ )+ )+files_to_delete: list[str] = []if delete_existing:- if use_timestamped_folders:+ if use_timestamped_folders and not scan_for_old_folders:+ await _log(f"No timestamped query folder is on record for table {normalized_table_name}; scan skipped")+ elif use_timestamped_folders:# Match only directories belonging to this specific table.# Keys may be bare folder names or full paths, so use (?:^|.+/) to handle both.# The uniqueness suffix is optional so folders created before it existed still match.@@ -523,7 +601,25 @@ async def prepare_s3_files_for_querying(# is a directory, each requiring its own S3 ListObjectsV2 call — with hundreds of# files copied concurrently, that multiplies into enough LIST traffic to trigger# S3's SlowDown rate limiting on the destination prefix.- await s3._cp_file(file, f"{s3_path_for_querying}/{relative_path(file)}")+ relative = relative_path(file)+ destination = f"{s3_path_for_querying}/{relative}"+ size = file_sizes.get(relative) if file_sizes is not None else None+ if size is not None and size <= MANAGED_COPY_THRESHOLD:+ # `_cp_file` reads the size of the source with a HEAD to select between this copy+ # and the multipart copy. The Delta log already has the size. CopyObject copies+ # the full object, so a wrong size cannot change the bytes that arrive.+ try:+ await s3._copy_basic(file, destination)+ return+ except FileNotFoundError:+ raise+ except OSError as e:+ if _is_s3_throttling_error(e):+ raise+ # Object stores do not agree on the error for a source that is gone: S3+ # answers NoSuchKey, others answer with an invalid-argument error. The copy+ # below reads the source first, so it raises the error the retry loop expects.+ await s3._cp_file(file, destination)import deltalake.exceptions # noqa: PLC0415 — keeps the heavy deltalake dep off this module's top-level import path