: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
perf(data-warehouse): rotate query folders and cut per-batch loader overhead (#107446)
Tom Owerse7c14387b61d
diff --git a/products/data_warehouse/backend/s3.py b/products/data_warehouse/backend/s3.pyindex 622b20563156..8a1e5ee8ba91 100644--- a/products/data_warehouse/backend/s3.py+++ b/products/data_warehouse/backend/s3.py@@ -1,4 +1,6 @@import time+import asyncio+import weakrefimport contextlibfrom typing import Optionalfrom urllib.parse import urlparse@@ -44,16 +46,51 @@ def get_s3_client(*, endpoint_url: Optional[str] = None, skip_instance_cache: bo)+# Shared asynchronous clients, one per (event loop, endpoint). An asynchronous S3FileSystem binds its+# aiobotocore client to the loop that called set_session, so it can only be reused on that loop.+# fsspec's own instance cache keys on the calling thread id instead, and async_to_sync runs each+# call on a new loop in a new thread whose id the OS may hand out again, so that cache could return+# a client bound to a loop that was already closed ("Event loop is closed"). Keying on the loop+# object itself does not evict on its own, though: the client's aiohttp session keeps a strong+# reference back to the loop that created it, so the loop stays reachable through our own value and+# is never weakly collected. _evict_closed_event_loops sweeps dead loops out explicitly instead.+_LOOP_S3_CLIENTS: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[Optional[str], s3fs.S3FileSystem]]" = (+ weakref.WeakKeyDictionary()+)+++def _evict_closed_event_loops() -> None:+ for closed_loop in [loop for loop in _LOOP_S3_CLIENTS if loop.is_closed()]:+ del _LOOP_S3_CLIENTS[closed_loop]+++async def _shared_async_s3_client(endpoint_url: Optional[str]) -> s3fs.S3FileSystem:+ loop = asyncio.get_running_loop()+ _evict_closed_event_loops()+ clients = _LOOP_S3_CLIENTS.setdefault(loop, {})+ s3 = clients.get(endpoint_url)+ if s3 is None:+ # endpoint_url only forwarded when set; see get_s3_client and s3_proxy for the proxy-bypass reasoning.+ extra = {"endpoint_url": endpoint_url} if endpoint_url is not None else {}+ s3 = s3fs.S3FileSystem(+ asynchronous=True,+ skip_instance_cache=True,+ config_kwargs=boto_proxy_config_kwargs(endpoint_url=endpoint_url),+ **extra,+ )+ await s3.set_session()+ clients[endpoint_url] = s3+ return s3++@contextlib.asynccontextmanagerasync def aget_s3_client(*, fresh_instance: bool = False, endpoint_url: Optional[str] = None):- # fresh_instance=True bypasses the fsspec instance cache: a new S3FileSystem bound to the current- # event loop, closed on context exit. The cached default hands every caller the same instance- # regardless of loop, so async_to_sync-driven code (each call runs on a fresh, short-lived loop)- # gets an aiobotocore client bound to an already-closed loop ("Event loop is closed") and a- # dircache that goes stale whenever delta-rs writes to S3 through its own object store behind- # s3fs's back. Reserve it for low-frequency, correctness-critical paths (repartition purge/swap):- # every fresh instance pays connection setup + credential resolution, so defaulting it on would- # hammer the credential provider from hot paths.+ # fresh_instance=True builds a new S3FileSystem bound to the current event loop and closes it on+ # context exit. The shared default is one client per event loop (see _LOOP_S3_CLIENTS), whose+ # dircache goes stale whenever delta-rs writes to S3 through its own object store behind s3fs's+ # back. Reserve fresh_instance for low-frequency, correctness-critical paths (repartition+ # purge/swap): every fresh instance pays connection setup + credential resolution, so defaulting+ # it on would hammer the credential provider from hot paths.uncached = fresh_instance or settings.USE_LOCAL_SETUPif settings.USE_LOCAL_SETUP:# Defaults for localhost dev and test suites. skip_instance_cache avoids "Event loop is@@ -65,18 +102,18 @@ async def aget_s3_client(*, fresh_instance: bool = False, endpoint_url: Optionalskip_instance_cache=True,asynchronous=True,)- else:- # endpoint_url only forwarded when set, so the shared cached client isn't split; see- # get_s3_client and s3_proxy for the proxy-bypass reasoning.+ await s3.set_session()+ elif fresh_instance:extra = {"endpoint_url": endpoint_url} if endpoint_url is not None else {}s3 = s3fs.S3FileSystem(asynchronous=True,- skip_instance_cache=fresh_instance,+ skip_instance_cache=True,config_kwargs=boto_proxy_config_kwargs(endpoint_url=endpoint_url),**extra,)-- await s3.set_session()+ await s3.set_session()+ else:+ s3 = await _shared_async_s3_client(endpoint_url)if not uncached:yield s3diff --git a/products/data_warehouse/backend/test/test_s3.py b/products/data_warehouse/backend/test/test_s3.pynew file mode 100644index 000000000000..93e04afa9c9c--- /dev/null+++ b/products/data_warehouse/backend/test/test_s3.py@@ -0,0 +1,86 @@+import asyncio+from typing import Any, NamedTuple++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from django.test import override_settings++from products.data_warehouse.backend import s3 as s3_module++_S3 = "products.data_warehouse.backend.s3"+++class _ClientPair(NamedTuple):+ first: Any+ second: Any+++def _filesystem_factory() -> MagicMock:+ def build(**kwargs):+ fs = MagicMock()+ fs.set_session = AsyncMock()+ fs.storage_options = kwargs+ return fs++ return MagicMock(side_effect=build)+++class TestSharedAsyncClientPerLoop:+ # An asynchronous S3FileSystem is bound to the loop that opened its session. Handing one loop's+ # client to another raises "Event loop is closed" from deep inside aiobotocore; handing every+ # call a new client rebuilds the session and resolves credentials each time.++ @pytest.fixture(autouse=True)+ def _cloud_setup_with_empty_registry(self):+ s3_module._LOOP_S3_CLIENTS.clear()+ with override_settings(USE_LOCAL_SETUP=False):+ yield+ s3_module._LOOP_S3_CLIENTS.clear()++ @patch(f"{_S3}.boto_proxy_config_kwargs", return_value={})+ def test_calls_on_one_loop_share_a_client_and_calls_on_another_loop_do_not(self, _proxy: MagicMock) -> None:+ async def two_uses() -> _ClientPair:+ async with s3_module.aget_s3_client() as first, s3_module.aget_s3_client() as second:+ return _ClientPair(first, second)++ with patch(f"{_S3}.s3fs.S3FileSystem", _filesystem_factory()) as filesystem:+ first_loop = asyncio.run(two_uses())+ second_loop = asyncio.run(two_uses())++ assert first_loop[0] is first_loop[1]+ assert second_loop[0] is second_loop[1]+ assert first_loop[0] is not second_loop[0]+ assert filesystem.call_count == 2+ assert all(+ call.kwargs["asynchronous"] and call.kwargs["skip_instance_cache"] for call in filesystem.call_args_list+ )++ @patch(f"{_S3}.boto_proxy_config_kwargs", return_value={})+ def test_each_endpoint_gets_its_own_shared_client(self, _proxy: MagicMock) -> None:+ # The proxy bypass keys on the endpoint, so a client for one must never serve another.+ async def two_endpoints() -> _ClientPair:+ async with (+ s3_module.aget_s3_client() as default,+ s3_module.aget_s3_client(endpoint_url="https://other.example.com") as other,+ ):+ return _ClientPair(default, other)++ with patch(f"{_S3}.s3fs.S3FileSystem", _filesystem_factory()):+ default, other = asyncio.run(two_endpoints())++ assert default is not other+ assert other.storage_options["endpoint_url"] == "https://other.example.com"+ assert "endpoint_url" not in default.storage_options++ @patch(f"{_S3}.boto_proxy_config_kwargs", return_value={})+ def test_a_fresh_instance_is_never_shared_and_is_closed(self, _proxy: MagicMock) -> None:+ async def use_fresh() -> Any:+ async with s3_module.aget_s3_client(fresh_instance=True) as fs:+ return fs++ with patch(f"{_S3}.s3fs.S3FileSystem", _filesystem_factory()):+ fresh = asyncio.run(use_fresh())++ assert len(s3_module._LOOP_S3_CLIENTS) == 0+ fresh._s3creator.__aexit__.assert_awaited_once()diff --git a/products/data_warehouse/backend/tests/test_s3.py b/products/data_warehouse/backend/tests/test_s3.pyindex 7997bcbf6b73..fe314d369087 100644--- a/products/data_warehouse/backend/tests/test_s3.py+++ b/products/data_warehouse/backend/tests/test_s3.py@@ -7,7 +7,13 @@ from django.test import SimpleTestCase, override_settingsfrom botocore.exceptions import ClientErrorfrom parameterized import parameterized-from products.data_warehouse.backend.s3 import aget_s3_client, ensure_bucket_exists, get_size_of_folder+from products.data_warehouse.backend.s3 import (+ _LOOP_S3_CLIENTS,+ _shared_async_s3_client,+ aget_s3_client,+ ensure_bucket_exists,+ get_size_of_folder,+)def _client_error(code: str) -> ClientError:@@ -38,6 +44,32 @@ class TestAgetS3Client(SimpleTestCase):fake_s3._s3.close.assert_not_awaited()+class TestSharedAsyncS3ClientLoopEviction(SimpleTestCase):+ @override_settings(USE_LOCAL_SETUP=False)+ def test_evicts_a_closed_loops_entry_instead_of_leaking_it_forever(self) -> None:+ # _LOOP_S3_CLIENTS is a WeakKeyDictionary keyed on the event loop, but each cached client's+ # aiohttp session keeps a strong reference back to that loop, so the loop is never weakly+ # reachable and its entry never disappears on its own (the leak both review bots flagged).+ # A worker whose call path keeps starting new short-lived loops needs those dead entries+ # swept explicitly, or they and their clients accumulate for the life of the process.+ dead_loop = asyncio.new_event_loop()+ dead_loop.run_until_complete(asyncio.sleep(0))+ _LOOP_S3_CLIENTS[dead_loop] = {None: MagicMock()}+ dead_loop.close()+ assert dead_loop in _LOOP_S3_CLIENTS++ fake_s3 = MagicMock()+ fake_s3.set_session = AsyncMock()++ async def run() -> None:+ with patch("products.data_warehouse.backend.s3.s3fs.S3FileSystem", return_value=fake_s3):+ await _shared_async_s3_client(None)++ asyncio.run(run())++ assert dead_loop not in _LOOP_S3_CLIENTS++class TestGetSizeOfFolder(SimpleTestCase):def _mock_s3(self) -> MagicMock:s3 = MagicMock()diff --git a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.pyindex 4f68075c2fcb..6014f9dff779 100644--- a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py+++ b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py@@ -62,6 +62,7 @@ from products.managed_warehouse.backend.temporal.metrics import (record_ducklake_register_data_imports_stage_duration,)from products.managed_warehouse.backend.temporal.source_job_state import record_managed_warehouse_source_job_activity+from products.warehouse_sources.backend.facade.ducklake import query_folder_publishing_job_idfrom products.warehouse_sources.backend.facade.models import ExternalDataSchemaLOGGER = get_logger(__name__)@@ -113,7 +114,7 @@ def _register_source_job_update(team_id=inputs.team_id,schema_ids=[inputs.schema_id],source_job_id=inputs.job_id,- attempt_id=f"{inputs.job_id}:{_generation_token(inputs.prepared_queryable_folder)}",+ attempt_id=f"{inputs.job_id}:{_generation_token(inputs.prepared_queryable_folder, inputs.job_id)}",workflow_type=ManagedWarehouseSourceJobWorkflow.REGISTER,status=status,started_at=started_at,@@ -410,13 +411,18 @@ def _is_valid_queryable_folder(queryable_folder: str) -> bool:_GENERATION_SUFFIX_PATTERN = re.compile(r"__query_(\d+(?:_[0-9a-f]{8})?)$")-def _generation_token(prepared_queryable_folder: str) -> str:+def _timestamped_generation(prepared_queryable_folder: str) -> str | None:match = _GENERATION_SUFFIX_PATTERN.search(prepared_queryable_folder)- if match:- return match.group(1)- # Folders predating the timestamped naming carry no generation, so derive a stable- # token from the whole name to keep the workflow id unique per generation.- return hashlib.sha256(prepared_queryable_folder.encode()).hexdigest()[:12]+ return match.group(1) if match else None+++def _generation_token(prepared_queryable_folder: str, job_id: str) -> str:+ timestamped = _timestamped_generation(prepared_queryable_folder)+ if timestamped is not None:+ return timestamped+ # A fixed folder name (a rotation slot, or the legacy `__query` folder) is reused by later syncs,+ # so the name alone does not identify a generation; the job that published it does.+ return hashlib.sha256(f"{prepared_queryable_folder}:{job_id}".encode()).hexdigest()[:12]def build_register_data_imports_workflow_id(*, team_id: int, schema_id: str) -> str:@@ -467,7 +473,7 @@ def _generation_scoped_landing_uri() -> str:normalized_uri = landing_uri.rstrip("/")safe_job_id = re.sub(r"[^A-Za-z0-9_-]", "_", str(job_id))- generation_token = _generation_token(prepared_queryable_folder)+ generation_token = _generation_token(prepared_queryable_folder, job_id)generation_suffix = f"/{safe_job_id}/{generation_token}"if normalized_uri.endswith(generation_suffix):return normalized_uri@@ -530,12 +536,27 @@ def _prepared_generation_is_current(inputs: DuckLakeRegisterDataImportsActivityIreturn _current_prepared_queryable_folder(inputs) == inputs.metadata.prepared_queryable_folder+def _publishing_job_id(*, team_id: int, schema_uuid: uuid.UUID, prepared_queryable_folder: str) -> str | None:+ return query_folder_publishing_job_id(+ team_id=team_id, schema_id=schema_uuid, queryable_folder=prepared_queryable_folder+ )++def _register_completed_for_generation(*, team_id: int, schema_id: str, prepared_queryable_folder: str) -> bool:try:schema_uuid = uuid.UUID(schema_id)except ValueError:return False- token = _generation_token(prepared_queryable_folder)+ token = _timestamped_generation(prepared_queryable_folder)+ if token is None:+ # A fixed folder name needs the job that published the current generation. Without that+ # record nothing can prove the newer generation landed, so this one is published.+ publishing_job_id = _publishing_job_id(+ team_id=team_id, schema_uuid=schema_uuid, prepared_queryable_folder=prepared_queryable_folder+ )+ if publishing_job_id is None:+ return False+ token = _generation_token(prepared_queryable_folder, publishing_job_id)return (ManagedWarehouseSourceJob.objects.for_team(team_id).filter(diff --git a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.pyindex 2c57b92adf50..75222967e9fe 100644--- a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py+++ b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py@@ -14,6 +14,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.sync import database_sync_to_asyncfrom products.managed_warehouse.backend.facade.contracts import ManagedWarehouseSourceJobStatus+from products.managed_warehouse.backend.models import ManagedWarehouseSourceJobfrom products.managed_warehouse.backend.temporal import ducklake_register_data_imports_workflow as registration_modulefrom products.managed_warehouse.backend.temporal.ducklake_register_data_imports_workflow import (S3_COPY_BATCH_SIZE,@@ -552,6 +553,96 @@ def test_should_publish_prepared_generation(assert registration_module._should_publish_prepared_generation(_activity_inputs()) is expected+ ("prepared_queryable_folder", "distinct_per_job"),+ [+ # A timestamped folder is one generation by construction, so its token stays the timestamp.+ ("customers__query_1234567890_abcdef12", False),+ # A rotation slot is reused by later syncs; the job tells the generations apart.+ ("customers__query_a", True),+ ],+)+def test_generation_token_tells_syncs_on_a_reused_folder_name_apart(+ prepared_queryable_folder: str, distinct_per_job: bool+) -> None:+ first = registration_module._generation_token(prepared_queryable_folder, "job-1")+ second = registration_module._generation_token(prepared_queryable_folder, "job-2")++ assert (first != second) is distinct_per_job+ if not distinct_per_job:+ assert first == "1234567890_abcdef12"+++def test_stale_generation_still_publishes_when_the_current_slot_was_registered_by_an_earlier_job(team) -> None:+ # Slot names repeat: the generation now on slot a was published by job-3, and an earlier+ # generation on the same slot (job-1) was registered before. Job-2's generation on slot b is+ # stale but newer than anything DuckLake holds, so it must publish; treating job-1's registration+ # as "the newer folder already landed" left DuckLake a generation behind.+ source = ExternalDataSource.objects.create(+ team=team, source_id="source", connection_id="connection", source_type="Postgres", status="Running"+ )+ table = DataWarehouseTable.objects.create(+ team=team,+ name="customers",+ format="Delta",+ url_pattern="s3://bucket/path",+ external_data_source=source,+ queryable_folder="customers__query_a",+ )+ schema = ExternalDataSchema.objects.create(+ team=team,+ name="customers",+ source=source,+ table=table,+ sync_type_config={+ "query_folder_state": {+ "customers__query": {+ "active": "customers__query_a",+ "active_since": "2026-08-19T10:00:00+00:00",+ "active_job_id": "job-3",+ "history_since": "2026-08-19T08:00:00+00:00",+ "inactive_since": {"customers__query_b": "2026-08-19T10:00:00+00:00"},+ }+ }+ },+ )+ started_at = dt.datetime(2026, 8, 19, 9, tzinfo=dt.UTC)+ earlier_registration = registration_module._register_source_job_update(+ inputs=DuckLakeRegisterDataImportsInputs(+ team_id=team.id, job_id="job-1", schema_id=schema.id, prepared_queryable_folder="customers__query_a"+ ),+ status=ManagedWarehouseSourceJobStatus.COMPLETED,+ started_at=started_at,+ finished_at=started_at,+ )+ ManagedWarehouseSourceJob.objects.for_team(team.id).create(+ team=team,+ environment_id=team.id,+ schema_id=schema.id,+ source_job_id="job-1",+ attempt_id=earlier_registration.attempt_id,+ workflow_type=ManagedWarehouseSourceJob.WorkflowType.REGISTER,+ status=ManagedWarehouseSourceJob.Status.COMPLETED,+ started_at=started_at,+ finished_at=started_at,+ )+ stale_inputs = DuckLakeRegisterDataImportsActivityInputs(+ team_id=team.id,+ job_id="job-2",+ metadata=DuckLakeRegisterDataImportsMetadata(+ source_schema_id=str(schema.id),+ prepared_queryable_folder="customers__query_b",+ prepared_source_uri="s3://source/team/customers__query_b",+ landing_uri="s3://ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job-2",+ ducklake_schema_name="posthog_data_imports_team_1",+ ducklake_table_name="postgres_customers",+ ),+ )++ assert registration_module._should_publish_prepared_generation(stale_inputs) is True++def test_copy_activity_registers_when_prepared_generation_is_no_longer_current(monkeypatch):monkeypatch.setattr(registration_module,diff --git a/products/warehouse_sources/backend/facade/ducklake.py b/products/warehouse_sources/backend/facade/ducklake.pyindex 1f7dbf4e488d..ede08d0cbff9 100644--- a/products/warehouse_sources/backend/facade/ducklake.py+++ b/products/warehouse_sources/backend/facade/ducklake.py@@ -1,9 +1,16 @@from __future__ import annotations+from uuid import UUID+from posthog.hogql.database.database import get_data_warehouse_table_namefrom products.warehouse_sources.backend.duckgres_naming import duckgres_data_imports_table_name_for_version+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import (+ QueryFolderPointerHistory,+ query_folder_table_prefix,+)from .contracts import DuckLakeImportedTablefrom .types import ExternalDataSourceAccessMethod@@ -38,3 +45,21 @@ def list_ducklake_imported_tables(team_id: int, naming_version: str) -> list[Duc)return imported_tables+++def query_folder_publishing_job_id(*, team_id: int, schema_id: UUID, queryable_folder: str) -> str | None:+ """The import job that pointed the table at `queryable_folder`, or None when the pointer is+ elsewhere or the move was not recorded.++ A query folder with a fixed name is reused by later syncs, so the folder name alone does not+ identify a generation of the table; the job that published it does.+ """+ sync_type_config = (+ ExternalDataSchema.objects.filter(id=schema_id, team_id=team_id)+ .values_list("sync_type_config", flat=True)+ .first()+ )+ history = QueryFolderPointerHistory.from_config(sync_type_config, query_folder_table_prefix(queryable_folder))+ if history is None or history.active != queryable_folder:+ return None+ return history.active_job_iddiff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.pyindex 270e946209d9..70afdabd0903 100644--- a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py+++ b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load import (process_batch,+ process_batches,)from products.warehouse_sources_queue.backend.models import SourceBatch@@ -89,6 +90,7 @@ async def _run_consumer(consumer = BatchConsumer(config=config,process_batch=process_batch,+ process_batches=process_batches,health_reporter=health_reporter,claim_sync_types=claim_sync_types,claim_exclude_sync_types=claim_exclude_sync_types,diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 71df010b1786..e5cf50ff5687 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -263,7 +263,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField# See `sources/common/history_window.py`. A column rather than a `sync_type_config` key# because it has to outlive a reset, and clearing that blob is what a reset is for.history_start = models.DateTimeField(null=True, blank=True)- # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "verified_primary_keys": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict } }+ # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "verified_primary_keys": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str }, "repartition_rewrite": { "temp_uri": str, "rows_written": int, "target": dict }, "query_folder_state": { "<table>__query": { "active": str, "active_since": iso8601 str, "active_job_id": str, "history_since": iso8601 str, "inactive_since": { str: iso8601 str } } }, "registered_schema_fingerprint": str }sync_type_config = models.JSONField(default=dict,blank=True,diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 5451393d35fd..2d68fe1633bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -164,6 +164,13 @@ Queue rows and their parquet files are pruned after the queue's retention windowThe Kafka-era replay runbook that used to live here reconstructed `ExportSignalMessage`s from S3 and re-produced them to the `data_warehouse_sources_jobs` topic.That transport was removed; see git history for the old procedure.+## Query folders++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.++- **Default (timestamped folders).** Each 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.+- **Rotating slots** (`data-warehouse-double-buffered-query-folders`, per schema, released the same way as the repartition flags). 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 under the flag fill the empty slots in full, and reconciliation takes over from there. Turning the flag off returns the table to timestamped folders; the age-based cleanup never matches the slot names, so those folders stay behind until the table is deleted. 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 dataWhen a source or schema is soft-deleted, S3 cleanup can fail silently (it's best-effort). This leaves orphaned data in S3 that customers consider deleted.diff --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 bd13e5656585..6fdc7625e869 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@@ -15,6 +15,7 @@ from posthog.temporal.common.logger import get_loggerfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, process_incremental_valuefrom products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (retry_on_operational_error,)@@ -25,7 +26,12 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helperssync_revenue_analytics_views,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import set_initial_sync_complete-from products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying+from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import QueryFolderPointerHistory+from products.warehouse_sources.backend.temporal.data_imports.schema_flags import is_schema_flag_enabled+from products.warehouse_sources.backend.temporal.data_imports.util import (+ DOUBLE_BUFFERED_QUERY_FOLDERS_FLAG,+ prepare_s3_files_for_querying,+)from products.warehouse_sources.backend.types import ExternalDataSourceTypeif TYPE_CHECKING:@@ -286,6 +292,17 @@ async def _run_delta_maintenance()+def _stored_sync_type_config(schema_id: Any, team_id: int) -> Any:+ """Read the schema's `sync_type_config` as committed rather than from the in-memory schema: the+ query folder pointer record was written by whichever run flipped the pointer, which a long-lived+ schema object may predate."""+ return (+ ExternalDataSchema.objects.filter(id=schema_id, team_id=team_id)+ .values_list("sync_type_config", flat=True)+ .first()+ )++async def _publish_queryable_files(job: ExternalDataJob,schema: ExternalDataSchema,@@ -321,6 +338,16 @@ async def _publish_queryable_files(lambda: schema.table.queryable_folder if schema.table else None)()+ double_buffer = await database_sync_to_async_pool(is_schema_flag_enabled)(+ schema, DOUBLE_BUFFERED_QUERY_FOLDERS_FLAG+ )+ pointer_history = None+ if double_buffer:+ sync_type_config = await database_sync_to_async_pool(_stored_sync_type_config)(schema.id, job.team_id)+ pointer_history = QueryFolderPointerHistory.from_config(+ sync_type_config, f"{NamingConvention.normalize_identifier(resource_name)}__query"+ )+# File URIs are listed after delta maintenance so the queryable folder serves the compacted# layout rather than the pre-compaction small files.file_uris = await delta_table_ref.get_file_uris()@@ -334,6 +361,8 @@ async def _publish_queryable_files(existing_queryable_folder=existing_queryable_folder,logger=logger,refresh_file_uris=delta_table_ref.get_file_uris,+ double_buffer=double_buffer,+ pointer_history=pointer_history,)return folder@@ -364,6 +393,7 @@ async def _finalize_sync_bookkeeping(async def _register_table(job: ExternalDataJob,schema: ExternalDataSchema,+ delta_table_ref: "DeltaTableRef",row_count: int,table_schema_dict: dict[str, str],resource: "Optional[SourceResponse]",@@ -374,6 +404,11 @@ async def _register_table(validate_schema_and_update_table,)+ # The handle is already open from the maintenance step, so the schema comes from the in-memory+ # snapshot rather than from another log read.+ delta_table = await delta_table_ref.get_delta_table()+ delta_schema_json = delta_table.schema().to_json() if delta_table is not None else None+logger.debug("Validating schema and updating table")with POST_LOAD_DURATION_SECONDS.labels(operation="validate_schema").time():await validate_schema_and_update_table(@@ -385,6 +420,7 @@ async def _register_table(queryable_folder=queryable_folder,table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,primary_keys=resource.primary_keys if resource is not None else None,+ delta_schema_json=delta_schema_json,)logger.debug("Finished validating schema and updating table")@@ -664,7 +700,9 @@ async def run_post_load_operations(is_cdc_only_initial = cdc_write_mode is None and is_cdc_schema and schema.cdc_table_mode == "cdc_only"if not is_cdc_companion and not is_cdc_only_initial:- await _register_table(job, schema, row_count, table_schema_dict, resource, queryable_folder, logger)+ await _register_table(+ job, schema, delta_table_ref, row_count, table_schema_dict, resource, queryable_folder, logger+ )if is_cdc_companion or is_cdc_schema:await _run_cdc_post_load(diff --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 d66e26104662..17b7b0ab85b4 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@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.lupdate_job_row_count,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance+from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import QueryFolderPointerHistoryfrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (CHARGE_RESOURCE_NAME as STRIPE_CHARGE_RESOURCE_NAME,)@@ -69,6 +70,8 @@ async def _run_post_load(*,cdc_write_mode: str | None = None,resource: Optional[MagicMock] = None,+ double_buffer_enabled: bool = False,+ stored_sync_type_config: dict | None = None,) -> tuple[AsyncMock, AsyncMock]:job = MagicMock()job.id = uuid.uuid4()@@ -79,6 +82,8 @@ async def _run_post_load(run_scheduled = AsyncMock()with (patch(f"{_LOAD_MODULE}.prepare_s3_files_for_querying", prepare_s3),+ patch(f"{_LOAD_MODULE}.is_schema_flag_enabled", MagicMock(return_value=double_buffer_enabled)),+ patch(f"{_LOAD_MODULE}._stored_sync_type_config", MagicMock(return_value=stored_sync_type_config)),patch(f"{_LOAD_MODULE}.notify_revenue_analytics_that_sync_has_completed", AsyncMock()),patch(f"{_LOAD_MODULE}.sync_revenue_analytics_views", MagicMock()),patch(f"{_LOAD_MODULE}.DataWarehouseTable", MagicMock()),@@ -160,6 +165,58 @@ class TestRunPostLoadDeltaMaintenance:assert prepare_s3.await_args.args[2] == post_maintenance_uris+class TestPublishQueryableFilesDoubleBufferRollout:+ _STATE = {+ "query_folder_state": {+ "orders__query": {+ "active": "orders__query_a",+ "active_since": "2026-08-19T10:00:00+00:00",+ "active_job_id": "job-1",+ "history_since": "2026-08-19T09:00:00+00:00",+ "inactive_since": {"orders__query_c": "2026-08-19T10:00:00+00:00"},+ }+ }+ }+ _HISTORY = QueryFolderPointerHistory(+ active="orders__query_a",+ active_since=datetime(2026, 8, 19, 10, tzinfo=UTC),+ active_job_id="job-1",+ history_since=datetime(2026, 8, 19, 9, tzinfo=UTC),+ inactive_since={"orders__query_c": datetime(2026, 8, 19, 10, tzinfo=UTC)},+ )++ @parameterized.expand(+ [+ # The flag is the rollback switch: off must reach the timestamped-folder path even when a+ # pointer record is stored, or turning it off after a bad rollout would change nothing.+ ("flag_off", False, _STATE, False, None),+ ("flag_on_with_record", True, _STATE, True, _HISTORY),+ ("flag_on_no_record", True, None, True, None),+ ]+ )+ @pytest.mark.asyncio+ async def test_passes_the_flag_and_the_pointer_history_to_the_publish_step(+ self,+ _name: str,+ flag_enabled: bool,+ stored_config: dict | None,+ expected_double_buffer: bool,+ expected_history: QueryFolderPointerHistory | None,+ ) -> None:+ schema = _make_schema(is_cdc=False)+ schema.table.queryable_folder = "orders__query_a"++ _, prepare_s3 = await _run_post_load(+ schema, _make_helper(), double_buffer_enabled=flag_enabled, stored_sync_type_config=stored_config+ )++ prepare_s3.assert_awaited_once()+ assert prepare_s3.await_args is not None+ assert prepare_s3.await_args.kwargs["existing_queryable_folder"] == "orders__query_a"+ assert prepare_s3.await_args.kwargs["double_buffer"] is expected_double_buffer+ assert prepare_s3.await_args.kwargs["pointer_history"] == expected_history++class TestZeroRowSkip:@parameterized.expand([diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/deltalite_handles.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/deltalite_handles.pynew file mode 100644index 000000000000..d8afb35ca6be--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/deltalite_handles.py@@ -0,0 +1,176 @@+"""A process-wide cache of open deltalite table handles.++Opening a `DeltaLiteTable` is a full snapshot load: a checkpoint read plus every commit since, all+over object storage. The handle then refreshes itself incrementally before each upsert, so a+loader that keeps one handle per table pays the full load once and one log listing per batch.++A cached handle is only reused for the table it was opened on. A reset or a repartition swap+replaces the table under the same URI with a new one (a new table id, a lower version), and a+handle that applied fresh commits on top of the old snapshot would plan a write against files+that no longer exist. The caller therefore hands in the identity of the table it has just opened+through delta-rs, and a handle that disagrees with it is thrown away.+"""++from __future__ import annotations++import time+import threading+import contextlib+from collections import OrderedDict+from collections.abc import Callable, Iterator+from typing import Any++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import get_governor++# A table nobody wrote to for this long gives its snapshot memory back. Sized above the gap+# between two syncs of a frequently scheduled schema, so those keep their handle.+HANDLE_IDLE_SECONDS = 600.0++Opener = Callable[[str, dict[str, str]], Any]+++def _open_deltalite_table(uri: str, storage_options: dict[str, str]) -> Any:+ # Imported at call time so a process that never writes through deltalite never loads it.+ import deltalite # noqa: PLC0415++ return deltalite.DeltaLiteTable.open(uri, storage_options)+++@frozen(frozen=False)+class _Entry:+ handle: Any+ table_id: str+ # The version the handle observed after its last upsert, recorded under the entry lock. Read+ # instead of `handle.version()` because a pyo3 object refuses a second borrow while another+ # thread's upsert holds it mutably.+ version: int+ storage_options: dict[str, str]+ last_used: float+ lock: threading.Lock+++class DeltaLiteHandleCache:+ """LRU of open deltalite handles keyed by table URI, safe to share across worker threads."""++ def __init__(+ self,+ *,+ maxsize: int,+ idle_seconds: float = HANDLE_IDLE_SECONDS,+ opener: Opener = _open_deltalite_table,+ clock: Callable[[], float] = time.monotonic,+ ) -> None:+ self._maxsize = max(1, maxsize)+ self._idle_seconds = idle_seconds+ self._opener = opener+ self._clock = clock+ self._lock = threading.Lock()+ self._entries: OrderedDict[str, _Entry] = OrderedDict()++ def __len__(self) -> int:+ with self._lock:+ return len(self._entries)++ def __contains__(self, uri: object) -> bool:+ with self._lock:+ return uri in self._entries++ @contextlib.contextmanager+ def lease(self, uri: str, *, storage_options: dict[str, str], table_id: str, table_version: int) -> Iterator[Any]:+ """Yield the handle for `uri` for exclusive use, opening or replacing it as needed.++ `table_id` and `table_version` describe the table as the caller has just read it from the+ live log. A cached handle that was opened on another table, with other credentials, or+ that is ahead of the live log is replaced.+ """+ entry = self._get_or_open(uri, storage_options, table_id, table_version)+ with entry.lock:+ try:+ yield entry.handle+ except Exception:+ # The handle's snapshot may be the reason it failed; the next batch reopens.+ self._drop(uri, entry)+ raise+ entry.version = self._observed_version(entry.handle, table_version)+ entry.last_used = self._clock()++ def invalidate(self, uri: str) -> None:+ with self._lock:+ self._entries.pop(uri, None)++ def clear(self) -> None:+ with self._lock:+ self._entries.clear()++ def _get_or_open(self, uri: str, storage_options: dict[str, str], table_id: str, table_version: int) -> _Entry:+ now = self._clock()+ with self._lock:+ self._evict_idle(now)+ entry = self._entries.get(uri)+ if entry is not None and not self._reusable(entry, storage_options, table_id, table_version):+ del self._entries[uri]+ entry = None+ if entry is not None:+ self._entries.move_to_end(uri)+ entry.last_used = now+ return entry++ # Opening is object-storage I/O, so it runs outside the cache lock.+ handle = self._opener(uri, dict(storage_options))+ opened = _Entry(+ handle=handle,+ table_id=table_id,+ version=self._observed_version(handle, table_version),+ storage_options=dict(storage_options),+ last_used=now,+ lock=threading.Lock(),+ )+ with self._lock:+ racing = self._entries.get(uri)+ if racing is not None and self._reusable(racing, storage_options, table_id, table_version):+ return racing+ self._entries[uri] = opened+ self._entries.move_to_end(uri)+ while len(self._entries) > self._maxsize:+ self._entries.popitem(last=False)+ return opened++ def _drop(self, uri: str, entry: _Entry) -> None:+ with self._lock:+ if self._entries.get(uri) is entry:+ del self._entries[uri]++ def _evict_idle(self, now: float) -> None:+ for uri, entry in list(self._entries.items()):+ if now - entry.last_used > self._idle_seconds:+ del self._entries[uri]++ @staticmethod+ def _reusable(entry: _Entry, storage_options: dict[str, str], table_id: str, table_version: int) -> bool:+ return (+ entry.table_id == table_id and entry.storage_options == storage_options and entry.version <= table_version+ )++ @staticmethod+ def _observed_version(handle: Any, fallback: int) -> int:+ try:+ version = handle.version()+ except Exception: # noqa: BLE001 - a handle that cannot report its version is treated as current+ return fallback+ return version if isinstance(version, int) else fallback+++_CACHE: DeltaLiteHandleCache | None = None+_CACHE_LOCK = threading.Lock()+++def get_handle_cache() -> DeltaLiteHandleCache:+ """The process-wide cache, sized to the number of upserts this process runs at once."""+ global _CACHE+ if _CACHE is None:+ with _CACHE_LOCK:+ if _CACHE is None:+ _CACHE = DeltaLiteHandleCache(maxsize=get_governor().config.max_concurrent)+ return _CACHEdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.pyindex 633c891cf130..b32ad3e2eb52 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py@@ -13,6 +13,9 @@ from posthog.sync import database_sync_to_async_poolfrom products.data_warehouse.backend.facade.api import aget_s3_client, delta_proxy_storage_options, ensure_bucket_existsfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.deltalite_handles import (+ get_handle_cache,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (TransientObjectStoreError,is_transient_delta_maintenance_error,@@ -161,6 +164,7 @@ class DeltaTableRef:_logger: FilteringBoundLogger_is_first_sync: bool_cached_table: deltalake.DeltaTable | None+ _table_uri: str | Nonedef __init__(self, resource_name: str, job: ExternalDataJob, logger: FilteringBoundLogger, is_first_sync: bool = False@@ -170,6 +174,7 @@ class DeltaTableRef:self._logger = loggerself._is_first_sync = is_first_syncself._cached_table = None+ self._table_uri = None@propertydef is_first_sync(self) -> bool:@@ -192,11 +197,14 @@ class DeltaTableRef:async def _get_delta_table_uri(self) -> str:folder_path = await database_sync_to_async_pool(self._job.folder_path)()- return build_delta_table_uri(folder_path, self._resource_name)+ self._table_uri = build_delta_table_uri(folder_path, self._resource_name)+ return self._table_uriasync def get_table_uri(self) -> str:"""Public accessor for the live Delta table S3 URI (used by the in-place repartitioner)."""- return await self._get_delta_table_uri()+ uri = await self._get_delta_table_uri()+ self._table_uri = uri+ return uridef get_storage_options(self) -> dict[str, str]:"""Public accessor for the delta-rs storage options (used by the in-place repartitioner)."""@@ -254,8 +262,14 @@ class DeltaTableRef:return tabledef invalidate_cached_table(self) -> None:- """Drop the cached handle so the next `get_delta_table` re-reads the live Delta log."""+ """Drop the cached handle so the next `get_delta_table` re-reads the live Delta log.++ The process-wide deltalite handle for this table goes with it: a reset or a repartition swap+ has replaced the table under the same URI, and that handle's snapshot describes the old one.+ """self._cached_table = None+ if self._table_uri is not None:+ get_handle_cache().invalidate(self._table_uri)def pop_cached_table(self) -> deltalake.DeltaTable | None:"""Release the cached handle without opening the table, for end-of-run memory cleanup."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.pyindex f171df459c30..66afa737c3ec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_table.py@@ -8,6 +8,9 @@ from django.test import override_settingsimport deltalakefrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.deltalite_handles import (+ DeltaLiteHandleCache,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (TransientObjectStoreError,)@@ -441,3 +444,24 @@ class TestPurgeS3PrefixPermissionErrors:await _purge_s3_prefix(MagicMock(), "s3://bucket/prefix")assert mock_once.await_count == expected_attempts+++class TestInvalidateDropsTheDeltaliteHandle:+ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table"++ @pytest.mark.asyncio+ async def test_invalidating_the_ref_forgets_the_process_wide_handle(self):+ # A reset or repartition swap replaces the table under the same URI. A deltalite handle+ # that survives it would refresh the old snapshot with the new log's commits.+ cache = DeltaLiteHandleCache(maxsize=2, opener=lambda uri, storage_options: MagicMock())+ ref = _openable_table_ref("s3://bucket/team/job/t")++ with patch(f"{self._MODULE}.get_handle_cache", return_value=cache):+ await ref.get_table_uri()+ with cache.lease("s3://bucket/team/job/t", storage_options={}, table_id="tid", table_version=1):+ pass+ assert "s3://bucket/team/job/t" in cache++ ref.invalidate_cached_table()++ assert "s3://bucket/team/job/t" not in cachediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.pyindex d46d659cb5a7..a39b99f52cdf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py@@ -22,6 +22,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrrealign_decimal_buffers,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.deltalite_handles import (+ DeltaLiteHandleCache,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenancefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import ensure_table_propertiesfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef@@ -35,6 +38,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delDeltaWriter,_deltalite_write_stats,_merge_predicate_ops,+ commit_covers_batch,)_WRITER_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer"@@ -115,7 +119,11 @@ def _make_writer() -> DeltaWriter:# exist specifically to exercise deltalite opt back in (`TestDeltaliteWritePath` drives the real# method directly / fakes the `deltalite` module itself, and `TestNullabilityDriftGuardOrder`# already sets this mock explicitly in both directions).-_DELTALITE_OPT_IN_CLASSES = {"TestDeltaliteWritePath", "TestNullabilityDriftGuardOrder"}+_DELTALITE_OPT_IN_CLASSES = {+ "TestDeltaliteWritePath",+ "TestNullabilityDriftGuardOrder",+ "TestDeltaliteHandleReuseInWriter",+}@pytest.fixture(autouse=True)@@ -164,18 +172,23 @@ class TestHasBatchBeenCommitted:[("string_run_uuid_int_batch", "run-123", 5, True),("zero_batch_index", "run-1", 0, False),+ ("member_of_a_set", "run-123", 7, True),])@pytest.mark.asyncio- async def test_wraps_has_commit_with_metadata(- self, _name: str, run_uuid: str, batch_index: int, mocked_return: bool+ async def test_finds_the_commit_that_wrote_the_batch(+ self, _name: str, run_uuid: str, batch_index: int, expected: bool):+ # A batch written alone is tagged with its index; one written as part of a set is listed+ # under `batch_indexes`. Missing either lets a redelivery merge the batch a second time.writer = _make_writer()- with patch.object(writer, "has_commit_with_metadata", AsyncMock(return_value=mocked_return)) as m:- result = await writer.has_batch_been_committed(run_uuid, batch_index)-- assert result is mocked_return- m.assert_called_once_with({"run_uuid": run_uuid, "batch_index": str(batch_index)})+ table = MagicMock()+ table.history.return_value = [+ {"run_uuid": "run-123", "batch_index": "5"},+ {"run_uuid": "run-123", "batch_index": "6", "batch_indexes": "6,7,8"},+ ]+ with patch.object(writer._table, "get_delta_table", AsyncMock(return_value=table)):+ assert await writer.has_batch_been_committed(run_uuid, batch_index) is expectedclass TestWriteToDeltalakeCommitMetadataPassThrough:@@ -1257,3 +1270,213 @@ class TestRealignDecimalBuffers:assert result.num_rows == 0assert result.schema == table.schema+++def _fake_handle(version: int, upsert_error: Exception | None = None) -> MagicMock:+ handle = MagicMock()+ handle.version.return_value = version+ if upsert_error is not None:+ handle.upsert.side_effect = upsert_error+ return handle+++class TestDeltaLiteHandleCache:+ """A cached handle that is reused for a table it was not opened on plans a write against files+ that a reset or a repartition swap already removed, so identity is what the cache is about."""++ def _cache(self, opened: list[str], versions: dict[str, int] | None = None, **kwargs: Any) -> DeltaLiteHandleCache:+ def opener(uri: str, storage_options: dict[str, str]) -> MagicMock:+ opened.append(uri)+ return _fake_handle((versions or {}).get(uri, 0))++ return DeltaLiteHandleCache(maxsize=kwargs.pop("maxsize", 4), opener=opener, **kwargs)++ def test_consecutive_leases_on_one_table_open_it_once(self) -> None:+ opened: list[str] = []+ cache = self._cache(opened)++ with cache.lease("s3://b/t", storage_options={}, table_id="tid", table_version=3) as first:+ first.version.return_value = 4+ with cache.lease("s3://b/t", storage_options={}, table_id="tid", table_version=4) as second:+ pass++ assert first is second+ assert opened == ["s3://b/t"]++ @parameterized.expand(+ [+ ("table_recreated", "other-tid", 3, {}),+ ("handle_ahead_of_the_live_log", "tid", 1, {}),+ ("credentials_changed", "tid", 3, {"AWS_SECRET_ACCESS_KEY": "rotated"}),+ ]+ )+ def test_a_handle_that_disagrees_with_the_live_table_is_replaced(+ self, _case: str, table_id: str, table_version: int, storage_options: dict[str, str]+ ) -> None:+ opened: list[str] = []+ cache = self._cache(opened, versions={"s3://b/t": 3})++ with cache.lease("s3://b/t", storage_options={}, table_id="tid", table_version=3) as first:+ pass+ with cache.lease(+ "s3://b/t", storage_options=storage_options, table_id=table_id, table_version=table_version+ ) as second:+ pass++ assert first is not second+ assert opened == ["s3://b/t", "s3://b/t"]++ def test_a_failed_lease_evicts_the_handle(self) -> None:+ opened: list[str] = []+ cache = self._cache(opened)++ with pytest.raises(RuntimeError, match="conflict"):+ with cache.lease("s3://b/t", storage_options={}, table_id="tid", table_version=0):+ raise RuntimeError("conflict retries exhausted")++ assert "s3://b/t" not in cache+ with cache.lease("s3://b/t", storage_options={}, table_id="tid", table_version=0):+ pass+ assert opened == ["s3://b/t", "s3://b/t"]++ def test_handles_are_bounded_by_size_and_idle_time(self) -> None:+ opened: list[str] = []+ now = {"t": 0.0}+ cache = self._cache(opened, maxsize=2, idle_seconds=100.0, clock=lambda: now["t"])++ for uri in ("s3://b/a", "s3://b/b", "s3://b/c"):+ with cache.lease(uri, storage_options={}, table_id="tid", table_version=0):+ pass+ assert "s3://b/a" not in cache and len(cache) == 2++ now["t"] = 101.0+ with cache.lease("s3://b/d", storage_options={}, table_id="tid", table_version=0):+ pass+ assert list(cache._entries) == ["s3://b/d"]++ def test_invalidate_forgets_the_handle(self) -> None:+ opened: list[str] = []+ cache = self._cache(opened)+ with cache.lease("s3://b/t", storage_options={}, table_id="tid", table_version=0):+ pass++ cache.invalidate("s3://b/t")++ assert "s3://b/t" not in cache+ cache.invalidate("s3://b/never-opened")+++class TestDeltaliteHandleReuseInWriter:+ _HANDLES = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.deltalite_handles"++ @pytest.fixture(autouse=True)+ def _preload_write_metrics(self):+ # Same reason as TestDeltaliteWritePath: keep the metrics module out of the sys.modules snapshot.+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load import ( # noqa: F401+ metrics,+ )++ async def _write(self, helper: DeltaTableRef, existing: MagicMock) -> bool:+ return await DeltaWriter(helper)._write_via_deltalite(+ existing_delta_table=existing,+ data=pa.table({"id": pa.array([1], pa.int64())}),+ normalized_primary_keys=["id"],+ use_partitioning=False,+ commit_metadata=None,+ )++ @staticmethod+ def _existing(table_id: str, version: int) -> MagicMock:+ existing = MagicMock()+ existing.metadata.return_value.id = table_id+ existing.version.return_value = version+ return existing++ @pytest.mark.asyncio+ async def test_consecutive_batches_share_one_open(self) -> None:+ # Every batch used to pay a full snapshot load; the handle refreshes itself incrementally.+ helper = DeltaTableRef(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=make_logger())+ fake_table = _fake_handle(4)+ fake_deltalite = MagicMock()+ fake_deltalite.DeltaLiteTable.open.return_value = fake_table+ cache = DeltaLiteHandleCache(maxsize=4)+ with (+ patch.dict("sys.modules", {"deltalite": fake_deltalite}),+ patch(f"{self._HANDLES}.get_handle_cache", return_value=cache),+ patch.object(helper, "_get_delta_table_uri", AsyncMock(return_value="s3://b/t")),+ patch.object(helper, "_get_credentials", return_value={}),+ ):+ assert await self._write(helper, self._existing("tid", 3)) is True+ assert await self._write(helper, self._existing("tid", 4)) is True++ fake_deltalite.DeltaLiteTable.open.assert_called_once_with("s3://b/t", {})+ assert fake_table.upsert.call_count == 2++ @pytest.mark.asyncio+ async def test_a_failed_upsert_reopens_on_the_next_batch(self) -> None:+ helper = DeltaTableRef(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=make_logger())+ fake_deltalite = MagicMock()+ fake_deltalite.DeltaLiteTable.open.side_effect = [+ _fake_handle(3, RuntimeError("commit conflict, retries exhausted")),+ _fake_handle(4),+ ]+ cache = DeltaLiteHandleCache(maxsize=4)+ with (+ patch.dict("sys.modules", {"deltalite": fake_deltalite}),+ patch(f"{self._HANDLES}.get_handle_cache", return_value=cache),+ patch.object(helper, "_get_delta_table_uri", AsyncMock(return_value="s3://b/t")),+ patch.object(helper, "_get_credentials", return_value={}),+ ):+ assert await self._write(helper, self._existing("tid", 3)) is False+ assert await self._write(helper, self._existing("tid", 3)) is True++ assert fake_deltalite.DeltaLiteTable.open.call_count == 2++ @pytest.mark.asyncio+ async def test_an_unknown_live_identity_never_reuses_a_handle(self) -> None:+ # Without a table id and version to compare against, reuse cannot be proven safe.+ helper = DeltaTableRef(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=make_logger())+ fake_deltalite = MagicMock()+ fake_deltalite.DeltaLiteTable.open.return_value = _fake_handle(1)+ cache = DeltaLiteHandleCache(maxsize=4)+ with (+ patch.dict("sys.modules", {"deltalite": fake_deltalite}),+ patch(f"{self._HANDLES}.get_handle_cache", return_value=cache),+ patch.object(helper, "_get_delta_table_uri", AsyncMock(return_value="s3://b/t")),+ patch.object(helper, "_get_credentials", return_value={}),+ ):+ assert await self._write(helper, MagicMock()) is True+ assert await self._write(helper, MagicMock()) is True++ assert fake_deltalite.DeltaLiteTable.open.call_count == 2+ assert len(cache) == 0+++class TestCommitCoversBatch:+ # A coalesced write names its members under `batch_indexes`; a member's redelivery that only+ # looked at `batch_index` would miss the commit and merge its rows again.++ @parameterized.expand(+ [+ ("flat_single", {"run_uuid": "r", "batch_index": "4"}, 4, True),+ ("flat_member", {"run_uuid": "r", "batch_index": "3", "batch_indexes": "3,4,5"}, 4, True),+ ("flat_not_a_member", {"run_uuid": "r", "batch_index": "3", "batch_indexes": "3,4,5"}, 6, False),+ ("flat_other_run", {"run_uuid": "other", "batch_index": "4"}, 4, False),+ ("nested_json_member", {"userMetadata": json.dumps({"run_uuid": "r", "batch_indexes": "3,4"})}, 4, True),+ ("nested_dict_single", {"userMetadata": {"run_uuid": "r", "batch_index": "4"}}, 4, True),+ ("no_metadata", {"operation": "WRITE"}, 4, False),+ ]+ )+ def test_matches_single_and_set_commits(self, _case: str, commit: dict, batch_index: int, expected: bool):+ assert commit_covers_batch(commit, "r", batch_index) is expected++ @pytest.mark.asyncio+ async def test_has_batch_been_committed_finds_a_member_of_a_set(self):+ helper = MagicMock()+ table = MagicMock()+ table.history.return_value = [{"run_uuid": "r", "batch_index": "3", "batch_indexes": "3,4,5"}]+ helper.get_delta_table = AsyncMock(return_value=table)+ helper.logger = make_logger()++ assert await DeltaWriter(helper).has_batch_been_committed("r", 5) is True+ assert await DeltaWriter(helper).has_batch_been_committed("r", 6) is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.pyindex 0d41d6bede9b..501d3a49fd65 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py@@ -93,30 +93,62 @@ def _deltalite_write_stats(stats: Any) -> dict[str, int | float | str | bool]:return fields-def commit_matches(commit: dict[str, Any], match: dict[str, str]) -> bool:- """Return True iff every (k, v) in `match` is present in this commit's metadata.+def _delta_table_identity(delta_table: deltalake.DeltaTable) -> tuple[str, int] | None:+ """The (table id, version) a delta-rs handle observes, or None when it cannot say.- Handles both the flat layout (delta-rs 1.x inlines custom_metadata onto the- top-level commit dict) and a nested `userMetadata` key (older/other layouts).+ None makes the deltalite write open a fresh handle instead of trusting a cached one: reuse is+ only safe when the caller can prove which table the cached snapshot belongs to."""- if all(commit.get(k) == v for k, v in match.items()):- return True-+ try:+ # Typed as object: a test double stands in for the handle here, and its attributes are not+ # the str and int the delta-rs stubs promise.+ table_id: object = delta_table.metadata().id+ version: object = delta_table.version()+ except Exception: # noqa: BLE001 - an unreadable identity only costs a fresh open+ return None+ if not isinstance(table_id, str) or not isinstance(version, int):+ return None+ return table_id, version+++def _commit_metadata_layouts(commit: dict[str, Any]) -> list[dict[str, Any]]:+ """The places a commit's custom metadata can live: inlined onto the commit dict (delta-rs 1.x)+ or nested under `userMetadata` as a dict or a JSON string (older/other layouts)."""+ layouts: list[dict[str, Any]] = [commit]raw = commit.get("userMetadata")- if raw is None:- return False-if isinstance(raw, str):try:nested = json.loads(raw)except (json.JSONDecodeError, ValueError):- return False+ nested = None+ if isinstance(nested, dict):+ layouts.append(nested)elif isinstance(raw, dict):- nested = raw- else:- return False+ layouts.append(raw)+ return layouts+++def commit_matches(commit: dict[str, Any], match: dict[str, str]) -> bool:+ """Return True iff every (k, v) in `match` is present in this commit's metadata."""+ return any(all(layout.get(k) == v for k, v in match.items()) for layout in _commit_metadata_layouts(commit))- return all(nested.get(k) == v for k, v in match.items())++def commit_covers_batch(commit: dict[str, Any], run_uuid: str, batch_index: int) -> bool:+ """Whether this commit wrote `batch_index` of `run_uuid`, alone or as one member of a set.++ A write of several consecutive batches is tagged with the first index under `batch_index` and+ every member under `batch_indexes`, so a member's redelivery has to look in both.+ """+ wanted = str(batch_index)+ for layout in _commit_metadata_layouts(commit):+ if layout.get("run_uuid") != run_uuid:+ continue+ if layout.get("batch_index") == wanted:+ return True+ members = layout.get("batch_indexes")+ if isinstance(members, str) and wanted in members.split(","):+ return True+ return Falseclass DeltaWriter:@@ -183,6 +215,9 @@ class DeltaWriter:try:import deltalite+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.deltalite_handles import (+ get_handle_cache,+ )from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import (get_governor,)@@ -199,6 +234,9 @@ class DeltaWriter:if use_partitioning and PARTITION_KEY in data.column_nameselse None)+ # The delta-rs handle was opened from the live log this batch, so it says which table+ # (and which version of it) a cached deltalite handle must match to be reused.+ live_identity = _delta_table_identity(existing_delta_table)# Capacity planning: size this upsert's knobs to a fixed per-upsert slice of pod memory,# so all MAX_CONCURRENT_ACTIVITIES upserts on this process are guaranteed to fit. deltalite@@ -207,8 +245,7 @@ class DeltaWriter:# mpp=1 (governor logs a capacity_exceeded ops signal).async with get_governor().admit(source_bytes=data.nbytes, n_partitions=n_partitions) as adm:- def _upsert(upsert_kwargs: dict[str, int] = adm.upsert_kwargs) -> Any:- table = deltalite.DeltaLiteTable.open(uri, storage_options)+ def _run_upsert(table: Any, upsert_kwargs: dict[str, int]) -> Any:return table.upsert(data,list(normalized_primary_keys),@@ -217,6 +254,15 @@ class DeltaWriter:**upsert_kwargs,)+ def _upsert(upsert_kwargs: dict[str, int] = adm.upsert_kwargs) -> Any:+ if live_identity is None:+ return _run_upsert(deltalite.DeltaLiteTable.open(uri, storage_options), upsert_kwargs)+ table_id, table_version = live_identity+ with get_handle_cache().lease(+ uri, storage_options=storage_options, table_id=table_id, table_version=table_version+ ) as table:+ return _run_upsert(table, upsert_kwargs)+started = time.perf_counter()stats = await asyncio.to_thread(_upsert)duration_s = time.perf_counter() - started@@ -601,10 +647,12 @@ class DeltaWriter:return False- async def has_batch_been_committed(self, run_uuid: str, batch_index: int) -> bool:- """Check whether a specific (run_uuid, batch_index) has already been committed to delta.+ async def has_batch_been_committed(self, run_uuid: str, batch_index: int, *, scan_limit: int = 50) -> bool:+ """Check whether a specific (run_uuid, batch_index) has already been committed to delta,+ on its own or as a member of a coalesced write (see `commit_covers_batch`)."""+ delta_table = await self._table.get_delta_table()+ if delta_table is None:+ return False- Thin wrapper around `has_commit_with_metadata` so callers don't need to know- the metadata schema used for idempotency tagging.- """- return await self.has_commit_with_metadata({"run_uuid": run_uuid, "batch_index": str(batch_index)})+ history = await asyncio.to_thread(delta_table.history, limit=scan_limit)+ return any(commit_covers_batch(commit, run_uuid, batch_index) for commit in history)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.pyindex 072a49327f49..1b0f923ccb7f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py@@ -1,4 +1,6 @@+import jsonimport uuid+import hashlibimport datetime as dtfrom dataclasses import dataclassfrom datetime import date, datetime@@ -39,6 +41,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpersbuild_table_name,resolve_table_and_folder_names,)+from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import advance_query_folder_pointerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (filter_dwh_columns_by_enabled_columns,)@@ -51,6 +54,76 @@ from products.warehouse_sources.backend.types import (LOGGER = get_logger(__name__)+def _record_query_folder_pointer(+ schema_id: uuid.UUID,+ team_id: int,+ previous_folder: Optional[str],+ queryable_folder: str,+ job_id: str,+ logger: FilteringBoundLogger,+) -> None:+ """Record the pointer move, so the publish step knows when each slot stopped being read.++ Written right after the pointer write rather than inside it, because the pointer lives on the+ table row and the record on the schema row. A crash between the two leaves a move unrecorded,+ which the next record detects and treats as unknown history, so the gap is safe. Best effort for+ the same reason: the pointer has landed, and failing the sync here would discard a load that+ succeeded.+ """++ def _mutate(config: dict[str, Any]) -> None:+ advance_query_folder_pointer(+ config, previous_folder=previous_folder, queryable_folder=queryable_folder, job_id=job_id+ )++ try:+ retry_on_db_connection_drop(lambda: update_sync_type_config_keys(schema_id, team_id, mutate=_mutate))+ except Exception:+ logger.warning(f"Could not record the query folder pointer move to {queryable_folder}", exc_info=True)+++# `sync_type_config` key holding the fingerprint of the inputs the table's `columns` were last built+# from, so a sync whose inputs match can skip introspecting the table again.+REGISTERED_SCHEMA_FINGERPRINT_KEY = "registered_schema_fingerprint"+++def registered_schema_fingerprint(+ delta_schema_json: str,+ table_schema_dict: dict[str, str],+ enabled_columns: Any,+ primary_keys: Any,+ incremental_field: Any,+) -> str:+ """Hash of everything `columns` is a pure function of, apart from the introspection itself.++ The ClickHouse DESCRIBE reads the Delta log's schema, so the same Delta schema gives the same+ introspection. The rest are the projection inputs applied after it, which a user can change+ between syncs (the column picker, a primary key) and which must invalidate the skip.+ """+ payload = {+ "delta_schema": delta_schema_json,+ "table_schema": table_schema_dict,+ "enabled_columns": enabled_columns,+ "primary_keys": primary_keys,+ "incremental_field": incremental_field,+ }+ return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()+++def _record_registered_schema_fingerprint(+ schema_id: uuid.UUID, team_id: int, fingerprint: str, logger: FilteringBoundLogger+) -> None:+ # Best effort: without the stamp the next sync introspects again, which is the safe direction.+ try:+ retry_on_db_connection_drop(+ lambda: update_sync_type_config_keys(+ schema_id, team_id, updates={REGISTERED_SCHEMA_FINGERPRINT_KEY: fingerprint}+ )+ )+ except Exception:+ logger.warning("Could not record the registered schema fingerprint", exc_info=True)++def merge_columns(db_columns: dict[str, str],table_schema_dict: dict[str, str],@@ -194,6 +267,7 @@ async def validate_schema_and_update_table(queryable_folder: str,table_schema_dict: Optional[dict[str, str]] = None,primary_keys: Optional[list[str]] = None,+ delta_schema_json: Optional[str] = None,) -> None:"""Async version of validate_schema_and_update_table_sync.@@ -208,6 +282,9 @@ async def validate_schema_and_update_table(row_count: The count of synced rowstable_format: The format of the tabletable_schema_dict: The schema of the table+ delta_schema_json: The Delta table's schema. When given and unchanged since the columns were+ last registered (together with the projection inputs), the ClickHouse introspection and+ the column write are skipped; the pointer flip and the row count still happen."""logger = LOGGER.bind(team_id=team_id)@@ -275,6 +352,7 @@ async def validate_schema_and_update_table(if table_created:table = table_created+ previous_queryable_folder = table.queryable_foldertable.format = table_params["format"]table.url_pattern = new_url_patterntable.queryable_folder = queryable_folder@@ -295,6 +373,9 @@ async def validate_schema_and_update_table(internally_computed_url_pattern=True,))+ _record_query_folder_pointer(+ _schema_id, team_id, previous_queryable_folder, queryable_folder, run_id, logger+ )else:logger.debug(f"Creating table for schema: {str(schema_id)}")@@ -303,6 +384,7 @@ async def validate_schema_and_update_table(created_via=DataWarehouseTableCreatedVia.SOURCE,**table_params,)+ _record_query_folder_pointer(_schema_id, team_id, None, queryable_folder, run_id, logger)if row_count == 0:# table_params holds 0 for a table an earlier attempt already filled. get_count()# can block long enough for the pooled connection to go stale, as above.@@ -312,6 +394,29 @@ async def validate_schema_and_update_table(assert isinstance(table_created, DataWarehouseTable) and table_created is not None+ # Prefer source-detected PKs (always present) over the schema model's PKs (only set+ # for CDC and user-picked incremental keys) so non-CDC schemas don't drop their PKs.+ effective_primary_keys = primary_keys or external_data_schema.primary_key_columns++ fingerprint: Optional[str] = None+ if delta_schema_json is not None:+ fingerprint = registered_schema_fingerprint(+ delta_schema_json,+ table_schema_dict or {},+ external_data_schema.enabled_columns,+ effective_primary_keys,+ external_data_schema.incremental_field,+ )+ if (+ fingerprint == (external_data_schema.sync_type_config or {}).get(REGISTERED_SCHEMA_FINGERPRINT_KEY)+ and table_created.columns+ and external_data_schema.table_id == table_created.id+ ):+ logger.debug(+ f"Registered schema unchanged for {_schema_name} ({_schema_id}), skipping introspection"+ )+ return+# safe_expose_ch_error=False keeps failures as ServerException (see except clause below)# instead of the generic, user-facing Exception get_columns() raises by default.raw_db_columns = table_created.get_columns(safe_expose_ch_error=False)@@ -329,9 +434,6 @@ async def validate_schema_and_update_table(columns = merge_columns(db_columns, table_schema_dict or {}, existing_columns)# Project to enabled_columns so disabled columns the user already deselected don't# creep back into HogQL via the Delta schema (which still contains them historically).- # Prefer source-detected PKs (always present) over the schema model's PKs (only set- # for CDC and user-picked incremental keys) so non-CDC schemas don't drop their PKs.- effective_primary_keys = primary_keys or external_data_schema.primary_key_columnscolumns = filter_dwh_columns_by_enabled_columns(columns,external_data_schema.enabled_columns,@@ -358,6 +460,8 @@ async def validate_schema_and_update_table(# stale. A dropped connection mid-atomic-block rolls the block back, so retrying it whole# is safe.retry_on_db_connection_drop(_persist_columns)+ if fingerprint is not None:+ _record_registered_schema_fingerprint(_schema_id, team_id, fingerprint, logger)except ServerException as err:# 636 (CANNOT_EXTRACT_TABLE_STRUCTURE) and 742 (DELTA_KERNEL_ERROR, "No files in log@@ -439,6 +543,7 @@ async def register_cdc_companion_table(deleted=False,).first()+ previous_queryable_folder = companion_table.queryable_folder if companion_table else Noneif companion_table:table = companion_tabletable.format = table_format@@ -465,6 +570,9 @@ async def register_cdc_companion_table(created_via=DataWarehouseTableCreatedVia.SOURCE,**table_params,)+ _record_query_folder_pointer(+ schema_id, team_id, previous_queryable_folder, queryable_folder, run_id, logger+ )raw_db_columns = companion_table.get_columns()db_columns = {key: str(column.get("clickhouse", "")) for key, column in raw_db_columns.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex d6ec4ac504b2..e6e43ed7116e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -4,9 +4,10 @@ import timeimport randomimport signalimport asyncio+import contextlibfrom collections import defaultdict-from collections.abc import Callable, Coroutine-from dataclasses import dataclass+from collections.abc import Callable, Coroutine, Iterator+from dataclasses import dataclass, replacefrom datetime import datetimefrom functools import partialfrom typing import Any, Protocol, TypeVar@@ -219,6 +220,13 @@ class OwnershipLostError(Exception):"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""+class CoalescingDeclined(Exception):+ """Raise from ``process_batches`` before any side effect when a set cannot be loaded as one write.++ The engine then loads the constituents one by one. Because nothing was written, the attempt is+ not spent; any other exception out of ``process_batches`` is, since the write may have landed."""++class PermanentBatchApplyError(Exception):"""Raise from process_batch for errors retries cannot fix (unsupported batchkind, missing primary keys, malformed batch metadata). The consumer skips@@ -420,6 +428,13 @@ class BatchConsumerAdapter(Protocol):batch: PendingBatch,) -> None: ...+ def coalesce_group(self, batches: list[PendingBatch]) -> list[list[PendingBatch]]:+ """Partition an ordered group into the sets the sink can load in one write.++ Consulted only when the engine was given ``process_batches``. A sink that never coalesces+ returns one singleton per batch. Order within and across sets must be the input order."""+ ...+class BatchConsumer:def __init__(@@ -429,9 +444,12 @@ class BatchConsumer:adapter: BatchConsumerAdapter,health_reporter: Callable[[], None] | None = None,metrics: ConsumerMetrics | None = None,+ process_batches: ProcessBatchesFn | None = None,) -> None:self._config = configself._process_batch = process_batch+ # Loads several consecutive batches of one run in one write; None keeps every batch single.+ self._process_batches = process_batchesself._adapter = adapter# Per-pod identity for group-lease ownership. A new token each start means# a restarted pod cannot accidentally renew a lease it abandoned pre-restart.@@ -861,17 +879,23 @@ class BatchConsumer:)return- for batch in batches:+ sets = self._coalesce(batches)+ processed = 0+ for batch_set in sets:+ batch = batch_set[0]if self._shutdown.is_set():logger.info(self._event("shutdown_mid_group"),team_id=team_id,schema_id=schema_id,- remaining=len(batches) - batches.index(batch),+ remaining=len(batches) - processed,)breaktry:- succeeded = await self._process_single(batch, lock_conn=group_conn)+ if len(batch_set) == 1:+ succeeded = await self._process_single(batch, lock_conn=group_conn)+ else:+ succeeded = await self._process_set(batch_set, lock_conn=group_conn)except OwnershipLostError:logger.warning(self._event("ownership_lost_abandoning_group"),@@ -889,13 +913,14 @@ class BatchConsumer:)capture_exception(e)succeeded = False+ processed += len(batch_set)if not succeeded:logger.info(self._event("group_halted_by_non_success"),team_id=team_id,schema_id=schema_id,run_uuid=batch.run_uuid,- remaining=len(batches) - batches.index(batch) - 1,+ remaining=len(batches) - processed,)breakfinally:@@ -1019,11 +1044,24 @@ class BatchConsumer:if not renewed:raise OwnershipLostError(f"group lease lost for ({batch.team_id}, {batch.schema_id})")+ def _coalesce(self, batches: list[PendingBatch]) -> list[list[PendingBatch]]:+ if self._process_batches is None:+ return [[batch] for batch in batches]+ return self._adapter.coalesce_group(batches)+async def _batch_heartbeat(self,lock_conn: psycopg.AsyncConnection[Any],batch: PendingBatch,attempt: int,+ ) -> None:+ await self._set_heartbeat(lock_conn, [batch], {batch.id: attempt})++ async def _set_heartbeat(+ self,+ lock_conn: psycopg.AsyncConnection[Any],+ batches: list[PendingBatch],+ attempts: dict[str, int],) -> None:"""Renew the group lease and re-insert EXECUTING status periodically to prevent premature recovery.@@ -1034,7 +1072,10 @@ class BatchConsumer:for good (reclaimed, sweep-deleted, or expired — expiry is terminal), sowe stop heartbeating immediately; the pre-success ownership check thenabandons the in-flight batch instead of writing ``succeeded``.++ A coalesced set shares one lease and refreshes every constituent's row."""+ batch = batches[0]interval = max((self._config.recovery_grace_seconds or RECOVERY_GRACE_SECONDS) / 3, 10.0)while True:await asyncio.sleep(interval)@@ -1072,31 +1113,28 @@ class BatchConsumer:external_data_schema_id=batch.schema_id,)return- try:- await self._adapter.update_status(- lock_conn,- batch_id=batch.id,- job_state=self._adapter.executing_state,- attempt=attempt,- batch_created_at=batch.created_at,- )- except Exception as e:- logger.warning(- self._event("batch_heartbeat_status_refresh_failed"),- batch_id=batch.id,- team_id=batch.team_id,- external_data_schema_id=batch.schema_id,- error=str(e),- )-- async def _process_single(self, batch: PendingBatch, lock_conn: psycopg.AsyncConnection[Any] | None = None) -> bool:- """Bind per-batch log context, then process. Returns True only on success.-- Binds structlog contextvars so every downstream log line (including loader calls)- routes to log_entries under the right schema/workflow before any logger fires.- """- attempt = batch.latest_attempt + 1+ for member in batches:+ try:+ await self._adapter.update_status(+ lock_conn,+ batch_id=member.id,+ job_state=self._adapter.executing_state,+ attempt=attempts[member.id],+ batch_created_at=member.created_at,+ )+ except Exception as e:+ logger.warning(+ self._event("batch_heartbeat_status_refresh_failed"),+ batch_id=member.id,+ team_id=member.team_id,+ external_data_schema_id=member.schema_id,+ error=str(e),+ )+ @contextlib.contextmanager+ def _batch_log_context(self, batch: PendingBatch, attempt: int) -> Iterator[None]:+ """Bind structlog contextvars so every downstream log line (including loader calls)+ routes to log_entries under the right schema/workflow before any logger fires."""workflow_id = batch.metadata.get("workflow_id") or ""workflow_run_id = batch.metadata.get("workflow_run_id") or ""workflow_type = "cdc-extraction" if workflow_id.startswith("cdc-extraction-") else "external-data-job"@@ -1131,15 +1169,143 @@ class BatchConsumer:)self._inflight_started[batch.id] = time.monotonic()try:+ yield+ finally:+ self._inflight_started.pop(batch.id, None)+ structlog.contextvars.unbind_contextvars(*bound_keys)++ async def _process_single(self, batch: PendingBatch, lock_conn: psycopg.AsyncConnection[Any] | None = None) -> bool:+ """Bind per-batch log context, then process. Returns True only on success."""+ attempt = batch.latest_attempt + 1+ with self._batch_log_context(batch, attempt):# Renew-or-abandon at entry (not a pure verify): re-ups the lease on# every batch so a long run of short batches can't expire it at# cumulative TTL and get abandoned mid-group. The pre-commit check in# _process_single_inner stays a fail-closed verify.await self._renew_ownership(lock_conn, batch)return await self._process_single_inner(batch, attempt, lock_conn)- finally:- self._inflight_started.pop(batch.id, None)- structlog.contextvars.unbind_contextvars(*bound_keys)++ async def _process_set(self, batches: list[PendingBatch], lock_conn: psycopg.AsyncConnection[Any] | None) -> bool:+ """Load several consecutive batches of one run as one write. Returns True only on success.++ Every constituent gets the same status transitions a single batch would, so recovery,+ the claim gates and the reconcile sweeps see nothing new. Anything that stops the set+ from loading as one falls back to the constituents one by one: a sink that declines+ before writing hands them over as they are, and a failure after that hands them over+ as redeliveries, so the single-batch idempotency check looks for the write the set+ may have committed.+ """+ assert self._process_batches is not None+ head = batches[0]+ attempts = {batch.id: batch.latest_attempt + 1 for batch in batches}+ if any(attempt > self._config.max_attempts for attempt in attempts.values()):+ return await self._process_singly(batches, lock_conn, spent_attempt=False)++ with self._batch_log_context(head, attempts[head.id]):+ await self._renew_ownership(lock_conn, head)+ status_conn = await self._get_status_conn(lock_conn)++ for batch in batches:+ if not await self._adapter.should_process_batch(status_conn, batch=batch):+ return await self._process_singly(batches, lock_conn, spent_attempt=False)++ logger.info(+ self._event("batch_set_picked_up"),+ batch_ids=[batch.id for batch in batches],+ run_uuid=head.run_uuid,+ batch_indexes=[batch.batch_index for batch in batches],+ is_final_batch=batches[-1].is_final_batch,+ resource_name=head.resource_name,+ )+ for batch in batches:+ await self._adapter.update_status(+ status_conn,+ batch_id=batch.id,+ job_state=self._adapter.executing_state,+ attempt=attempts[batch.id],+ batch_created_at=batch.created_at,+ )++ heartbeat_task: asyncio.Task[None] | None = None+ start = time.monotonic()+ try:+ if lock_conn is not None:+ heartbeat_task = asyncio.create_task(self._set_heartbeat(lock_conn, batches, attempts))+ try:+ await self._process_batches(batches)+ except CoalescingDeclined as declined:+ await self._stop_heartbeat(heartbeat_task)+ heartbeat_task = None+ logger.info(self._event("batch_set_declined"), run_uuid=head.run_uuid, reason=str(declined))+ return await self._process_singly(batches, lock_conn, spent_attempt=False)+ except OwnershipLostError:+ raise+ except Exception as err:+ await self._stop_heartbeat(heartbeat_task)+ heartbeat_task = None+ logger.warning(+ self._event("batch_set_failed_loading_singly"),+ run_uuid=head.run_uuid,+ batch_indexes=[batch.batch_index for batch in batches],+ error=str(err),+ error_type=type(err).__name__,+ )+ self._metrics.coalesced_sets_total.labels(outcome="failed").inc()+ return await self._process_singly(batches, lock_conn, spent_attempt=True)++ await self._stop_heartbeat(heartbeat_task)+ heartbeat_task = None++ for batch in batches:+ await self._adapter.after_batch_processed(status_conn, batch=batch)++ duration = time.monotonic() - start+ self._metrics.batch_processing_duration_seconds.observe(duration)++ await self._verify_ownership(lock_conn, head)+ for batch in batches:+ await self._adapter.update_status(+ status_conn,+ batch_id=batch.id,+ job_state=self._adapter.succeeded_state,+ attempt=attempts[batch.id],+ batch_created_at=batch.created_at,+ )+ self._metrics.batches_processed_total.labels(status="success").inc()+ self._metrics.coalesced_sets_total.labels(outcome="success").inc()+ logger.info(+ self._event("batch_set_processed_ok"),+ run_uuid=head.run_uuid,+ batch_indexes=[batch.batch_index for batch in batches],+ is_final_batch=batches[-1].is_final_batch,+ duration_seconds=round(duration, 3),+ )+ return True+ finally:+ await self._stop_heartbeat(heartbeat_task)++ async def _process_singly(+ self, batches: list[PendingBatch], lock_conn: psycopg.AsyncConnection[Any] | None, *, spent_attempt: bool+ ) -> bool:+ """Load the constituents of a set one by one, stopping at the first that does not succeed."""+ for batch in batches:+ if spent_attempt:+ # The set's attempt wrote executing rows and may have committed, so each constituent+ # is now a redelivery: its status rows advance and its idempotency check scans history.+ batch = replace(batch, latest_attempt=batch.latest_attempt + 1)+ if not await self._process_single(batch, lock_conn=lock_conn):+ return False+ return True++ @staticmethod+ async def _stop_heartbeat(heartbeat_task: asyncio.Task[None] | None) -> None:+ if heartbeat_task is None:+ return+ heartbeat_task.cancel()+ try:+ await heartbeat_task+ except asyncio.CancelledError:+ passasync def _process_single_inner(self,@@ -1628,6 +1794,7 @@ class BatchConsumer:ProcessBatchFn = Callable[[PendingBatch], Coroutine[Any, Any, None]]+ProcessBatchesFn = Callable[[list[PendingBatch]], Coroutine[Any, Any, None]]def _group_by_key(batches: list[PendingBatch]) -> dict[tuple[int, str], list[PendingBatch]]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.pyindex eb11dff21a41..bc0035a5f508 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/lanes.py@@ -248,9 +248,7 @@ class LanedPipelineV3(PipelineV3[ResumableData]):writer.row_count += lane_table.num_rowsbatch_result = await asyncio.to_thread(writer.s3_batch_writer.write_batch, lane_table, batch_index)writer.batch_results.append(batch_result)- writer.pg_producer.send_batch_notification(- batch_result, is_final_batch=False, cumulative_row_count=writer.row_count- )+ writer.pg_producer.hold_batch(batch_result, cumulative_row_count=writer.row_count)# One read of a change stream is one sync however many tables it keeps.if lane.billable:billable_rows += lane_table.num_rows@@ -272,20 +270,22 @@ class LanedPipelineV3(PipelineV3[ResumableData]):continuelane_schema_path = await asyncio.to_thread(writer.s3_batch_writer.write_schema)schema_path = schema_path or lane_schema_path- writer.pg_producer.send_batch_notification(+ writer.pg_producer.send_final_batch(writer.batch_results[-1],- is_final_batch=True,total_batches=len(writer.batch_results),total_rows=writer.row_count,data_folder=writer.s3_batch_writer.get_data_folder(),schema_path=lane_schema_path,- cumulative_row_count=writer.row_count,)if writer.job is not None:self._final_sent_job_ids.add(str(writer.job.id))await self._record_companion_rows(writer)return schema_path+ def _release_held_batches(self) -> None:+ for writer in self._lane_writers:+ writer.pg_producer.release_held_batch()+async def _record_companion_rows(self, writer: _LaneWriter) -> None:"""Count what a companion wrote onto its own job, as the workflow does for the first."""from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.pyindex f6f5bb1cb199..86a5e29a4b53 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -1,12 +1,12 @@import uuidimport socket+import dataclassesfrom collections.abc import Callablefrom typing import Any, Literalfrom django.conf import settingsfrom django.db import close_old_connections, transaction-import s3fsimport pyarrow as paimport deltalake as deltalakeimport structlog@@ -62,6 +62,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinevalidate_schema_and_update_table,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (+ CoalescingDeclined,OwnershipLostError,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.idempotency import (@@ -392,18 +393,16 @@ async def _handle_partial_data_loading(def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessage) -> str | None:"""Run post-load operations for a final batch whose data was already written to Delta Lake.- The batch data (S3 read, partitioning, Delta Lake write) was already handled when- the batch was first processed with is_final_batch=False. We only need to run- post-load operations (compaction, S3 queryable folder prep, schema validation).+ Two deliveries land here: a redelivered final row whose earlier attempt committed the write+ but failed before post-load finished, and the final-only marker row an older producer inserts+ as a copy of the run's last data batch. Either way the data is in the table; only the post-load+ operations (compaction, S3 queryable folder prep, schema validation) are left.All async operations are run within a single async_to_sync call to avoidevent loop lifecycle issues with aiohttp/s3fs clients.Returns the prepared queryable_folder, or None if post-load couldn't run."""- # Clear cached S3FileSystem instances to avoid reusing sessions bound to a- # previously closed event loop (async_to_sync creates/destroys loops).- s3fs.S3FileSystem.clear_instance_cache()async def _run() -> str | None:job = await ExternalDataJob.objects.prefetch_related("schema", "schema__source", "schema__table").aget(@@ -788,6 +787,57 @@ def process_message(_process_message_reported(message, export_signal, progress_callback, verify_ownership, attempt)+def combine_export_signals(signals: list[ExportSignalMessage]) -> ExportSignalMessage:+ """The message one write of several consecutive batches stands for.++ It starts where the first batch starts, so batch 0 keeps its overwrite and its partial-loading+ semantics, and it ends how the last batch ends, so a final batch in the set completes the run.+ """+ head, tail = signals[0], signals[-1]+ return dataclasses.replace(+ head,+ row_count=sum(signal.row_count for signal in signals),+ byte_size=sum(signal.byte_size for signal in signals),+ is_final_batch=tail.is_final_batch,+ total_batches=tail.total_batches,+ total_rows=tail.total_rows,+ data_folder=tail.data_folder or head.data_folder,+ schema_path=tail.schema_path or head.schema_path,+ cumulative_row_count=tail.cumulative_row_count,+ )+++def process_messages(+ messages: list[Any],+ progress_callback: Callable[[], None] | None = None,+ verify_ownership: Callable[[], None] | None = None,+ attempt: int = 1,+) -> None:+ """Load consecutive batches of one run into Delta Lake as one write.++ Raises ``CoalescingDeclined`` before any side effect when the set cannot be loaded as one+ (a constituent already landed, or the batches' schemas do not concatenate); the engine then+ loads the constituents one by one.+ """+ signals = [ExportSignalMessage.from_dict(message) for message in messages]+ if len({signal.run_uuid for signal in signals}) != 1:+ raise CoalescingDeclined("batches belong to different runs")+ if any(later.batch_index != earlier.batch_index + 1 for earlier, later in zip(signals, signals[1:])):+ raise CoalescingDeclined("batch indexes are not consecutive")+ combined = combine_export_signals(signals)++ with workload_reporting(+ team_id=combined.team_id,+ schema_id=str(combined.schema_id),+ run_id=f"{combined.job_id}:load",+ host=socket.gethostname(),+ initial_phase="load",+ ):+ _process_message_reported(+ messages[0], combined, progress_callback, verify_ownership, attempt, constituents=signals+ )++def _process_external_destinations_only(export_signal: "ExportSignalMessage",verify_ownership: Callable[[], None] | None,@@ -814,20 +864,37 @@ def _process_external_destinations_only(_mark_job_completed(export_signal)+def _read_constituents(constituents: list[ExportSignalMessage]) -> pa.Table:+ """Read every constituent's parquet file and concatenate them in batch order.++ Batches of one run were converged onto one accumulated schema when they were staged, so they+ normally concatenate as they are; a later batch can still carry a column an earlier one lacked,+ which permissive promotion fills with nulls. Anything that still does not fit declines the set,+ since nothing has been written yet.+ """+ tables = [read_parquet(signal.s3_path) for signal in constituents]+ try:+ return pa.concat_tables(tables, promote_options="permissive")+ except (pa.ArrowInvalid, pa.ArrowTypeError, pa.ArrowNotImplementedError) as e:+ raise CoalescingDeclined(f"batch schemas do not concatenate: {e}") from e++def _process_message_reported(message: Any,export_signal: "ExportSignalMessage",progress_callback: Callable[[], None] | None,verify_ownership: Callable[[], None] | None,attempt: int = 1,+ constituents: list[ExportSignalMessage] | None = None,) -> None:+ # The batch indexes this write stands for: one for an ordinary batch, every member for a set.+ batch_indexes = (+ [signal.batch_index for signal in constituents] if constituents is not None else [export_signal.batch_index]+ )+# Reconnect stale app-DB connections up front so the ORM queries below don't burn all batch attempts.close_old_connections()- # Clear cached S3FileSystem instances to avoid reusing sessions bound to a- # previously closed event loop (async_to_sync creates/destroys loops).- s3fs.S3FileSystem.clear_instance_cache()-# Imported here, not at module scope: `load/__init__` imports this module, and delivery# imports `load.idempotency`, so a module-level import closes the cycle.from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.delivery import ( # noqa: PLC0415@@ -863,14 +930,29 @@ def _process_message_reported(_process_external_destinations_only(export_signal, verify_ownership)return- already_processed = is_batch_already_processed(- export_signal.team_id,- export_signal.schema_id,- export_signal.run_uuid,- export_signal.batch_index,- delta_table_ref=delta_table_ref,- is_first_attempt=attempt <= 1,- )+ if constituents is not None:+ # A set is all-or-nothing: a member that already landed means the others must be checked+ # and written one at a time, which the single-batch path knows how to do.+ for index in batch_indexes:+ if is_batch_already_processed(+ export_signal.team_id,+ export_signal.schema_id,+ export_signal.run_uuid,+ index,+ delta_table_ref=delta_table_ref,+ is_first_attempt=attempt <= 1,+ ):+ raise CoalescingDeclined(f"batch {index} was already processed")+ already_processed = False+ else:+ already_processed = is_batch_already_processed(+ export_signal.team_id,+ export_signal.schema_id,+ export_signal.run_uuid,+ export_signal.batch_index,+ delta_table_ref=delta_table_ref,+ is_first_attempt=attempt <= 1,+ )# The warehouse having this batch says nothing about the other destinations, so# delivery runs on every path and decides for itself what is left to do. Gating it on@@ -923,7 +1005,10 @@ def _process_message_reported()with PARQUET_READ_DURATION_SECONDS.time():- pa_table = read_parquet(export_signal.s3_path)+ if constituents is not None:+ pa_table = _read_constituents(constituents)+ else:+ pa_table = read_parquet(export_signal.s3_path)logger.debug("parquet_file_read",@@ -950,13 +1035,15 @@ def _process_message_reported(primary_keys = export_signal.primary_keyscdc_write_mode = export_signal.cdc_write_mode- # Tag every delta commit with (run_uuid, batch_index) so that a Kafka- # redelivery after a writer crash can detect "already committed" even when- # the Redis dedup flag is missing. See `is_batch_already_processed`.+ # Tag every delta commit with (run_uuid, batch_index) so that a redelivery after a writer+ # crash can detect "already committed" even when the Redis dedup flag is missing. A set+ # names every member, so each one's redelivery finds the commit. See `is_batch_already_processed`.commit_metadata = {"run_uuid": export_signal.run_uuid,"batch_index": str(export_signal.batch_index),}+ if constituents is not None:+ commit_metadata["batch_indexes"] = ",".join(str(index) for index in batch_indexes)resolution_enabled = cdc_write_mode is not None@@ -1046,6 +1133,12 @@ def _process_message_reported(DELTA_ROWS_WRITTEN_TOTAL.labels(team_id=team_id_str, schema_id=schema_id_str).inc(pa_table.num_rows)+ # Marked as soon as the commit lands, before post-load: the final row of a run carries its own+ # data now, so a post-load failure must send the retry down the post-load-only path rather+ # than through the write again.+ for index in batch_indexes:+ mark_batch_as_processed(export_signal.team_id, export_signal.schema_id, export_signal.run_uuid, index)+internal_schema = HogQLSchema()# Build from the Delta table schema first to cover all columns from# all batches, then overlay the current batch for JSON detection.@@ -1117,11 +1210,6 @@ def _process_message_reported(logger.debug("post_load_operations_complete")- mark_batch_as_processed(- export_signal.team_id, export_signal.schema_id, export_signal.run_uuid, export_signal.batch_index- )-- if export_signal.is_final_batch:posthoganalytics.capture(distinct_id=get_machine_id(),event="warehouse_v3_load_completed",diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.pyindex 4d000bc3185a..a1e2db52aa10 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py@@ -17,6 +17,9 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher importTOAST_OMITTED_COLUMN,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (+ CoalescingDeclined,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (_apply_partitioning,_enrich_cdc_rows,@@ -28,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_run_post_load_for_already_processed_batch,_trigger_post_import_workflow,process_message,+ process_messages,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.test_mocks import mock_delta_table@@ -263,12 +267,10 @@ class TestProcessMessageOwnershipGate:@patch(f"{_PROCESSOR}.Scd2DeltaWriter")@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")- @patch(f"{_PROCESSOR}.s3fs")@patch(f"{_PROCESSOR}.close_old_connections")def test_lost_ownership_blocks_delta_write(self,_close: MagicMock,- _s3fs: MagicMock,mock_job_model: MagicMock,mock_helper_cls: MagicMock,mock_scd2_cls: MagicMock,@@ -296,12 +298,10 @@ class TestProcessMessageOwnershipGate:@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")- @patch(f"{_PROCESSOR}.s3fs")@patch(f"{_PROCESSOR}.close_old_connections")def test_lost_ownership_blocks_final_batch_completion(self,_close: MagicMock,- _s3fs: MagicMock,mock_job_model: MagicMock,_helper_cls: MagicMock,_already: MagicMock,@@ -326,12 +326,10 @@ class TestProcessMessageOwnershipGate:@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")- @patch(f"{_PROCESSOR}.s3fs")@patch(f"{_PROCESSOR}.close_old_connections")def test_ownership_lost_during_post_load_blocks_completion(self,_close: MagicMock,- _s3fs: MagicMock,mock_job_model: MagicMock,_helper_cls: MagicMock,_already: MagicMock,@@ -361,12 +359,10 @@ class TestProcessMessageOwnershipGate:@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")- @patch(f"{_PROCESSOR}.s3fs")@patch(f"{_PROCESSOR}.close_old_connections")def test_ownership_loss_is_not_counted_as_load_failure(self,_close: MagicMock,- _s3fs: MagicMock,mock_job_model: MagicMock,_helper_cls: MagicMock,_already: MagicMock,@@ -501,12 +497,10 @@ class TestRedeliveredFinalBatchPostLoad:@patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")- @patch(f"{_PROCESSOR}.s3fs")def test_forwards_the_batch_write_mode(self,_case: str,cdc_write_mode: str | None,- _s3fs: MagicMock,mock_job_model: MagicMock,mock_helper_cls: MagicMock,_read: MagicMock,@@ -529,6 +523,178 @@ class TestRedeliveredFinalBatchPostLoad:assert mock_post_load.await_args.kwargs["cdc_write_mode"] == cdc_write_mode+class TestFinalDataBatch:+ # The run's last data row is its own final marker, so one delivery writes the batch and runs+ # post-load. The write must be marked as soon as it commits: a post-load failure otherwise+ # leaves the retry with no fast way to know the merge already happened.++ @patch(f"{_PROCESSOR}.posthoganalytics")+ @patch(f"{_PROCESSOR}.mark_batch_as_processed")+ @patch(f"{_PROCESSOR}._mark_job_completed")+ @patch(+ f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, side_effect=RuntimeError("compaction died")+ )+ @patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)+ @patch(f"{_PROCESSOR}.DeltaWriter")+ @patch(f"{_PROCESSOR}.DeltaTableRef")+ @patch(f"{_PROCESSOR}.ExternalDataJob")+ def test_a_post_load_failure_leaves_the_write_marked_processed(+ self,+ mock_job_model: MagicMock,+ mock_helper_cls: MagicMock,+ mock_writer_cls: MagicMock,+ _already: MagicMock,+ _read: MagicMock,+ _post_load: AsyncMock,+ mock_mark_completed: MagicMock,+ mock_mark_processed: MagicMock,+ _analytics: MagicMock,+ ) -> None:+ delta_table = MagicMock()+ delta_table.schema.return_value = pa.schema([pa.field("id", pa.int64())])+ delta_table.file_uris.return_value = []+ mock_helper_cls.return_value.get_delta_table = AsyncMock(return_value=None)+ mock_writer_cls.return_value.write = AsyncMock(return_value=delta_table)+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()++ with pytest.raises(RuntimeError, match="compaction died"):+ process_message(_message(is_final_batch=True, batch_index=4, run_uuid="run-9"))++ mock_writer_cls.return_value.write.assert_awaited_once()+ mock_mark_processed.assert_called_once_with(1, "schema-1", "run-9", 4)+ mock_mark_completed.assert_not_called()+++def _set_messages(count: int, *, sync_type: str = "full_refresh", final: bool = True) -> list[dict[str, Any]]:+ return [+ _message(+ batch_index=index,+ s3_path=f"s3://bucket/{index}.parquet",+ sync_type=sync_type,+ is_final_batch=final and index == count - 1,+ total_batches=count if final and index == count - 1 else None,+ total_rows=6 if final and index == count - 1 else None,+ row_count=index + 1,+ )+ for index in range(count)+ ]+++class TestProcessMessages:+ """Several consecutive batches of one run loaded as one write. The write must carry every member,+ or a redelivery of one of them merges its rows a second time."""++ @patch(f"{_PROCESSOR}.posthoganalytics")+ @patch(f"{_PROCESSOR}.mark_batch_as_processed")+ @patch(f"{_PROCESSOR}._trigger_post_import_workflow")+ @patch(f"{_PROCESSOR}._trigger_ducklake_register_data_imports")+ @patch(f"{_PROCESSOR}._mark_job_completed")+ @patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value="folder")+ @patch(f"{_PROCESSOR}.read_parquet")+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)+ @patch(f"{_PROCESSOR}.DeltaWriter")+ @patch(f"{_PROCESSOR}.DeltaTableRef")+ @patch(f"{_PROCESSOR}.ExternalDataJob")+ def test_a_set_starting_at_batch_zero_overwrites_with_the_union_and_finishes_the_run(+ self,+ mock_job_model: MagicMock,+ mock_helper_cls: MagicMock,+ mock_writer_cls: MagicMock,+ _already: MagicMock,+ mock_read: MagicMock,+ mock_post_load: AsyncMock,+ mock_mark_completed: MagicMock,+ _ducklake: MagicMock,+ mock_trigger: MagicMock,+ mock_mark_processed: MagicMock,+ _analytics: MagicMock,+ ) -> None:+ mock_read.side_effect = lambda path: pa.table({"id": list(range(int(path[-9]) + 1))})+ delta_table = MagicMock()+ delta_table.schema.return_value = pa.schema([pa.field("id", pa.int64())])+ delta_table.file_uris.return_value = []+ mock_helper_cls.return_value.get_delta_table = AsyncMock(return_value=None)+ mock_writer_cls.return_value.write = AsyncMock(return_value=delta_table)+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()++ process_messages(_set_messages(3))++ write = mock_writer_cls.return_value.write+ write.assert_awaited_once()+ assert write.await_args.kwargs["data"].num_rows == 6+ assert write.await_args.kwargs["should_overwrite_table"] is True+ assert write.await_args.kwargs["commit_metadata"] == {+ "run_uuid": "run-1",+ "batch_index": "0",+ "batch_indexes": "0,1,2",+ }+ assert [call.args[3] for call in mock_mark_processed.call_args_list] == [0, 1, 2]+ mock_post_load.assert_awaited_once()+ assert mock_post_load.await_args is not None+ assert mock_post_load.await_args.kwargs["row_count"] == 6+ mock_mark_completed.assert_called_once()+ mock_trigger.assert_called_once()++ @patch(f"{_PROCESSOR}.posthoganalytics")+ @patch(f"{_PROCESSOR}.read_parquet")+ @patch(f"{_PROCESSOR}.is_batch_already_processed", side_effect=[False, True, False])+ @patch(f"{_PROCESSOR}.DeltaWriter")+ @patch(f"{_PROCESSOR}.DeltaTableRef")+ @patch(f"{_PROCESSOR}.ExternalDataJob")+ def test_a_member_that_already_landed_declines_the_set_before_any_read_or_write(+ self,+ mock_job_model: MagicMock,+ _helper_cls: MagicMock,+ mock_writer_cls: MagicMock,+ _already: MagicMock,+ mock_read: MagicMock,+ _analytics: MagicMock,+ ) -> None:+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()++ with pytest.raises(CoalescingDeclined):+ process_messages(_set_messages(3))++ mock_read.assert_not_called()+ mock_writer_cls.return_value.write.assert_not_called()++ @patch(f"{_PROCESSOR}.posthoganalytics")+ @patch(f"{_PROCESSOR}.read_parquet")+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)+ @patch(f"{_PROCESSOR}.DeltaWriter")+ @patch(f"{_PROCESSOR}.DeltaTableRef")+ @patch(f"{_PROCESSOR}.ExternalDataJob")+ def test_members_whose_schemas_do_not_concatenate_decline_the_set(+ self,+ mock_job_model: MagicMock,+ _helper_cls: MagicMock,+ mock_writer_cls: MagicMock,+ _already: MagicMock,+ mock_read: MagicMock,+ _analytics: MagicMock,+ ) -> None:+ mock_read.side_effect = [pa.table({"id": [1]}), pa.table({"id": ["a"]})]+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()++ with pytest.raises(CoalescingDeclined):+ process_messages(_set_messages(2))++ mock_writer_cls.return_value.write.assert_not_called()++ @parameterized.expand(+ [+ ("different_runs", [{"batch_index": 0}, {"batch_index": 1, "run_uuid": "run-2"}]),+ ("gap_in_indexes", [{"batch_index": 0}, {"batch_index": 2}]),+ ]+ )+ def test_a_set_that_is_not_one_consecutive_run_is_declined(+ self, _case: str, overrides: list[dict[str, Any]]+ ) -> None:+ with pytest.raises(CoalescingDeclined):+ process_messages([_message(**o) for o in overrides])++class TestPostImportTrigger:"""The V3 hand-off to `data-import-post-import`: without it the load-dependentpost-import steps (signals, enrichment, statistics, table size, DuckLake copy)@@ -545,10 +711,8 @@ class TestPostImportTrigger:@patch(f"{_PROCESSOR}.DeltaWriter")@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")- @patch(f"{_PROCESSOR}.s3fs")def test_final_batch_triggers_post_import_once(self,- _s3fs: MagicMock,mock_job_model: MagicMock,mock_helper_cls: MagicMock,mock_writer_cls: MagicMock,@@ -581,10 +745,8 @@ class TestPostImportTrigger:@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=True)@patch(f"{_PROCESSOR}.DeltaTableRef")@patch(f"{_PROCESSOR}.ExternalDataJob")- @patch(f"{_PROCESSOR}.s3fs")def test_redelivered_final_batch_triggers_post_import(self,- _s3fs: MagicMock,mock_job_model: MagicMock,_helper_cls: MagicMock,_already: MagicMock,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.pyindex 37427fa2377e..8bd80014a043 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py@@ -301,7 +301,7 @@ class PipelineV3(Generic[ResumableData]):batch_result = await asyncio.to_thread(self._s3_batch_writer.write_batch, pa_table, batch_index)self._batch_results.append(batch_result)- self._pg_producer.send_batch_notification(batch_result, is_final_batch=False, cumulative_row_count=row_count)+ self._pg_producer.hold_batch(batch_result, cumulative_row_count=row_count)return pa_table.num_rowsdef _total_batches(self) -> int:@@ -314,19 +314,19 @@ class PipelineV3(Generic[ResumableData]):async def _send_final_batches(self, total_batches: int, row_count: int) -> str | None:schema_path = await asyncio.to_thread(self._s3_batch_writer.write_schema)- final_batch = self._batch_results[-1]-- self._pg_producer.send_batch_notification(- final_batch,- is_final_batch=True,+ self._pg_producer.send_final_batch(+ self._batch_results[-1],total_batches=total_batches,total_rows=row_count,data_folder=self._s3_batch_writer.get_data_folder(),schema_path=schema_path,- cumulative_row_count=row_count,)return schema_path+ def _release_held_batches(self) -> None:+ """Put every held queue row into the queue now, as a non-final row."""+ self._pg_producer.release_held_batch()+def _mark_first_ever_sync(self) -> None:self._pg_producer.is_first_ever_sync = True@@ -343,8 +343,14 @@ class PipelineV3(Generic[ResumableData]):self._pg_producer.close()async def _commit_resume_state(self) -> None:- if self._resumable_source_manager is not None:- await asyncio.to_thread(self._resumable_source_manager.commit)+ if self._resumable_source_manager is None:+ return+ if self._resumable_source_manager.has_staged_state():+ # The cursor about to commit says every row yielded before it is loadable. A batch whose+ # queue row is still held is not, so a crash between the commit and the next insert+ # would resume past rows the loader never hears about.+ self._release_held_batches()+ await asyncio.to_thread(self._resumable_source_manager.commit)async def run(self) -> PipelineResult:pa_memory_pool = pa.default_memory_pool()@@ -536,6 +542,12 @@ class PipelineV3(Generic[ResumableData]):except Exception:status = "error"self._logger.exception("V3 Pipeline: Extraction failed")+ # Same queue state a failed run has always left: every staged batch has a row, so an+ # incremental run's loadable tail can still drain (see `_drainable_after_failure`).+ try:+ self._release_held_batches()+ except Exception:+ self._logger.exception("V3 Pipeline: Failed to enqueue the held batch after the extraction error")raisefinally:duration = time.perf_counter() - start_timediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.mdindex b817dc6ca9dd..85386007c48d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md@@ -48,7 +48,10 @@ All SQL lives in `jobs_db.py`; the polling/retry/recovery engine is `../batch_coIt is single-flighted fleet-wide through a sentinel lease row (`try_acquire_reconcile_sweep_slot`, team_id 0 / `__reconcile-sweep__`, 240s slot TTL): the sweeps reconcile global state, so N pods running them concurrently is pure duplicated load, exactly when the queue DB can least afford it.- **Stranded-run sweep** (same cadence and connection, `get_stale_stranded_runs`): runs the loader abandoned, meaning non-terminal batches, no live lease, and no loader progress for 6 hours.These have no `failed` batch for the reconcile sweep to key on (the extraction died before a final batch), so without this pass they would strand until the retention prune.-- **Sync producer** (`producer.py`): runs inside Temporal activities, plain `psycopg.Connection` with autocommit. Each `send_batch_notification` is a single INSERT.+- **Sync producer** (`producer.py`): runs inside Temporal activities, plain `psycopg.Connection` with autocommit. Each queue row is a single INSERT.+ The v3 pipeline holds each batch's row back by one (`hold_batch`): staging batch N inserts the row for batch N-1, and the end of the run inserts the held row with `is_final_batch = true`, so the run's last data row is its own final marker and the loader reads every parquet file once.+ A resumable source releases the held row before it commits a cursor (`release_held_batch`), because the cursor promises that every row before it is loadable; when that leaves nothing held at the end, `send_final_batch` inserts the last batch a second time as a final-only marker, which the loader still accepts (`_run_post_load_for_already_processed_batch`).+ The CDC extraction activities know at send time whether a batch is final and keep using `send_batch_notification` directly.- **New DB**: we created a new DB to store these tables.- **Daily range partitioning** on `created_at`: both tables use `PARTITION BY RANGE (created_at)` with daily partitions and a DEFAULT partition catching rows that miss one.A Temporal scheduled workflow (`warehouse-sources-queue-partition-management`, daily at 8 AM UTC) creates the next 7 days of partitions, drops partitions older than 7 days, deletes DEFAULT-partition rows older than 7 days, and prunes the matching S3 extraction prefixes on the same retention.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex 99ca27325f84..5d6907ce1218 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -90,6 +90,7 @@ ConsumerConfig = BatchConsumerConfigVerifyOwnership = Callable[[], None]# Unlike the engine's ProcessBatchFn, the Delta sink also receives the per-batch ownership check.DeltaProcessBatchFn = Callable[[PendingBatch, VerifyOwnership | None], Coroutine[Any, Any, None]]+DeltaProcessBatchesFn = Callable[[list[PendingBatch], VerifyOwnership | None], Coroutine[Any, Any, None]]# Ceiling for the queue-freshness probe, deliberately far below the sweep# timeout so a degraded probe can't starve the reconcile sweep it rides on.@@ -179,6 +180,43 @@ JOB_STATUS_CACHE_TTL_SECONDS = 30JOB_STATUS_CACHE_MAX_ENTRIES = 1000+# Bounds on a set of consecutive batches loaded as one Delta commit. A batch is at most one+# extraction chunk (500k rows, 200 MiB of Arrow), so the row cap keeps a set to what one large+# batch already costs, and the byte cap (parquet on disk, several times smaller than the Arrow it+# decodes to) keeps many small batches from adding up past it.+COALESCE_MAX_BATCHES = 8+COALESCE_MAX_ROWS = 500_000+COALESCE_MAX_BYTES = 64 * 1024 * 1024+# CDC batches resolve positions against the table between writes, and a batch bound for external+# destinations is delivered per batch, so neither is folded into a set.+COALESCABLE_SYNC_TYPES: frozenset[str] = frozenset({"incremental", "append", "full_refresh"})+++def _coalescable(batch: PendingBatch) -> bool:+ return (+ batch.sync_type in COALESCABLE_SYNC_TYPES+ # A redelivery may sit on a half-finished write; its idempotency check runs per batch.+ and batch.latest_attempt == 0+ and not batch.destination_ids+ and batch.metadata.get("cdc_write_mode") is None+ )+++def _extends_coalesced_set(current: list[PendingBatch], batch: PendingBatch) -> bool:+ head = current[-1]+ if not (_coalescable(head) and _coalescable(batch)):+ return False+ if batch.run_uuid != head.run_uuid or batch.job_id != head.job_id:+ return False+ if batch.batch_index != head.batch_index + 1:+ return False+ if len(current) >= COALESCE_MAX_BATCHES:+ return False+ rows = sum(member.row_count for member in current) + batch.row_count+ size = sum(member.byte_size for member in current) + batch.byte_size+ return rows <= COALESCE_MAX_ROWS and size <= COALESCE_MAX_BYTES++def _is_transient_queue_connection_drop(err: Exception, conn: psycopg.AsyncConnection[Any]) -> bool:"""Whether `err` is a queue-db connection dying mid-query rather than a real bug.@@ -915,6 +953,20 @@ class DeltaBatchConsumerAdapter:) -> None:return None+ def coalesce_group(self, batches: list[PendingBatch]) -> list[list[PendingBatch]]:+ sets: list[list[PendingBatch]] = []+ current: list[PendingBatch] = []+ for batch in batches:+ if current and _extends_coalesced_set(current, batch):+ current.append(batch)+ continue+ if current:+ sets.append(current)+ current = [batch]+ if current:+ sets.append(current)+ return sets+class BatchConsumer(SharedBatchConsumer):def __init__(@@ -924,10 +976,16 @@ class BatchConsumer(SharedBatchConsumer):health_reporter: Callable[[], None] | None = None,claim_sync_types: list[str] | None = None,claim_exclude_sync_types: list[str] | None = None,+ process_batches: DeltaProcessBatchesFn | None = None,) -> None:async def process_with_ownership_check(batch: PendingBatch) -> None:await process_batch(batch, self._make_verify_ownership(batch))+ async def process_set_with_ownership_check(batches: list[PendingBatch]) -> None:+ assert process_batches is not None+ # One lease covers the whole set: every constituent shares the group.+ await process_batches(batches, self._make_verify_ownership(batches[0]))+super().__init__(config=config,process_batch=process_with_ownership_check,@@ -936,6 +994,7 @@ class BatchConsumer(SharedBatchConsumer):claim_exclude_sync_types=claim_exclude_sync_types,),health_reporter=health_reporter,+ process_batches=process_set_with_ownership_check if process_batches is not None else None,)def _make_verify_ownership(self, batch: PendingBatch) -> Callable[[], None]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.pyindex efd16bd8b4e5..4853a8341fb8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py@@ -17,6 +17,9 @@ from __future__ import annotationsimport jsonimport time+import threading+from collections.abc import Iterator+from contextlib import contextmanager, suppressfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import Any@@ -803,6 +806,109 @@ class QueueDepth:serialized_batches: int+# Idle sync connections kept per queue DB for the worker-thread lease checks. Sized to the loader's+# group concurrency: every in-flight batch checks its lease a few times, and each check used to dial+# a fresh connection.+SYNC_POOL_MAX_IDLE = 16+++class _SyncConnectionPool:+ """A small pool of autocommit connections for callers that run outside the event loop.++ Connections are handed out LIFO so the warm ones stay in use and are checked for liveness on+ the way out; one the server dropped while idle is closed instead of reused. Callers that hit an+ error mid-query discard the connection through `discard`, since the pool cannot tell a broken+ session from a healthy one until it fails.+ """++ def __init__(self, database_url: str, *, connect_timeout_seconds: int, max_idle: int = SYNC_POOL_MAX_IDLE) -> None:+ self._database_url = database_url+ self._connect_timeout_seconds = connect_timeout_seconds+ self._max_idle = max_idle+ self._lock = threading.Lock()+ self._idle: list[psycopg.Connection[Any]] = []++ def _checkout(self) -> psycopg.Connection[Any]:+ while True:+ with self._lock:+ conn = self._idle.pop() if self._idle else None+ if conn is None:+ return psycopg.connect(+ self._database_url, autocommit=True, connect_timeout=self._connect_timeout_seconds+ )+ if not conn.closed and not conn.broken:+ return conn+ self._close_quietly(conn)++ def _checkin(self, conn: psycopg.Connection[Any]) -> None:+ if conn.closed or conn.broken:+ self._close_quietly(conn)+ return+ with self._lock:+ if len(self._idle) < self._max_idle:+ self._idle.append(conn)+ return+ self._close_quietly(conn)++ def discard(self, conn: psycopg.Connection[Any]) -> None:+ """Take `conn` out of circulation: the caller saw it fail and nothing should reuse it."""+ with self._lock:+ if conn in self._idle:+ self._idle.remove(conn)+ self._close_quietly(conn)++ @contextmanager+ def connection(self) -> Iterator[psycopg.Connection[Any]]:+ conn = self._checkout()+ try:+ yield conn+ finally:+ if not conn.closed:+ self._checkin(conn)++ @property+ def idle_count(self) -> int:+ with self._lock:+ return len(self._idle)++ @staticmethod+ def _close_quietly(conn: psycopg.Connection[Any]) -> None:+ with suppress(Exception):+ conn.close()+++_SYNC_POOLS: dict[tuple[str, int], _SyncConnectionPool] = {}+_SYNC_POOLS_LOCK = threading.Lock()+++def _sync_connection_pool(database_url: str, connect_timeout_seconds: int) -> _SyncConnectionPool:+ key = (database_url, connect_timeout_seconds)+ with _SYNC_POOLS_LOCK:+ pool = _SYNC_POOLS.get(key)+ if pool is None:+ pool = _SyncConnectionPool(database_url, connect_timeout_seconds=connect_timeout_seconds)+ _SYNC_POOLS[key] = pool+ return pool+++def _lease_is_held(conn: psycopg.Connection[Any], *, team_id: int, schema_id: str, owner_token: str) -> bool:+ with conn.cursor() as cur:+ cur.execute(+ f"""+ SELECT EXISTS (+ SELECT 1 FROM {LEASE_TABLE}+ WHERE team_id = %(team_id)s+ AND schema_id = %(schema_id)s+ AND owner_token = %(owner)s+ AND expires_at > now()+ )+ """,+ {"team_id": team_id, "schema_id": schema_id, "owner": owner_token},+ )+ row = cur.fetchone()+ return bool(row and row[0])++class BatchQueue:"""Async interface to the Postgres batch queue tables. Each method runs@@ -1228,24 +1334,23 @@ class BatchQueue:owner_token: str,connect_timeout_seconds: int = 10,) -> bool:- """Sync counterpart of verify_advisory_lock: the Delta write runs in a worker thread- that can't share the group's async connection, so use a short-lived sync one."""- with psycopg.connect(database_url, autocommit=True, connect_timeout=connect_timeout_seconds) as conn:- with conn.cursor() as cur:- cur.execute(- f"""- SELECT EXISTS (- SELECT 1 FROM {LEASE_TABLE}- WHERE team_id = %(team_id)s- AND schema_id = %(schema_id)s- AND owner_token = %(owner)s- AND expires_at > now()- )- """,- {"team_id": team_id, "schema_id": schema_id, "owner": owner_token},- )- row = cur.fetchone()- return bool(row and row[0])+ """Sync counterpart of verify_advisory_lock: the Delta write runs in a worker thread that+ can't share the group's async connection, so it borrows one from a small sync pool.++ A connection the queue DB dropped while idle (a pooler cull, a failover) surfaces as an+ OperationalError on first use; that connection is discarded and the query runs once more+ on a fresh one, so a stale pool entry cannot read as a lost lease.+ """+ pool = _sync_connection_pool(database_url, connect_timeout_seconds)+ for attempt in (1, 2):+ with pool.connection() as conn:+ try:+ return _lease_is_held(conn, team_id=team_id, schema_id=schema_id, owner_token=owner_token)+ except psycopg.OperationalError:+ pool.discard(conn)+ if attempt == 2:+ raise+ raise AssertionError("unreachable")@staticmethodasync def get_stale_executing(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.pyindex cb2bb74a8a39..49e373a5bd73 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py@@ -19,6 +19,7 @@ from asgiref.sync import sync_to_asyncfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (process_message,+ process_messages,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (PendingBatch,@@ -34,3 +35,12 @@ async def process_batch(batch: PendingBatch, verify_ownership: Callable[[], Noneawait sync_to_async(process_message, thread_sensitive=False)(batch.to_export_signal(), verify_ownership=verify_ownership, attempt=batch.latest_attempt + 1)+++async def process_batches(batches: list[PendingBatch], verify_ownership: Callable[[], None] | None = None) -> None:+ """Load consecutive batches of one run into Delta Lake as a single write."""+ await sync_to_async(process_messages, thread_sensitive=False)(+ [batch.to_export_signal() for batch in batches],+ verify_ownership=verify_ownership,+ attempt=max(batch.latest_attempt for batch in batches) + 1,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.pyindex f68a10f51a38..bab1653018a4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py@@ -263,8 +263,15 @@ class ConsumerMetrics:poll_failures_total: Counteractive_groups: Gaugerecovery_sweeps_total: Counter+ coalesced_sets_total: Counter+COALESCED_SETS_TOTAL = Counter(+ "warehouse_pg_consumer_coalesced_sets_total",+ "Sets of consecutive batches of one run loaded as a single write, by outcome",+ labelnames=["outcome"],+)+DELTA_CONSUMER_METRICS = ConsumerMetrics(batches_processed_total=BATCHES_PROCESSED_TOTAL,batch_processing_duration_seconds=BATCH_PROCESSING_DURATION_SECONDS,@@ -275,6 +282,7 @@ DELTA_CONSUMER_METRICS = ConsumerMetrics(poll_failures_total=POLL_FAILURES_TOTAL,active_groups=ACTIVE_GROUPS,recovery_sweeps_total=RECOVERY_SWEEPS_TOTAL,+ coalesced_sets_total=COALESCED_SETS_TOTAL,)_metrics_by_prefix: dict[str, ConsumerMetrics] = {}@@ -332,6 +340,11 @@ def make_consumer_metrics(prefix: str) -> ConsumerMetrics:"Total recovery sweeps executed",labelnames=["outcome"],),+ coalesced_sets_total=Counter(+ f"{p}_coalesced_sets_total",+ "Sets of consecutive batches of one run loaded as a single write, by outcome",+ labelnames=["outcome"],+ ),)_metrics_by_prefix[prefix] = metricsreturn metricsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.pyindex b6622cf43e1b..81b84453f1fd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py@@ -98,6 +98,9 @@ class PostgresProducer:self._conn = _connect_with_retry(database_url)self._batches_sent = 0+ # The most recent staged batch and its cumulative row count, kept out of the queue until the+ # next batch arrives or the run ends, so the run's last row can carry the final flag itself.+ self._held: tuple[BatchWriteResult, int] | None = None@propertydef sync_type(self) -> SyncTypeLiteral:@@ -111,6 +114,67 @@ class PostgresProducer:def is_first_ever_sync(self, value: bool) -> None:self._is_first_ever_sync = value+ @property+ def has_held_batch(self) -> bool:+ return self._held is not None++ def hold_batch(self, batch_result: BatchWriteResult, *, cumulative_row_count: int) -> None:+ """Stage a batch's queue row, inserting the previously held one as a non-final row.++ The parquet file is already durable when this is called; only the queue row waits. Holding+ one row back is what lets `send_final_batch` flag the run's last data row as final instead of+ inserting a second row for it, which the loader would have to process twice.++ Superseding runs on the staging of batch 0, not on its insert, so it keeps firing at the+ same point of the run it always has.+ """+ if batch_result.batch_index == 0 and not self._is_resume:+ self._supersede_other_runs()+ previous = self._held+ self._held = (batch_result, cumulative_row_count)+ if previous is not None:+ self._insert(previous[0], is_final_batch=False, cumulative_row_count=previous[1])++ def release_held_batch(self) -> bool:+ """Insert the held batch as a non-final row now. Returns whether a row was inserted.++ For a resumable source, whose cursor commit promises that every yielded row is loadable,+ the held row has to be in the queue before that commit lands.+ """+ held = self._held+ if held is None:+ return False+ self._held = None+ self._insert(held[0], is_final_batch=False, cumulative_row_count=held[1])+ return True++ def send_final_batch(+ self,+ last_batch: BatchWriteResult,+ *,+ total_batches: int,+ total_rows: int,+ data_folder: str,+ schema_path: str | None,+ ) -> None:+ """Mark the run complete: the held last batch becomes the final row.++ When nothing is held (a resumable source released it before a cursor commit), the last+ batch is inserted a second time as a final-only marker, which the loader still accepts.+ """+ held = self._held+ self._held = None+ final_batch = last_batch if held is None else held[0]+ self._insert(+ final_batch,+ is_final_batch=True,+ total_batches=total_batches,+ total_rows=total_rows,+ data_folder=data_folder,+ schema_path=schema_path,+ cumulative_row_count=total_rows,+ )+def send_batch_notification(self,batch_result: BatchWriteResult,@@ -121,7 +185,48 @@ class PostgresProducer:schema_path: Optional[str] = None,cumulative_row_count: int = 0,) -> None:- """Insert a batch row into the Postgres queue."""+ """Insert a batch row into the Postgres queue immediately."""+ if batch_result.batch_index == 0 and not self._is_resume:+ self._supersede_other_runs()+ self._insert(+ batch_result,+ is_final_batch=is_final_batch,+ total_batches=total_batches,+ total_rows=total_rows,+ data_folder=data_folder,+ schema_path=schema_path,+ cumulative_row_count=cumulative_row_count,+ )++ def _supersede_other_runs(self) -> None:+ # One-shot, at the start of a fresh (non-resume) run: stalled sibling runs of+ # this job go terminal so their batches can't double-load. Runs the loader is+ # still draining are spared (see supersede_other_runs); a spared run that+ # stalls later is recovered by the reconcile sweep's stranded-run pass.+ #+ # A full_refresh is the exception: this run's batch 0 overwrites the table, so+ # an older attempt's loaded rows are gone either way and sparing it only leaves+ # its batches clogging the serial per-(team, schema) gate.+ superseded = BatchQueue.supersede_other_runs(+ self._conn,+ job_id=self._job_id,+ current_run_uuid=self._run_uuid,+ spare_runs_with_progress=self._sync_type != "full_refresh",+ )+ if superseded > 0:+ self._logger.info("superseded_old_run_batches", count=superseded)++ def _insert(+ self,+ batch_result: BatchWriteResult,+ *,+ is_final_batch: bool,+ total_batches: Optional[int] = None,+ total_rows: Optional[int] = None,+ data_folder: Optional[str] = None,+ schema_path: Optional[str] = None,+ cumulative_row_count: int = 0,+ ) -> None:metadata: dict[str, Any] = {}if data_folder is not None:metadata["data_folder"] = data_folder@@ -151,24 +256,6 @@ class PostgresProducer:metadata["workflow_run_id"] = self._workflow_run_idmetadata["timestamp_ns"] = batch_result.timestamp_ns- # One-shot, at the start of a fresh (non-resume) run: stalled sibling runs of- # this job go terminal so their batches can't double-load. Runs the loader is- # still draining are spared (see supersede_other_runs); a spared run that- # stalls later is recovered by the reconcile sweep's stranded-run pass.- #- # A full_refresh is the exception: this run's batch 0 overwrites the table, so- # an older attempt's loaded rows are gone either way and sparing it only leaves- # its batches clogging the serial per-(team, schema) gate.- if batch_result.batch_index == 0 and not self._is_resume:- superseded = BatchQueue.supersede_other_runs(- self._conn,- job_id=self._job_id,- current_run_uuid=self._run_uuid,- spare_runs_with_progress=self._sync_type != "full_refresh",- )- if superseded > 0:- self._logger.info("superseded_old_run_batches", count=superseded)-self._conn.execute(f"""INSERT INTO {BATCH_TABLE} (diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 5e2cc4a8bdfb..16326e609f05 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -1,6 +1,6 @@import asynciofrom datetime import UTC, datetime-from typing import Any, cast+from typing import Any, NamedTuple, castimport pytestfrom unittest.mock import AsyncMock, patch@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (QUEUE_RETRY_MAX_ATTEMPTS,+ CoalescingDeclined,OwnershipLostError,_is_admin_shutdown_error,_is_connect_timeout_error,@@ -3686,3 +3687,181 @@ class TestIsRetryableError:)def test_pattern_classification(self, message: str, retryable: bool):assert DeltaBatchConsumerAdapter().is_retryable_error(Exception(message)) is retryable+++def _run_batches(count: int, *, run_uuid: str = "run-1", start: int = 0, **overrides: Any) -> list[PendingBatch]:+ return [+ _make_batch(+ id=f"00000000-0000-0000-0000-{run_uuid[-1]}{start + offset:011d}",+ run_uuid=run_uuid,+ batch_index=start + offset,+ sync_type="incremental",+ **overrides,+ )+ for offset in range(count)+ ]+++class TestCoalesceGroup:+ """Which consecutive batches the Delta sink may load as one write. A set that crosses a run, skips+ an index or grows past the caps would merge rows the writer must never see together."""++ def _sets(self, batches: list[PendingBatch]) -> list[list[int]]:+ return [[b.batch_index for b in s] for s in DeltaBatchConsumerAdapter().coalesce_group(batches)]++ def test_consecutive_batches_of_one_run_form_one_set(self):+ assert self._sets(_run_batches(3)) == [[0, 1, 2]]++ def test_a_gap_in_the_indexes_splits_the_set(self):+ batches = _run_batches(2) + _run_batches(1, start=3)+ assert self._sets(batches) == [[0, 1], [3]]++ def test_a_set_never_crosses_a_run(self):+ batches = _run_batches(2, run_uuid="run-1") + _run_batches(2, run_uuid="run-2")+ assert self._sets(batches) == [[0, 1], [0, 1]]++ def test_a_final_only_marker_row_stays_alone(self):+ # An older producer repeats the last batch's index as a final-only row; it is not a new batch.+ batches = _run_batches(2)+ marker = _make_batch(+ id="00000000-0000-0000-0000-999999999999",+ run_uuid="run-1",+ batch_index=1,+ is_final_batch=True,+ sync_type="incremental",+ )+ assert self._sets([*batches, marker]) == [[0, 1], [1]]++ @pytest.mark.parametrize(+ "overrides",+ [+ {"sync_type": "cdc"},+ {"metadata": {"cdc_write_mode": "scd2_append"}},+ {"destination_ids": ["dest-1"]},+ {"latest_attempt": 1},+ ],+ ids=["cdc", "scd2_companion", "external_destinations", "redelivery"],+ )+ def test_batches_the_sink_loads_one_at_a_time(self, overrides: dict[str, Any]):+ batches = [+ _make_batch(+ id=f"00000000-0000-0000-0000-{i:012d}",+ run_uuid="run-1",+ batch_index=i,+ **({"sync_type": "incremental"} | overrides),+ )+ for i in range(3)+ ]+ assert self._sets(batches) == [[0], [1], [2]]++ @pytest.mark.parametrize(+ "count,overrides,expected",+ [+ (3, {"row_count": 300_000, "byte_size": 1}, [[0], [1], [2]]),+ (3, {"row_count": 1, "byte_size": 40 * 1024 * 1024}, [[0], [1], [2]]),+ (9, {"row_count": 1, "byte_size": 1}, [list(range(8)), [8]]),+ ],+ ids=["rows", "bytes", "count"],+ )+ def test_sets_are_capped(self, count: int, overrides: dict[str, Any], expected: list[list[int]]):+ assert self._sets(_run_batches(count, **overrides)) == expected+++class _BatchStatus(NamedTuple):+ batch_id: str+ job_state: str+ attempt: int+++class TestProcessGroupCoalescing:+ _CONSUMER_QUEUE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue"++ def _consumer(self, process_batches: Any, process_batch: Any) -> BatchConsumer:+ config = ConsumerConfig(database_url="postgres://unused:unused@localhost/unused", max_attempts=3)+ consumer = BatchConsumer(config=config, process_batch=process_batch, process_batches=process_batches)+ consumer._poll_conn = _make_healthy_conn()+ consumer._recovery_conn = _make_healthy_conn()+ return consumer++ async def _run_group(self, consumer: BatchConsumer, batches: list[PendingBatch]) -> list[_BatchStatus]:+ statuses: list[_BatchStatus] = []++ async def record_status(conn, *, batch_id, job_state, attempt, **kwargs):+ statuses.append(_BatchStatus(batch_id, job_state, attempt))+ return True++ with (+ patch(f"{self._CONSUMER_QUEUE}.update_status_unless_failed", side_effect=record_status),+ patch(f"{self._CONSUMER_QUEUE}.unlock_for_batches", new_callable=AsyncMock),+ patch(f"{self._CONSUMER_QUEUE}.verify_advisory_lock", new_callable=AsyncMock, return_value=True),+ patch.object(DeltaBatchConsumerAdapter, "should_process_batch", new_callable=AsyncMock, return_value=True),+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),+ ):+ await consumer._process_group((1, "schema-1"), batches)+ return statuses++ @pytest.mark.asyncio+ async def test_a_set_is_loaded_once_and_every_member_gets_its_statuses(self):+ # Recovery, the claim gates and the reconcile sweeps all read per-batch status rows, so a+ # member left without them would look unclaimed or stranded.+ loaded: list[list[int]] = []++ async def process_batches(batches, verify_ownership=None):+ loaded.append([b.batch_index for b in batches])++ process_batch = AsyncMock()+ consumer = self._consumer(process_batches, process_batch)+ batches = _run_batches(3)++ statuses = await self._run_group(consumer, batches)++ assert loaded == [[0, 1, 2]]+ process_batch.assert_not_called()+ assert statuses == [*[(b.id, "executing", 1) for b in batches], *[(b.id, "succeeded", 1) for b in batches]]++ @pytest.mark.parametrize(+ "error,expected_latest_attempt,expected_status_attempt",+ [+ # Declined before writing: the members are loaded as they are.+ (CoalescingDeclined("schemas differ"), 0, 1),+ # Failed after the write may have landed: each member is a redelivery, so its own+ # idempotency check scans the commit history for the set's write.+ (RuntimeError("merge blew up"), 1, 2),+ ],+ ids=["declined", "failed"],+ )+ @pytest.mark.asyncio+ async def test_a_set_that_cannot_load_falls_back_to_its_members(+ self, error: Exception, expected_latest_attempt: int, expected_status_attempt: int+ ):+ process_batches = AsyncMock(side_effect=error)+ seen: list[tuple[int, int]] = []++ async def process_batch(batch, verify_ownership=None):+ seen.append((batch.batch_index, batch.latest_attempt))++ consumer = self._consumer(process_batches, process_batch)+ batches = _run_batches(2)++ statuses = await self._run_group(consumer, batches)++ assert seen == [(0, expected_latest_attempt), (1, expected_latest_attempt)]+ # The set's own executing rows come first; each member then goes through the single-batch+ # transitions, at the same attempt when nothing was written and at the next one otherwise.+ assert statuses == [+ (batches[0].id, "executing", 1),+ (batches[1].id, "executing", 1),+ (batches[0].id, "executing", expected_status_attempt),+ (batches[0].id, "succeeded", expected_status_attempt),+ (batches[1].id, "executing", expected_status_attempt),+ (batches[1].id, "succeeded", expected_status_attempt),+ ]++ @pytest.mark.asyncio+ async def test_without_a_set_loader_every_batch_is_single(self):+ process_batch = AsyncMock()+ consumer = self._consumer(None, process_batch)++ await self._run_group(consumer, _run_batches(3))++ assert process_batch.await_count == 3diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.pyindex ad7f0c739110..6ddea0bc9200 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py@@ -3,7 +3,7 @@ import timeimport asynciofrom collections.abc import Coroutinefrom datetime import timedelta-from typing import Any+from typing import Any, NamedTuplefrom uuid import uuid4import pytest@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineDeltaBatchConsumerAdapter,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ _SYNC_POOLS,BATCH_TABLE,CLAIM_ELIGIBILITY_INTERVAL,LEASE_TABLE,@@ -29,10 +30,12 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineQueueDepth,_orphaned_candidate_runs_sql,_queue_depth_sql,+ _sync_connection_pool,build_status_dual_write_sql,)# Distinct per-pod identities for the group-lease tests.+_JOBS_DB = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db"OWNER_A = str(uuid4())OWNER_B = str(uuid4())@@ -707,6 +710,56 @@ class TestVerifyGroupLeaseSync:assert owns is expected+ @pytest.fixture(autouse=True)+ def _fresh_pool(self):+ _SYNC_POOLS.clear()+ yield+ for pool in _SYNC_POOLS.values():+ for pooled in pool._idle:+ pooled.close()+ _SYNC_POOLS.clear()++ @pytest.mark.asyncio+ async def test_consecutive_checks_reuse_one_connection(self, conn, _db_url):+ # Every in-flight batch verifies its lease before each lasting side effect; dialing the queue+ # DB for each check was a connection setup per batch.+ await _insert_lease(conn, team_id=1, schema_id="s1", owner=OWNER_A, expires_in_seconds=300)++ with patch(f"{_JOBS_DB}.psycopg.connect", wraps=psycopg.connect) as connect:+ for _ in range(3):+ assert BatchQueue.verify_group_lease_sync(+ _db_url, team_id=1, schema_id="s1", owner_token=OWNER_A, connect_timeout_seconds=5+ )++ connect.assert_called_once()+ assert _sync_connection_pool(_db_url, 5).idle_count == 1++ @pytest.mark.asyncio+ async def test_a_dropped_pooled_connection_is_replaced_not_reported_as_a_lost_lease(self, conn, _db_url):+ # A pooler cull or failover closes idle server sessions behind the pool's back. The check must+ # answer from a fresh connection: raising here makes the caller abandon a batch it still owns.+ await _insert_lease(conn, team_id=1, schema_id="s1", owner=OWNER_A, expires_in_seconds=300)+ assert BatchQueue.verify_group_lease_sync(+ _db_url, team_id=1, schema_id="s1", owner_token=OWNER_A, connect_timeout_seconds=5+ )+ pool = _sync_connection_pool(_db_url, 5)+ (pooled,) = pool._idle+ # Kill the server side of the pooled session so the next query on it fails mid-flight.+ await conn.execute(+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid = %s",+ [pooled.info.backend_pid],+ )++ with patch(f"{_JOBS_DB}.psycopg.connect", wraps=psycopg.connect) as connect:+ owns = BatchQueue.verify_group_lease_sync(+ _db_url, team_id=1, schema_id="s1", owner_token=OWNER_A, connect_timeout_seconds=5+ )++ assert owns is True+ connect.assert_called_once()+ assert pooled.closed+ assert pool.idle_count == 1 and pool._idle[0] is not pooled+@pytest.mark.django_db(transaction=True)class TestQueueFreshnessProbe:@@ -1424,14 +1477,20 @@ class TestCountBatchesForRun:assert BatchQueue.count_batches_for_run(sync_conn, job_id="job-missing") == 0-async def _batch_state(conn: psycopg.AsyncConnection[Any], batch_id: str) -> tuple[str, int, Any]:+class _BatchState(NamedTuple):+ state: str+ attempt: int+ changed_at: Any+++async def _batch_state(conn: psycopg.AsyncConnection[Any], batch_id: str) -> _BatchState:cur = await conn.execute(f"SELECT latest_state, latest_attempt, state_changed_at FROM {BATCH_TABLE} WHERE id = %s",(batch_id,),)row = await cur.fetchone()assert row is not None- return row[0], row[1], row[2]+ return _BatchState(row[0], row[1], row[2])@pytest.mark.django_db(transaction=True)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_load.pyindex 7d935f28bd70..e8347069410f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_load.py@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load import (process_batch,+ process_batches,)_LOAD_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load"@@ -58,3 +59,18 @@ class TestProcessBatch:await process_batch(_make_batch(latest_attempt=latest_attempt))assert mock_process_message.call_args.kwargs["attempt"] == expected_attempt+++class TestProcessBatches:+ @pytest.mark.asyncio+ async def test_forwards_every_member_and_the_highest_attempt(self):+ # The set's attempt number decides whether the processor scans delta history; taking the+ # first member's count would let a redelivered member skip that scan.+ batches = [_make_batch(batch_index=0, latest_attempt=0), _make_batch(batch_index=1, latest_attempt=2)]++ with patch(f"{_LOAD_MODULE}.process_messages") as mock_process_messages:+ await process_batches(batches)++ messages = mock_process_messages.call_args.args[0]+ assert [message["batch_index"] for message in messages] == [0, 1]+ assert mock_process_messages.call_args.kwargs["attempt"] == 3diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.pyindex 616fca2e742e..b19cf64d81b2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py@@ -235,3 +235,83 @@ class TestPostgresProducerProperties:producer.is_first_ever_sync = Falseassert producer.is_first_ever_sync is False+++def _inserted_rows(producer: PostgresProducer) -> list[tuple[int, bool]]:+ return [+ (call.args[1]["batch_index"], call.args[1]["is_final_batch"])+ for call in _mock_conn(producer).execute.call_args_list+ if "INSERT INTO" in call.args[0]+ ]+++class TestPostgresProducerHeldBatch:+ # A run whose last data row is not its own final marker makes the loader read that parquet+ # file twice: once to write it, once to finish the run.++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",+ return_value=0,+ )+ def test_the_last_data_row_carries_the_final_flag(self, _supersede: MagicMock) -> None:+ producer = _make_producer()+ batches = [_make_batch_result(batch_index=i) for i in range(3)]++ for index, batch in enumerate(batches):+ producer.hold_batch(batch, cumulative_row_count=100 * (index + 1))+ assert _inserted_rows(producer) == [(i, False) for i in range(index)]+ producer.send_final_batch(batches[-1], total_batches=3, total_rows=300, data_folder="s3://d", schema_path=None)++ assert _inserted_rows(producer) == [(0, False), (1, False), (2, True)]+ final_params = _mock_conn(producer).execute.call_args_list[-1].args[1]+ assert (final_params["total_batches"], final_params["total_rows"], final_params["cumulative_row_count"]) == (+ 3,+ 300,+ 300,+ )++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",+ return_value=0,+ )+ def test_a_single_batch_run_inserts_exactly_one_row(self, _supersede: MagicMock) -> None:+ producer = _make_producer()+ batch = _make_batch_result(batch_index=0)++ producer.hold_batch(batch, cumulative_row_count=100)+ producer.send_final_batch(batch, total_batches=1, total_rows=100, data_folder="s3://d", schema_path="s3://s")++ assert _inserted_rows(producer) == [(0, True)]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",+ return_value=0,+ )+ def test_a_released_row_leaves_the_final_marker_as_a_second_row(self, _supersede: MagicMock) -> None:+ # A resumable source releases the held row before it commits a cursor. The run still needs a+ # final marker, and the loader still accepts the last batch repeated with the flag set.+ producer = _make_producer()+ batch = _make_batch_result(batch_index=0)++ producer.hold_batch(batch, cumulative_row_count=100)+ assert producer.release_held_batch() is True+ assert producer.release_held_batch() is False+ producer.send_final_batch(batch, total_batches=1, total_rows=100, data_folder="s3://d", schema_path=None)++ assert _inserted_rows(producer) == [(0, False), (0, True)]++ def test_superseding_fires_when_batch_zero_is_staged_not_when_it_is_inserted(self) -> None:+ # Holding the row back must not delay retiring the previous attempt's stalled batches, or+ # they stay claimable for one extra batch of extraction time.+ producer = _make_producer(is_resume=False)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.BatchQueue.supersede_other_runs",+ return_value=0,+ ) as mock_supersede:+ producer.hold_batch(_make_batch_result(batch_index=0), cumulative_row_count=100)++ mock_supersede.assert_called_once_with(+ producer._conn, job_id="job-1", current_run_uuid="run-1", spare_runs_with_progress=False+ )+ assert _inserted_rows(producer) == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/reader.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/reader.pyindex fe7f86d59bd7..bff78c8407b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/reader.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/reader.py@@ -1,3 +1,6 @@+import threading+from typing import Any+import pyarrow as paimport structlogimport pyarrow.parquet as pq@@ -7,15 +10,53 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinelogger = structlog.get_logger(__name__)+# One synchronous client for every read this process makes. A sync `S3FileSystem` runs its I/O on+# fsspec's own long-lived loop thread, so it is safe to share across the loader's worker threads and+# across the short-lived event loops `async_to_sync` spins up. Building one costs an aiobotocore+# client and credential resolution, which is why it is not rebuilt per batch.+_shared_lock = threading.Lock()+_shared_s3: Any = None+++def _get_shared_s3() -> Any:+ global _shared_s3+ s3 = _shared_s3+ if s3 is None:+ with _shared_lock:+ if _shared_s3 is None:+ _shared_s3 = get_s3_client(skip_instance_cache=True)+ s3 = _shared_s3+ return s3+++def _discard_shared_s3(s3: Any) -> None:+ global _shared_s3+ with _shared_lock:+ if _shared_s3 is s3:+ _shared_s3 = None+++def _read_table(s3: Any, path: str) -> pa.Table:+ with s3.open(path, "rb") as f:+ return pq.read_table(f)+def read_parquet(s3_path: str) -> pa.Table:- s3 = get_s3_client()s3_path_without_protocol = strip_s3_protocol(s3_path)logger.debug("reading_parquet", s3_path=s3_path)- with s3.open(s3_path_without_protocol, "rb") as f:- table = pq.read_table(f)+ s3 = _get_shared_s3()+ try:+ table = _read_table(s3, s3_path_without_protocol)+ except RuntimeError as e:+ # The RuntimeError s3fs raises here is a session whose event loop is gone. A fresh client is+ # the fix, and a single retry keeps a genuine fault from looping.+ if "loop" not in str(e).lower():+ raise+ logger.warning("parquet_read_client_rebuilt", s3_path=s3_path, error=str(e))+ _discard_shared_s3(s3)+ table = _read_table(_get_shared_s3(), s3_path_without_protocol)logger.debug("parquet_read_success", s3_path=s3_path, row_count=table.num_rows)@@ -23,7 +64,7 @@ def read_parquet(s3_path: str) -> pa.Table:def list_parquet_files(data_folder: str) -> list[str]:- s3 = get_s3_client()+ s3 = _get_shared_s3()folder_without_protocol = strip_s3_protocol(data_folder)try:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_reader.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_reader.pynew file mode 100644index 000000000000..50ffb8fcd52e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_reader.py@@ -0,0 +1,69 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import pyarrow as pa++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import reader++_READER = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.reader"++[email protected](autouse=True)+def _fresh_shared_client():+ reader._shared_s3 = None+ yield+ reader._shared_s3 = None+++def _client(open_error: Exception | None = None) -> MagicMock:+ s3 = MagicMock()+ if open_error is not None:+ s3.open.side_effect = open_error+ return s3+++class TestReadParquetClientReuse:+ # Building an S3 client is an aiobotocore session plus credential resolution, which the loader+ # used to pay on every batch because the fsspec instance cache was cleared per message.++ @patch(f"{_READER}.pq.read_table", return_value=pa.table({"id": [1]}))+ @patch(f"{_READER}.get_s3_client")+ def test_consecutive_reads_share_one_client(self, mock_get_client: MagicMock, _read: MagicMock) -> None:+ mock_get_client.return_value = _client()++ reader.read_parquet("s3://bucket/a.parquet")+ reader.read_parquet("s3://bucket/b.parquet")+ reader.list_parquet_files("s3://bucket/folder")++ mock_get_client.assert_called_once_with(skip_instance_cache=True)++ @patch(f"{_READER}.pq.read_table", return_value=pa.table({"id": [1]}))+ @patch(f"{_READER}.get_s3_client")+ def test_a_client_whose_loop_is_gone_is_rebuilt_once(self, mock_get_client: MagicMock, _read: MagicMock) -> None:+ dead, live = _client(RuntimeError("Event loop is closed")), _client()+ mock_get_client.side_effect = [dead, live]++ table = reader.read_parquet("s3://bucket/a.parquet")++ assert table.num_rows == 1+ assert mock_get_client.call_count == 2+ live.open.assert_called_once_with("bucket/a.parquet", "rb")++ @pytest.mark.parametrize(+ "error",+ [RuntimeError("parquet footer is corrupt"), FileNotFoundError("bucket/a.parquet"), PermissionError("denied")],+ ids=["other_runtime_error", "missing_object", "permission"],+ )+ @patch(f"{_READER}.get_s3_client")+ def test_other_read_failures_keep_the_client_and_propagate(self, mock_get_client: MagicMock, error: Any) -> None:+ # A missing or forbidden object is not a client fault; rebuilding would only hide it and cost a+ # session per failing batch.+ mock_get_client.return_value = _client(error)++ with pytest.raises(type(error)):+ reader.read_parquet("s3://bucket/a.parquet")++ mock_get_client.assert_called_once()+ assert reader._shared_s3 is mock_get_client.return_valuediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.pyindex 340e53b1bc63..52b48ef9ff24 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py@@ -21,6 +21,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinePipelineV3,should_coalesce_tables,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import (+ PostgresProducer,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResultfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (OutputLane,@@ -34,6 +38,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie_PIPELINE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline"_LANES = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.lanes"_CONSUMER = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer"+_PRODUCER = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer"def _make_logger() -> MagicMock:@@ -456,7 +461,7 @@ class TestLaneFanOut:assert [len(writer.batch_results) for writer in writers] == [1, 1]for writer in writers:- cast(MagicMock, writer.pg_producer.send_batch_notification).assert_called_once()+ cast(MagicMock, writer.pg_producer.hold_batch).assert_called_once()async def test_only_the_billable_lane_counts_towards_usage(self) -> None:# One read of a change stream is one sync however many tables it keeps.@@ -474,7 +479,7 @@ class TestLaneFanOut:await self._process(pipeline, pa.table({"id": pa.array([1, 2], pa.int64())}))assert [len(writer.batch_results) for writer in writers] == [1, 0]- cast(MagicMock, writers[1].pg_producer.send_batch_notification).assert_not_called()+ cast(MagicMock, writers[1].pg_producer.hold_batch).assert_not_called()async def test_the_primary_lane_keeps_batch_zero_even_when_it_filters_it_away(self) -> None:# The producer supersedes a previous attempt's staged batches only on index 0. If the@@ -521,8 +526,7 @@ class TestLaneFanOut:await pipeline._finalize(row_count=1)for writer in writers:- call = cast(MagicMock, writer.pg_producer.send_batch_notification).call_args- assert call.kwargs["is_final_batch"] is True+ cast(MagicMock, writer.pg_producer.send_final_batch).assert_called_once()async def test_a_lane_with_nothing_to_write_sends_no_final_batch(self) -> None:writers = [_lane_writer("users"), _lane_writer("users_cdc", transform=lambda t: t.slice(0, 0))]@@ -541,7 +545,7 @@ class TestLaneFanOut:):await pipeline._finalize(row_count=1)- cast(MagicMock, writers[1].pg_producer.send_batch_notification).assert_not_called()+ cast(MagicMock, writers[1].pg_producer.send_final_batch).assert_not_called()class TestCompanionJob:@@ -758,7 +762,7 @@ class TestSingleTableRunIsUntouched:assert staged == 0pipeline._s3_batch_writer.write_batch.assert_called_once()- pipeline._pg_producer.send_batch_notification.assert_called_once()+ pipeline._pg_producer.hold_batch.assert_called_once()def test_the_activity_runs_the_base_class_for_a_source_without_lanes(self) -> None:# What keeps every other source off the subclass. `lanes=None` is what a source that@@ -972,3 +976,180 @@ class TestResumeCursorCommit:assert cast(AsyncMock, pipeline._process_batch).await_count == 1assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == ["a"]+++def _recording_producer(events: list[str] | None = None) -> PostgresProducer:+ """A real producer over a mocked queue connection, so the rows it inserts can be read back."""+ with patch(f"{_PRODUCER}.psycopg") as mock_psycopg:+ conn = MagicMock()+ if events is not None:+ conn.execute.side_effect = lambda *_a, **_k: events.append("insert")+ mock_psycopg.Connection.connect.return_value = conn+ producer = PostgresProducer(+ database_url="postgres://unused:unused@localhost/unused",+ team_id=1,+ job_id="job-1",+ schema_id="schema-1",+ source_id="source-1",+ resource_name="test_table",+ sync_type="full_refresh",+ run_uuid="run-1",+ logger=MagicMock(),+ )+ return producer+++def _queue_rows(producer: PostgresProducer) -> list[tuple[int, bool]]:+ return [+ (call.args[1]["batch_index"], call.args[1]["is_final_batch"])+ for call in cast(MagicMock, producer._conn.execute).call_args_list+ if "INSERT INTO" in call.args[0]+ ]+++class TestFinalMarkerIsTheLastDataRow:+ """The loader processes every queue row. A final marker that repeats the last data batch makes it+ read and open that batch twice, and a marker that goes missing leaves the run running forever."""++ def _staging_pipeline(self, ids: list[str], manager: ResumableSourceManager[_Cursor] | None = None) -> PipelineV3:+ pipeline = _make_pipeline()+ pipeline._pg_producer = _recording_producer()+ pipeline._resumable_source_manager = manager+ pipeline._last_incremental_field_value = None+ pipeline._batcher = Batcher(MagicMock(), primary_keys=["id"])+ pipeline._schema = MagicMock(+ id="schema-1",+ source_id="source-1",+ is_incremental=False,+ is_webhook=False,+ is_append=False,+ should_use_incremental_field=False,+ table=None,+ )+ pipeline._s3_batch_writer = MagicMock(+ write_batch=MagicMock(+ side_effect=lambda table, index: BatchWriteResult(+ s3_path=f"s3://data/{index}.parquet",+ row_count=table.num_rows,+ byte_size=1,+ batch_index=index,+ timestamp_ns=0,+ )+ ),+ write_schema=MagicMock(return_value="s3://data/schema.json"),+ get_data_folder=MagicMock(return_value="s3://data"),+ get_run_uuid=MagicMock(return_value="run-1"),+ )++ def items():+ for row_id in ids:+ if manager is not None:+ manager.save_state(_Cursor(row_id))+ yield pa.table({"id": [row_id]})++ pipeline._resource = SourceResponse(name="test_table", items=items, primary_keys=["id"])++ # Everything `_process_batch` does besides staging needs the app DB; staging is the part under test.+ async def stage_only(pa_table: pa.Table, batch_index: int, row_count: int) -> None:+ await pipeline._stage_batch(pa_table, batch_index, row_count)++ pipeline._process_batch = AsyncMock(side_effect=stage_only) # type: ignore[method-assign]+ return pipeline++ async def _run(self, pipeline: PipelineV3, redis: MagicMock | None = None) -> None:+ with ExitStack() as stack:+ stack.enter_context(+ patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis or MagicMock()))+ )+ for name in (+ "reset_rows_synced_if_needed",+ "setup_row_tracking_with_billing_check",+ "handle_reset_or_full_refresh",+ "handle_corrupted_delta_log",+ "finalize_desc_sort_incremental_value",+ "advance_xmin_state",+ ):+ stack.enter_context(patch(f"{_PIPELINE}.{name}", new_callable=AsyncMock))+ for name in ("validate_incremental_sync", "record_source_item_stats", "update_sync_type_config_keys"):+ stack.enter_context(patch(f"{_PIPELINE}.{name}"))+ stack.enter_context(patch(f"{_PRODUCER}.BatchQueue.supersede_other_runs", return_value=0))+ stack.enter_context(patch(f"{_PIPELINE}.activity")).in_activity.return_value = False+ await pipeline.run()++ @pytest.mark.parametrize(+ "ids,expected_rows",+ [+ ([], []),+ (["a"], [(0, True)]),+ (["a", "b", "c"], [(0, False), (1, False), (2, True)]),+ ],+ ids=["zero_rows", "single_batch", "three_batches"],+ )+ @pytest.mark.asyncio+ async def test_a_run_enqueues_one_row_per_batch_with_the_last_one_final(+ self, ids: list[str], expected_rows: list[tuple[int, bool]]+ ) -> None:+ pipeline = self._staging_pipeline(ids)+ producer = pipeline._pg_producer++ await self._run(pipeline)++ assert _queue_rows(producer) == expected_rows++ @pytest.mark.asyncio+ async def test_a_resumable_source_enqueues_each_row_before_its_cursor_and_ends_with_a_marker(self) -> None:+ # Every cursor commit promises that the rows before it are loadable, so each held row goes in+ # before the commit that depends on it; the run then ends the old way, with the last batch+ # repeated as the final marker.+ events: list[str] = []+ manager = _manager()+ redis = MagicMock()+ redis.set.side_effect = lambda *_a, **_k: events.append("commit")+ pipeline = self._staging_pipeline(["a", "b"], manager)+ pipeline._pg_producer = _recording_producer(events)+ producer = pipeline._pg_producer++ await self._run(pipeline, redis)++ assert events == ["insert", "commit", "insert", "commit", "insert"]+ assert _queue_rows(producer) == [(0, False), (1, False), (1, True)]++ @pytest.mark.parametrize("staged", [True, False], ids=["cursor_staged", "nothing_staged"])+ @pytest.mark.asyncio+ async def test_a_cursor_commit_releases_the_held_row_first(self, staged: bool) -> None:+ events: list[str] = []+ manager = _manager()+ if staged:+ manager.save_state(_Cursor("a"))+ redis = MagicMock()+ redis.set.side_effect = lambda *_a, **_k: events.append("commit")+ pipeline = _make_pipeline()+ pipeline._pg_producer = _recording_producer(events)+ pipeline._resumable_source_manager = manager+ pipeline._pg_producer.hold_batch(+ BatchWriteResult(s3_path="s3://data/1.parquet", row_count=1, byte_size=1, batch_index=1, timestamp_ns=2),+ cumulative_row_count=2,+ )++ with patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)):+ await pipeline._commit_resume_state()++ assert events == (["insert", "commit"] if staged else [])++ @pytest.mark.asyncio+ async def test_an_extraction_error_still_enqueues_the_held_row(self) -> None:+ # A failed incremental run's staged tail is drained by the loader; a row left out of the queue+ # is a parquet file nothing ever loads.+ pipeline = self._staging_pipeline(["a", "b"])+ producer = pipeline._pg_producer++ def items():+ yield pa.table({"id": ["a"]})+ raise RuntimeError("source went away")++ pipeline._resource = SourceResponse(name="test_table", items=items, primary_keys=["id"])++ with pytest.raises(RuntimeError, match="source went away"):+ await self._run(pipeline)++ assert _queue_rows(producer) == [(0, False)]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.pyindex ded0e6e20de9..8316612cfd67 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py@@ -1,6 +1,8 @@import uuid+from datetime import UTC, datetimeimport pytest+import time_machinefrom posthog.test.base import BaseTest, NonAtomicBaseTestfrom unittest.mock import MagicMock, patch@@ -20,11 +22,17 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpersresolve_table_and_folder_names,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (+ REGISTERED_SCHEMA_FINGERPRINT_KEY,_refresh_cumulative_row_count,merge_columns,+ register_cdc_companion_table,update_last_synced_at,validate_schema_and_update_table,)+from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import (+ QueryFolderPointerHistory,+ advance_query_folder_pointer,+)from products.warehouse_sources.backend.types import (DataWarehouseTableCreatedVia,DataWarehouseTableFormat,@@ -315,6 +323,42 @@ class TestRegisterCDCCompanionTable(BaseTest):assert companions.count() == 0+# transaction=True: the real async function (not the sync mirror above) writes from the async thread+# pool (database_sync_to_async_pool), which can't see an atomic TestCase's uncommitted rows.[email protected]_db(transaction=True)+class TestRegisterCdcCompanionTableStamp:+ def test_stamps_the_companion_folder_activation_on_the_schema(self, team):+ # The companion table shares the schema row with the snapshot table, so its stamp has to land+ # under its own folder name or the snapshot's publish step would read the wrong flip time.+ source = ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=team, source_type="Postgres"+ )+ schema = ExternalDataSchema.objects.create(name="orders", team=team, source=source)+ job = ExternalDataJob.objects.create(+ team=team, pipeline=source, schema=schema, status=ExternalDataJobStatus.RUNNING, rows_synced=10+ )++ with (+ patch.object(DataWarehouseTable, "get_columns", return_value={}),+ patch.object(DataWarehouseTable, "get_count", return_value=100),+ ):+ async_to_sync(register_cdc_companion_table)(+ run_id=str(job.id),+ team_id=team.pk,+ schema_id=schema.id,+ resource_name="orders_cdc",+ row_count=100,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder="orders_cdc__query_a",+ )++ schema.refresh_from_db()+ history = QueryFolderPointerHistory.from_config(schema.sync_type_config, "orders_cdc__query")+ assert history is not None+ assert history.active == "orders_cdc__query_a"+ assert history.active_job_id == str(job.id)++# transaction=True: validate_schema_and_update_table writes to the DB from the async thread pool# (database_sync_to_async_pool), which can't see an atomic TestCase's uncommitted rows.@pytest.mark.django_db(transaction=True)@@ -404,6 +448,151 @@ class TestValidateSchemaAndUpdateTable:# A reported 0 must not zero a table that was just republished.assert table.row_count == 150+ @pytest.mark.parametrize(+ ("recorded_active", "expect_restart"),+ [+ # The recorded active folder is the one the pointer is on: the history stays contiguous, so+ # the publish step may keep trusting that an unrecorded slot has not been read since it began.+ pytest.param("orders__query_a", False, id="recorded_move"),+ # The pointer is not where the record says: a move was lost (a crash between the pointer+ # write and the record). Trusting the old history would let a slot that was read moments+ # ago be rewritten, so the history restarts now.+ pytest.param("orders__query_c", True, id="unrecorded_move"),+ ],+ )+ @time_machine.travel("2026-01-02T12:00:00Z", tick=False)+ def test_records_the_pointer_move_and_restarts_the_history_after_a_gap(+ self, team, recorded_active: str, expect_restart: bool+ ):+ schema, job = self._schema_and_job(team)+ self._linked_table(team, schema, job, queryable_folder="orders__query_a")+ long_ago = datetime(2026, 1, 1, tzinfo=UTC)+ config: dict = {}+ advance_query_folder_pointer(+ config, previous_folder="orders__query_b", queryable_folder=recorded_active, job_id="old-job", now=long_ago+ )+ advance_query_folder_pointer(+ config, previous_folder=None, queryable_folder="orders_cdc__query_a", job_id="cdc-job", now=long_ago+ )+ schema.sync_type_config = config+ schema.save()+ before = datetime.now(UTC)++ with (+ patch.object(DataWarehouseTable, "get_columns", return_value={}),+ patch.object(DataWarehouseTable, "get_count", return_value=150),+ ):+ async_to_sync(validate_schema_and_update_table)(+ run_id=str(job.id),+ team_id=team.pk,+ schema_id=schema.id,+ row_count=10,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder="orders__query_b",+ )++ schema.refresh_from_db()+ history = QueryFolderPointerHistory.from_config(schema.sync_type_config, "orders__query")+ assert history is not None+ assert history.active == "orders__query_b"+ assert history.active_job_id == str(job.id)+ a_stopped = history.stopped_being_active("orders__query_a")+ assert a_stopped is not None and a_stopped >= before+ assert history.stopped_being_active("orders__query_b") is None+ assert history.history_since is not None+ assert (history.history_since >= before) is expect_restart+ companion = QueryFolderPointerHistory.from_config(schema.sync_type_config, "orders_cdc__query")+ assert companion is not None and companion.active == "orders_cdc__query_a"++ def _register(+ self,+ team,+ schema,+ job,+ *,+ queryable_folder: str,+ delta_schema_json: str,+ table_schema_dict: dict[str, str] | None = None,+ ) -> None:+ async_to_sync(validate_schema_and_update_table)(+ run_id=str(job.id),+ team_id=team.pk,+ schema_id=schema.id,+ row_count=10,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder=queryable_folder,+ table_schema_dict=table_schema_dict or {"id": "IntegerDatabaseField"},+ delta_schema_json=delta_schema_json,+ )++ @pytest.mark.parametrize(+ ("changes", "expect_introspection"),+ [+ pytest.param({}, False, id="same_inputs"),+ # The Delta log gained a column: the DESCRIBE result changes with it.+ pytest.param({"delta_schema_json": '{"fields": ["id", "email"]}'}, True, id="delta_schema_changed"),+ # The user deselected a column: the projection over the same introspection changes.+ pytest.param({"enabled_columns": ["id"]}, True, id="enabled_columns_changed"),+ # The loader typed a column differently (JSON detection): the merge changes.+ pytest.param({"table_schema_dict": {"id": "StringJSONDatabaseField"}}, True, id="table_schema_changed"),+ ],+ )+ def test_introspects_again_only_when_a_registration_input_changed(+ self, team, changes: dict, expect_introspection: bool+ ):+ # A DESCRIBE of the published files runs against ClickHouse on every sync although the+ # schema rarely changes. Skipping it must not go further than that: the pointer flip and the+ # row count are what make the new files queryable, and any input the columns depend on must+ # bring the introspection back, or a deselected column would stay in HogQL.+ schema, job = self._schema_and_job(team)+ table = self._linked_table(team, schema, job, queryable_folder="orders__query_a")+ delta_schema_json = '{"fields": ["id"]}'++ with (+ patch.object(+ DataWarehouseTable, "get_columns", return_value={"id": {"clickhouse": "Int64", "hogql": "x"}}+ ) as get_columns,+ patch.object(DataWarehouseTable, "get_count", return_value=150),+ ):+ self._register(team, schema, job, queryable_folder="orders__query_a", delta_schema_json=delta_schema_json)+ assert get_columns.call_count == 1+ if "enabled_columns" in changes:+ ExternalDataSchema.objects.filter(id=schema.id).update(enabled_columns=changes["enabled_columns"])+ self._register(+ team,+ schema,+ job,+ queryable_folder="orders__query_b",+ delta_schema_json=changes.get("delta_schema_json", delta_schema_json),+ table_schema_dict=changes.get("table_schema_dict"),+ )++ assert get_columns.call_count == (2 if expect_introspection else 1)+ table.refresh_from_db()+ assert table.queryable_folder == "orders__query_b"+ assert table.row_count == 10+ assert table.columns is not None+ assert table.columns["id"]["clickhouse"] == "Int64"+ schema.refresh_from_db()+ assert schema.sync_type_config[REGISTERED_SCHEMA_FINGERPRINT_KEY]++ def test_a_failed_introspection_leaves_no_fingerprint_behind(self, team):+ # get_columns() can fail on a table with no committed files (tolerated, see above). The next+ # sync must introspect again rather than trust a fingerprint for columns that were never written.+ schema, job = self._schema_and_job(team)+ self._linked_table(team, schema, job, queryable_folder="orders__query_a")+ no_files_error = ServerException("No files in log segment (in snapshot).", code=742)++ with (+ patch(f"{_TABLE_MODULE}.sync_execute", side_effect=no_files_error),+ patch(f"{_TABLE_MODULE}.time.sleep"),+ patch.object(DataWarehouseTable, "get_count", return_value=0),+ ):+ self._register(team, schema, job, queryable_folder="orders__query_a", delta_schema_json="{}")++ schema.refresh_from_db()+ assert REGISTERED_SCHEMA_FINGERPRINT_KEY not in schema.sync_type_config+def test_zero_row_sync_creates_no_table(self, team):# The publish step republishes the whole delta table every run, so files being queryable# says nothing about this run writing any. A table born here has no column types to take -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.pynew file mode 100644index 000000000000..624503f0488e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/query_folder_state.py@@ -0,0 +1,138 @@+"""Where a table's query folder pointer has been, recorded on the schema's `sync_type_config`.++A leaf module (no deltalake, no pipeline imports): table registration writes the record after every+pointer flip, the publish step reads it to pick a standby slot, and the DuckLake registration reads+it to tell one generation on a fixed slot name from the next.+"""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Any++from 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).+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+# slot being reconciled stopped being read one whole sync interval before the current slot took over,+# and a table synced more often than S3_DELETE_TIME_BUFFER still takes the incremental path. None of+# the names ends in digits, so the age-based cleanup of `__query_<digits>` folders never selects them.+QUERY_FOLDER_SLOTS = ("a", "b", "c")+++def query_folder_table_prefix(queryable_folder: str) -> str:+ """`<table>__query`, shared by every query folder of one table: the slots, the timestamped+ folders and the legacy fixed folder."""+ return queryable_folder.rsplit("__query", 1)[0] + "__query"+++def query_folder_slot_names(table_prefix: str) -> tuple[str, ...]:+ return tuple(f"{table_prefix}_{slot}" for slot in QUERY_FOLDER_SLOTS)+++def _parse_instant(raw: Any) -> datetime | None:+ if not isinstance(raw, str):+ return None+ try:+ parsed = datetime.fromisoformat(raw)+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+++@frozen+class QueryFolderPointerHistory:+ """The recorded pointer moves of one table's query folders."""++ active: str | None+ active_since: datetime | None+ active_job_id: str | None+ # Every pointer move since this instant was recorded, so a folder with no record was not the+ # pointer at any time after it.+ history_since: datetime | None+ # When each folder last stopped being the pointer.+ inactive_since: dict[str, datetime]++ @classmethod+ def from_config(cls, sync_type_config: Any, table_prefix: str) -> QueryFolderPointerHistory | None:+ if not isinstance(sync_type_config, dict):+ return None+ states = sync_type_config.get(QUERY_FOLDER_STATE_KEY)+ state = states.get(table_prefix) if isinstance(states, dict) else None+ if not isinstance(state, dict):+ return None+ raw_inactive = state.get("inactive_since")+ inactive_since: dict[str, datetime] = {}+ if isinstance(raw_inactive, dict):+ for folder, raw in raw_inactive.items():+ instant = _parse_instant(raw)+ if instant is not None:+ inactive_since[str(folder)] = instant+ active = state.get("active")+ active_job_id = state.get("active_job_id")+ return cls(+ active=active if isinstance(active, str) else None,+ active_since=_parse_instant(state.get("active_since")),+ 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,+ )++ def stopped_being_active(self, folder: str) -> datetime | None:+ """When `folder` last stopped being the pointer, or None when that is not known.++ A folder with no record has not been the pointer since `history_since`, so any read of it+ started before then.+ """+ if folder == self.active:+ return None+ recorded = self.inactive_since.get(folder)+ if recorded is not None:+ return recorded+ return self.history_since+++def advance_query_folder_pointer(+ sync_type_config: dict[str, Any],+ *,+ previous_folder: str | None,+ queryable_folder: str,+ job_id: str,+ now: datetime | None = None,+) -> None:+ """Record, in place, that the pointer moved from `previous_folder` to `queryable_folder`.++ A `previous_folder` that is not the recorded active folder means a move this record missed (a+ crash between the pointer write and the record, or a reset that cleared the config), so+ `history_since` restarts: a slot with no record can then only be trusted as unread since now.+ Only the slots keep an `inactive_since` entry, because they are the only folders that get reused.+ """+ at = now or datetime.now(UTC)+ table_prefix = query_folder_table_prefix(queryable_folder)+ previous = QueryFolderPointerHistory.from_config(sync_type_config, table_prefix)++ contiguous = previous is not None and previous.active == previous_folder+ history_since = previous.history_since if contiguous and previous is not None else None+ inactive_since = dict(previous.inactive_since) if previous is not None else {}+ if previous_folder is not None and previous_folder != queryable_folder:+ inactive_since[previous_folder] = at+ inactive_since.pop(queryable_folder, None)+ slot_names = query_folder_slot_names(table_prefix)++ states = sync_type_config.get(QUERY_FOLDER_STATE_KEY)+ if not isinstance(states, dict):+ states = {}+ states[table_prefix] = {+ "active": queryable_folder,+ "active_since": at.isoformat(),+ "active_job_id": job_id,+ "history_since": (history_since or at).isoformat(),+ "inactive_since": {+ folder: instant.isoformat() for folder, instant in inactive_since.items() if folder in slot_names+ },+ }+ sync_type_config[QUERY_FOLDER_STATE_KEY] = statesdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.pyindex 702baee35726..47a5aaa33883 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py@@ -124,6 +124,10 @@ class ResumableSourceManager(Generic[ResumableData]):self._logger.debug(f"Staging resumable source state. key={self._key}, data={json_data}")self._staged[self._key] = json_data+ def has_staged_state(self) -> bool:+ """Whether the next `commit` will write anything."""+ return bool(self._staged)+def commit(self) -> None:"""Persist every staged cursor, across namespaces."""if not self._staged: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.pyindex 646796487d98..f2c3f31580a7 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@@ -1,10 +1,14 @@+import reimport errnoimport contextlib+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespaceimport pytest+import time_machinefrom unittest.mock import AsyncMock, MagicMock, patch+from django.conf import settingsfrom django.db import (OperationalError as DjangoOperationalError,ProgrammingError,@@ -18,6 +22,7 @@ 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 QueryFolderPointerHistoryfrom products.warehouse_sources.backend.temporal.data_imports.util import (_INTERNAL_DB_MAX_ATTEMPTS,NonRetryableException,@@ -57,6 +62,7 @@ def _fake_s3(**kwargs):"invalidate_cache": lambda: None,"_ls": AsyncMock(return_value=[]),"_exists": AsyncMock(return_value=False),+ "_find": AsyncMock(return_value={}),"_cp_file": AsyncMock(),"_copy": AsyncMock(),"_rm": AsyncMock(),@@ -339,6 +345,272 @@ class TestPrepareS3FilesForQuerying:s3._cp_file.assert_awaited_once()+_JOB_URI = f"{settings.BUCKET_URL}/job"+_JOB_KEY = _JOB_URI.split("://", 1)[-1]+_TIMESTAMPED_FOLDER = re.compile(r"^my_table__query_\d+_[0-9a-f]{8}$")+++def _live(*names: str) -> list[str]:+ return [f"{_JOB_URI}/my_table/{name}" for name in names]+++def _standby_listing(folder: str, *names: str) -> dict[str, dict]:+ return {+ f"{_JOB_KEY}/{folder}/{name}": {"Key": f"{_JOB_KEY}/{folder}/{name}", "type": "file", "size": 1}+ for name in names+ }+++def _job_folder_listing(*folders: str) -> list[dict]:+ return [{"Key": f"{_JOB_KEY}/{folder}", "type": "directory"} for folder in folders]+++def _stale_epoch() -> int:+ return int((datetime.now(UTC) - timedelta(seconds=util_module.S3_DELETE_TIME_BUFFER * 2)).timestamp())+++# Histories are built at import (many inside parameterized cases), so they are anchored to a fixed+# instant and the double-buffer tests freeze the clock there. Relative to the real clock, a+# "moments ago" stamp goes stale when the suite reaches these tests long after collection.+_NOW = datetime(2026, 1, 1, 12, 0, tzinfo=UTC)+_LONG_AGO = _NOW - timedelta(seconds=util_module.S3_DELETE_TIME_BUFFER * 2)+_MOMENTS_AGO = _NOW - timedelta(seconds=30)+_SLOT_A, _SLOT_B, _SLOT_C = "my_table__query_a", "my_table__query_b", "my_table__query_c"+++def _history(+ active: str | None,+ *,+ inactive: dict[str, datetime] | None = None,+ history_since: datetime = _LONG_AGO,+) -> QueryFolderPointerHistory:+ return QueryFolderPointerHistory(+ active=active,+ active_since=_MOMENTS_AGO,+ active_job_id="job",+ history_since=history_since,+ inactive_since=inactive or {},+ )+++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]++ return AsyncMock(side_effect=_find)+++async def _prepare_double_buffered(+ s3: SimpleNamespace,+ *,+ existing: str | None,+ history: QueryFolderPointerHistory | None,+ file_uris: list[str],+ double_buffer: bool = True,+) -> str:+ with (+ patch.object(util_module, "aget_s3_client", return_value=_FakeS3CM(s3)),+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ return await prepare_s3_files_for_querying(+ folder_path="job",+ table_name="my_table",+ file_uris=file_uris,+ existing_queryable_folder=existing,+ double_buffer=double_buffer,+ pointer_history=history,+ )+++class TestDoubleBufferedQueryFolders:+ @pytest.fixture(autouse=True)+ def _clock_at_the_histories_anchor(self):+ with time_machine.travel(_NOW, tick=True):+ yield++ def _copied(self, s3: SimpleNamespace) -> set[str]:+ return {call.args[1] for call in s3._cp_file.await_args_list}++ @parameterized.expand(+ [+ # A table with no pointer yet, and one still on a timestamped folder, both start on slot a.+ ("new_table", None, None, _SLOT_A),+ (+ "migrating_from_timestamped_folder",+ "my_table__query_1700000000_0badf00d",+ _history("my_table__query_1700000000_0badf00d"),+ _SLOT_A,+ ),+ # The rotation fills every empty slot before it rewrites one that held a generation.+ ("second_sync_fills_b", _SLOT_A, _history(_SLOT_A), _SLOT_B),+ (+ "third_sync_fills_c_before_reusing_a",+ _SLOT_B,+ _history(_SLOT_B, inactive={_SLOT_A: _MOMENTS_AGO}),+ _SLOT_C,+ ),+ ]+ )+ async def test_fills_the_least_recently_used_empty_slot_in_full(+ self, _name: str, existing: str | None, history: QueryFolderPointerHistory | None, expected: str+ ):+ s3 = _fake_s3(_find=_find_returning({}))++ folder = await _prepare_double_buffered(s3, existing=existing, history=history, file_uris=_live("p0", "p1"))++ assert folder == expected+ assert self._copied(s3) == {f"{_JOB_URI}/{expected}/p0", f"{_JOB_URI}/{expected}/p1"}+ s3._rm.assert_not_awaited()++ async def test_reconciles_the_slot_that_stopped_being_read_longest_ago(self):+ # Steady-state rotation a -> b -> c -> a: with c active, a stopped being the pointer when b+ # took over, one whole sync interval before c did, so a is the slot to rewrite. The rewrite+ # pays for the files that changed, not for every live file, and a file that stopped being live+ # leaves the slot before readers are pointed at it, or the glob returns its rows twice.+ s3 = _fake_s3(+ _find=_find_returning(+ {_SLOT_A: _standby_listing(_SLOT_A, "p1", "stale"), _SLOT_B: _standby_listing(_SLOT_B, "p1")}+ )+ )+ history = _history(_SLOT_C, inactive={_SLOT_A: _LONG_AGO, _SLOT_B: _MOMENTS_AGO})++ folder = await _prepare_double_buffered(s3, existing=_SLOT_C, history=history, file_uris=_live("p1", "p2"))++ assert folder == _SLOT_A+ assert self._copied(s3) == {f"{_JOB_URI}/{_SLOT_A}/p2"}+ s3._rm.assert_awaited_once_with([f"s3://{_JOB_KEY}/{_SLOT_A}/stale"])++ @parameterized.expand(+ [+ ("stopped_just_past_the_buffer", util_module.S3_DELETE_TIME_BUFFER + 1, _SLOT_A),+ ("stopped_just_inside_the_buffer", util_module.S3_DELETE_TIME_BUFFER - 1, None),+ ]+ )+ async def test_reuses_a_populated_slot_only_once_it_is_older_than_the_buffer(+ self, _name: str, seconds_since_a_stopped: int, expected_slot: str | None+ ):+ # The age that matters is when the slot stopped being the pointer (its successor took over),+ # not when it became the pointer: a reader that started just before the flip may still be+ # globbing it for up to the buffer.+ s3 = _fake_s3(+ _find=_find_returning({_SLOT_A: _standby_listing(_SLOT_A, "p1"), _SLOT_B: _standby_listing(_SLOT_B, "p1")})+ )+ a_stopped = datetime.now(UTC) - timedelta(seconds=seconds_since_a_stopped)+ history = _history(_SLOT_C, inactive={_SLOT_A: a_stopped, _SLOT_B: _MOMENTS_AGO})++ folder = await _prepare_double_buffered(s3, existing=_SLOT_C, history=history, file_uris=_live("p1", "p2"))++ if expected_slot is None:+ assert _TIMESTAMPED_FOLDER.match(folder)+ assert self._copied(s3) == {f"{_JOB_URI}/{folder}/p1", f"{_JOB_URI}/{folder}/p2"}+ else:+ assert folder == expected_slot+ assert self._copied(s3) == {f"{_JOB_URI}/{expected_slot}/p2"}++ async 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+ # is as suspect as one read moments ago. An empty slot has no prefix in S3 and nothing can be+ # reading it, so it is still usable even when it sorts behind the suspect one.+ s3 = _fake_s3(_find=_find_returning({_SLOT_B: _standby_listing(_SLOT_B, "p1")}))+ history = _history(_SLOT_A, inactive={_SLOT_B: _MOMENTS_AGO}, history_since=_MOMENTS_AGO)++ folder = await _prepare_double_buffered(s3, existing=_SLOT_A, history=history, file_uris=_live("p1"))++ assert folder == _SLOT_C+ assert self._copied(s3) == {f"{_JOB_URI}/{_SLOT_C}/p1"}++ async def test_reconcile_diffs_against_a_refreshed_listing_after_a_vanished_source_file(self):+ # A zombie compaction can replace live files between the listing and the copy. The retry must+ # diff the fresh listing against the standby again, otherwise it copies the vanished file+ # forever or leaves the compacted file behind.+ cp_file = AsyncMock(side_effect=[FileNotFoundError("p2"), None])+ s3 = _fake_s3(_cp_file=cp_file, _find=_find_returning({_SLOT_A: _standby_listing(_SLOT_A, "p1")}))+ refresh = AsyncMock(return_value=_live("p1", "compacted"))++ with (+ patch.object(util_module, "aget_s3_client", return_value=_FakeS3CM(s3)),+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ folder = await prepare_s3_files_for_querying(+ folder_path="job",+ table_name="my_table",+ file_uris=_live("p1", "p2"),+ existing_queryable_folder=_SLOT_C,+ double_buffer=True,+ pointer_history=_history(_SLOT_C, inactive={_SLOT_A: _LONG_AGO, _SLOT_B: _MOMENTS_AGO}),+ refresh_file_uris=refresh,+ )++ assert folder == _SLOT_A+ assert cp_file.await_args_list[-1].args[1] == f"{_JOB_URI}/{_SLOT_A}/compacted"+ s3._rm.assert_not_awaited()++ @parameterized.expand(+ [+ # No record at all: nothing says when a populated slot was last read.+ ("no_history_and_populated_slots", None, None),+ # Every other slot stopped being read within the buffer.+ (+ "all_slots_read_recently",+ _SLOT_C,+ _history(_SLOT_C, inactive={_SLOT_A: _MOMENTS_AGO, _SLOT_B: _MOMENTS_AGO}),+ ),+ # A move this record missed (a crash between pointer write and record, or a schema reset)+ # restarts the history, and unrecorded populated slots are not trusted until it is old.+ ("history_restarted_recently", _SLOT_A, _history(_SLOT_A, history_since=_MOMENTS_AGO)),+ ]+ )+ async def test_falls_back_to_a_fresh_timestamped_folder_when_every_slot_may_still_be_read(+ self, _name: str, existing: str | None, history: QueryFolderPointerHistory | None+ ):+ s3 = _fake_s3(+ _find=_find_returning({slot: _standby_listing(slot, "p1") for slot in (_SLOT_A, _SLOT_B, _SLOT_C)})+ )++ folder = await _prepare_double_buffered(s3, existing=existing, history=history, file_uris=_live("p1", "p2"))++ assert _TIMESTAMPED_FOLDER.match(folder)+ assert self._copied(s3) == {f"{_JOB_URI}/{folder}/p1", f"{_JOB_URI}/{folder}/p2"}+ s3._rm.assert_not_awaited()++ @parameterized.expand([("flag_on", True), ("flag_off", False)])+ async def test_age_based_cleanup_never_removes_the_slot_folders(self, _name: str, double_buffer: bool):+ # Turning the flag off after a table moved onto the slots returns it to timestamped folders;+ # the cleanup must still take the stale timestamped folders and must leave every slot alone,+ # because one of them is what readers are on right now.+ 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)),+ _find=_find_returning({}),+ )++ folder = await _prepare_double_buffered(+ s3, existing=_SLOT_A, history=_history(_SLOT_A), file_uris=_live("p1"), double_buffer=double_buffer+ )++ if double_buffer:+ assert folder == _SLOT_B+ else:+ 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 swallowing+ # the failure would publish duplicate rows. Raising keeps the pointer where it is.+ s3 = _fake_s3(+ _find=_find_returning({_SLOT_A: _standby_listing(_SLOT_A, "p1", "stale")}),+ _rm=AsyncMock(side_effect=PermissionError("Access Denied")),+ )+ history = _history(_SLOT_C, inactive={_SLOT_A: _LONG_AGO, _SLOT_B: _MOMENTS_AGO})++ with pytest.raises(S3OperationError):+ await _prepare_double_buffered(s3, existing=_SLOT_C, history=history, file_uris=_live("p1"))++@parameterized.expand([(diff --git a/products/warehouse_sources/backend/temporal/data_imports/util.py b/products/warehouse_sources/backend/temporal/data_imports/util.pyindex 040f0090eab7..ea4b6deaf100 100644--- a/products/warehouse_sources/backend/temporal/data_imports/util.py+++ b/products/warehouse_sources/backend/temporal/data_imports/util.py@@ -3,9 +3,9 @@ import timeimport errnoimport asynciofrom collections.abc import Awaitable, Callable-from datetime import datetime+from datetime import UTC, datetimefrom functools import wraps-from typing import Literal, Optional, ParamSpec, TypeVar+from typing import TYPE_CHECKING, Literal, Optional, ParamSpec, TypeVarfrom uuid import uuid4from django.conf import settings@@ -25,6 +25,13 @@ from posthog.utils import str_to_boolfrom products.data_warehouse.backend.facade.api import aget_s3_clientfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import (+ QueryFolderPointerHistory,+ query_folder_slot_names,+)++if TYPE_CHECKING:+ from s3fs import S3FileSystemLOGGER = get_logger(__name__)@@ -235,6 +242,10 @@ def with_internal_db_retries(fn: Callable[P, T]) -> Callable[P, T]:# 10 mins buffer to avoid deleting files Clickhouse may be readingS3_DELETE_TIME_BUFFER = 600+# Per-schema rollout flag for the fixed a/b query folder pair below. Off (or unevaluable) means the+# timestamped-folder path, so a bad rollout is undone by turning the flag off.+DOUBLE_BUFFERED_QUERY_FOLDERS_FLAG = "data-warehouse-double-buffered-query-folders"+# 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 core/delta/maintenance.py, before vacuum even starts - which can outlive a@@ -258,6 +269,101 @@ def is_posthog_team(team_id: int) -> bool:return (region == "EU" and team_id == 1) or (region == "US" and team_id == 2)+def _unread_long_enough(stopped_being_active: Optional[datetime]) -> bool:+ """Whether a slot that stopped being the pointer at `stopped_being_active` can be rewritten: every+ read of it started before that instant, and none runs longer than the buffer."""+ if stopped_being_active is None:+ return False+ return (datetime.now(UTC) - stopped_being_active).total_seconds() >= S3_DELETE_TIME_BUFFER+++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.+ """+ try:+ found = await s3._find(folder_uri, detail=True)+ except FileNotFoundError:+ return {}+ entries = found.values() if isinstance(found, dict) else found+ prefix = folder_uri.split("://", 1)[-1].rstrip("/") + "/"+ files: dict[str, str] = {}+ for entry in entries:+ if entry.get("type") == "directory":+ continue+ key = str(entry["Key"]).split("://", 1)[-1]+ if key.startswith(prefix):+ files[key[len(prefix) :]] = f"s3://{key}"+ return files+++async def _pick_standby_slot(+ s3: "S3FileSystem",+ s3_folder_for_job: str,+ normalized_table_name: str,+ existing_queryable_folder: Optional[str],+ pointer_history: Optional[QueryFolderPointerHistory],+ log: Callable[..., Awaitable[None]],+) -> Optional[tuple[str, dict[str, str]]]:+ """The slot to reconcile and what it holds, or None when every slot may still be read.++ Candidates are tried from the one that stopped being the pointer longest ago. A slot is usable+ when it is empty (no prefix in S3, so nothing can be reading it) or when it stopped being the+ pointer at least `S3_DELETE_TIME_BUFFER` ago. A slot with no pointer record is treated as unread+ since the record began; with no record at all, only an empty slot is 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+ candidates = [name for name in slot_names if name not in (existing_queryable_folder, recorded_active)]++ def stopped_at(name: str) -> Optional[datetime]:+ return pointer_history.stopped_being_active(name) if pointer_history is not None else None++ candidates.sort(key=lambda name: (stopped_at(name) is None, stopped_at(name) or datetime.min.replace(tzinfo=UTC)))+ for name in candidates:+ listed = 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")+ return name, listed+ await log(f"Standby query folder {name} stopped being read at {stopped_at(name)}, too recent to rewrite")+ await log("No query folder slot is safe to rewrite; falling back to a fresh timestamped folder")+ return None+++async def _delete_stale_standby_files(+ s3: "S3FileSystem",+ stale_files: list[str],+ log: Callable[..., Awaitable[None]],+) -> None:+ """Remove files from the standby that are not in the live set.++ Unlike the old-folder cleanup, this is not best effort: the caller repoints readers at this+ folder next, and a leftover file would make the glob return rows twice. A failure here raises so+ the pointer stays on the current folder and the next sync reconciles again.+ """+ delete_attempt = 0+ while True:+ delete_attempt += 1+ try:+ await s3._rm(stale_files)+ return+ except FileNotFoundError:+ # Already gone, which is the state this delete wanted.+ return+ except Exception as e:+ if _is_s3_throttling_error(e) and delete_attempt < _DELETE_FOLDER_MAX_ATTEMPTS:+ await log(+ f"S3 throttled the delete of stale standby files (attempt "+ f"{delete_attempt}/{_DELETE_FOLDER_MAX_ATTEMPTS}), retrying: {e}",+ level="error",+ )+ await asyncio.sleep(2**delete_attempt)+ continue+ raise S3OperationError("remove stale files from this table's standby query folder", e)++async def prepare_s3_files_for_querying(folder_path: str,table_name: str,@@ -268,8 +374,26 @@ async def prepare_s3_files_for_querying(delete_existing: bool = True,logger: Optional[FilteringBoundLogger] = None,refresh_file_uris: Optional[Callable[[], Awaitable[list[str]]]] = None,+ double_buffer: bool = False,+ pointer_history: Optional[QueryFolderPointerHistory] = None,) -> str:- """Async version that uses s3fs native async methods for concurrent file operations."""+ """Publish the table's live parquet files into a folder readers glob, and return that folder's name.++ The caller repoints `DataWarehouseTable.queryable_folder` at the returned folder afterwards, so a+ folder this function returns must be complete: S3 has no multi-object atomic update, so a+ reader glob over a half-written folder sees missing or duplicated rows.++ Default path: a fresh `<table>__query_<ts>_<uuid>` folder receives a copy of every live file, and+ timestamped folders older than `S3_DELETE_TIME_BUFFER` are removed.++ `double_buffer`: the table rotates through `<table>__query_a`, `_b` and `_c`. The standby to+ reconcile is the slot that stopped being the pointer longest ago (per `pointer_history`); it is+ reconciled against the live file set, so a sync copies only the files the standby lacks and+ removes the ones no longer live. The diff is taken against an S3 listing rather than a commit+ range, so a missed sync or a crash mid-reconcile heals on the next pass. A populated slot that+ stopped being the pointer within `S3_DELETE_TIME_BUFFER`, or whose last use is unknown, is not+ touched; the sync falls back to the default path.+ """async def _log(msg: str, level: Optional[Literal["debug", "error"]] = "debug") -> None:if logger:@@ -280,7 +404,8 @@ async def prepare_s3_files_for_querying(await _log(f"Preparing S3 files for querying for table {table_name} in folder {folder_path}. "- f"delete_existing={delete_existing}. use_timestamped_folders={use_timestamped_folders}."+ f"delete_existing={delete_existing}. use_timestamped_folders={use_timestamped_folders}. "+ f"double_buffer={double_buffer}.")async with aget_s3_client() as s3:@@ -298,7 +423,19 @@ async def prepare_s3_files_for_querying(s3_folder_for_querying = f"{normalized_table_name}__query"s3_path_for_querying = f"{s3_folder_for_job}/{s3_folder_for_querying}"- if use_timestamped_folders:++ # Relative path -> full URI of what the standby already holds. None means a full copy into a+ # fresh folder, either because double buffering is off or because no slot is safe to touch yet.+ standby_files: Optional[dict[str, str]] = None+ if double_buffer and use_timestamped_folders:+ standby = await _pick_standby_slot(+ s3, s3_folder_for_job, normalized_table_name, existing_queryable_folder, pointer_history, _log+ )+ if standby is not None:+ s3_folder_for_querying, standby_files = standby+ s3_path_for_querying = f"{s3_folder_for_job}/{s3_folder_for_querying}"++ if standby_files is None and use_timestamped_folders:# Seconds first (the age-based GC below parses them), then a unique suffix:# two syncs completing within the same second must not share a folder, or the# additive copy below merges two parquet generations into one folder and the@@ -313,6 +450,7 @@ async def prepare_s3_files_for_querying(# 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.+ # The a/b slot folders end in a letter, so this pattern never selects them.query_folder_pattern = re.compile(rf"(?:^|.+/){re.escape(normalized_table_name)}\_\_query\_(\d+)(?:_[0-9a-f]{{8}})?\/?$")@@ -365,20 +503,25 @@ async def prepare_s3_files_for_querying(if await s3._exists(s3_path_for_querying):files_to_delete.append(s3_path_for_querying)- # Copy files concurrently with limited concurrency to avoid overwhelming S3- await _log(f"Copying {len(file_uris)} files to {s3_path_for_querying}")+ def relative_path(file: str) -> str:+ return file.replace(f"{s3_folder_for_schema}/", "")+ def pending_copies() -> list[str]:+ if standby_files is None:+ return list(file_uris)+ return [file for file in file_uris if relative_path(file) not in standby_files]++ # Copy files concurrently with limited concurrency to avoid overwhelming S3semaphore = asyncio.Semaphore(50)async def copy_file(file: str) -> None:async with semaphore:- file_name = file.replace(f"{s3_folder_for_schema}/", "")# _cp_file() copies a single known source to a known destination key directly.# The generic _copy() also globs the source and probes whether the destination# 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}/{file_name}")+ await s3._cp_file(file, f"{s3_path_for_querying}/{relative_path(file)}")import deltalake.exceptions # noqa: PLC0415 — keeps the heavy deltalake dep off this module's top-level import path@@ -392,8 +535,10 @@ async def prepare_s3_files_for_querying(attempt = 0while True:attempt += 1+ files_to_copy = pending_copies()+ await _log(f"Copying {len(files_to_copy)} of {len(file_uris)} files to {s3_path_for_querying}")try:- await asyncio.gather(*[copy_file(file) for file in file_uris])+ await asyncio.gather(*[copy_file(file) for file in files_to_copy])breakexcept FileNotFoundError as e:if refresh_file_uris is None or attempt >= _COPY_FILES_MAX_ATTEMPTS:@@ -451,6 +596,13 @@ async def prepare_s3_files_for_querying()await asyncio.sleep(2**attempt)+ if standby_files is not None:+ live_relative_paths = {relative_path(file) for file in file_uris}+ stale_files = [uri for relative, uri in standby_files.items() if relative not in live_relative_paths]+ if stale_files:+ await _log(f"Removing {len(stale_files)} files no longer live from {s3_path_for_querying}")+ await _delete_stale_standby_files(s3, stale_files, _log)+# Delete existing files after copying new onesif delete_existing and files_to_delete:await _log(f"Deleting {len(files_to_delete)} old query folders")diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.pyindex 80532fb74163..a553c121efd4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py@@ -26,9 +26,51 @@ class CalculateTableSizeActivityInputs:job_id: str+def _delta_table_uri(schema: ExternalDataSchema, table: DataWarehouseTable) -> str:+ """Where the table's Delta log lives.++ The query folder is named `<delta folder leaf>__query[...]`, so the leaf comes from the pointer+ when there is one: a `cdc_only` schema's table is its `_cdc` companion, whose Delta folder is not+ the schema's own.+ """+ if table.queryable_folder:+ leaf = table.queryable_folder.rsplit("__query", 1)[0]+ else:+ leaf = schema.normalized_s3_folder_name+ return f"{settings.BUCKET_URL}/{schema.folder_path()}/{leaf}"+++def _live_delta_size_mib(delta_uri: str) -> float | None:+ """Total size of the files the Delta log lists as live, in MiB.++ The query folder holds a copy of exactly those files, so this is the number an S3 listing of+ that folder gives, without paging through every object. None when no Delta log exists there,+ so the caller can fall back to listing.+ """+ import pyarrow as pa # noqa: PLC0415 — keeps the heavy pyarrow dep off this activity module's import path+ import deltalake # noqa: PLC0415 — keeps the heavy deltalake dep off this activity module's import path+ import pyarrow.compute as pc # noqa: PLC0415 — keeps the heavy pyarrow dep off this activity module's import path+ import deltalake.exceptions # noqa: PLC0415 — keeps the heavy deltalake dep off this activity module's import path++ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import ( # noqa: PLC0415 — keeps the heavy deltalake dep off this activity module's import path+ delta_storage_options,+ )++ try:+ delta_table = deltalake.DeltaTable(delta_uri, storage_options=delta_storage_options())+ except deltalake.exceptions.TableNotFoundError:+ return None++ # deltalake>=1.x returns an arro3 RecordBatch; pa.table() normalizes it through the Arrow C interface.+ add_actions = pa.table(delta_table.get_add_actions(flatten=True))+ total_bytes = pc.sum(add_actions.column("size_bytes")).as_py() or 0+ return total_bytes / (1024 * 1024)++# The individual queries carry `retry_internal_db_operation` rather than the whole activity-# carrying `with_internal_db_retries`, because retrying the whole body would repeat the S3 folder-# listing below, which can take minutes and still has to finish inside the activity's timeout.+# carrying `with_internal_db_retries`, because retrying the whole body would repeat the size+# measurement below, which for the S3 listing fallback can take minutes and still has to finish+# inside the activity's timeout.@activity.defndef calculate_table_size_activity(inputs: CalculateTableSizeActivityInputs) -> None:bind_contextvars(team_id=inputs.team_id)@@ -70,7 +112,11 @@ def calculate_table_size_activity(inputs: CalculateTableSizeActivityInputs) -> Ns3_folder = f"{settings.BUCKET_URL}/{folder_name}/{schema.normalized_name}"try:- total_mib = get_size_of_folder(s3_folder)+ total_mib: float | None = None+ if table.format == DataWarehouseTable.TableFormat.DeltaS3Wrapper:+ total_mib = _live_delta_size_mib(_delta_table_uri(schema, table))+ if total_mib is None:+ total_mib = get_size_of_folder(s3_folder)except OSError as e:if e.errno not in (errno.EMFILE, errno.ENFILE):raisediff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_calculate_table_size.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_calculate_table_size.pyindex 7d785d8e3d23..3452be707808 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_calculate_table_size.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_calculate_table_size.py@@ -1,8 +1,15 @@import errno+from pathlib import Path+from typing import NamedTuple, castimport pytestfrom unittest.mock import patch+from django.test import override_settings++import pyarrow as pa+import deltalake+from posthog.models import Organization, Teamfrom posthog.temporal.common.errors import NonReportableError@@ -16,17 +23,28 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitiecalculate_table_size_activity,)+_DELTA_TABLE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table"+def _team() -> Team:return Team.objects.create(organization=Organization.objects.create(name="org"), name="t")-def _schema_table_job(team: Team) -> tuple[ExternalDataSchema, DataWarehouseTable, ExternalDataJob]:+class _SchemaTableJob(NamedTuple):+ schema: ExternalDataSchema+ table: DataWarehouseTable+ job: ExternalDataJob+++def _schema_table_job(+ team: Team, *, table_format: str = "Parquet", queryable_folder: str | None = None+) -> _SchemaTableJob:table = DataWarehouseTable(name="stripe_charge",- format="Parquet",+ format=table_format,team=team,url_pattern="https://posthog-owned.example/team/stripe_charge",+ queryable_folder=queryable_folder,)table.save(internally_computed_url_pattern=True)source = ExternalDataSource.objects.create(source_id="src", connection_id="conn", team=team, source_type="Stripe")@@ -34,7 +52,7 @@ def _schema_table_job(team: Team) -> tuple[ExternalDataSchema, DataWarehouseTabljob = ExternalDataJob.objects.create(team=team, pipeline=source, schema=schema, status=ExternalDataJob.Status.COMPLETED)- return schema, table, job+ return _SchemaTableJob(schema, table, job)# transaction=True: the activity calls close_old_connections(), which breaks the atomic wrapper@@ -113,3 +131,59 @@ class TestCalculateTableSizeActivity:CalculateTableSizeActivityInputs(team_id=team.id, schema_id=str(schema.id), job_id=str(job.id)))assert not isinstance(exc_info.value, NonReportableError)++ def test_reads_the_size_of_the_live_files_from_the_delta_log(self, tmp_path: Path) -> None:+ # An S3 listing of the query folder pages through every object and takes minutes on a large+ # table. The Delta log already carries the size of each live file, and the query folder holds+ # exactly those files, so the two numbers agree. Regression: counting files the log no longer+ # lists (an overwritten generation still on disk) would inflate the size.+ team = _team()+ schema, table, job = _schema_table_job(+ team, table_format="DeltaS3Wrapper", queryable_folder="stripe_charge__query_a"+ )+ delta_dir = tmp_path / schema.folder_path() / "stripe_charge"+ deltalake.write_deltalake(str(delta_dir), pa.table({"amount": list(range(2000))}))+ deltalake.write_deltalake(str(delta_dir), pa.table({"amount": [1, 2, 3]}), mode="overwrite")+ live_bytes = sum(+ cast(+ list[int],+ pa.table(deltalake.DeltaTable(str(delta_dir)).get_add_actions(flatten=True))+ .column("size_bytes")+ .to_pylist(),+ )+ )+ all_bytes = sum(path.stat().st_size for path in delta_dir.glob("*.parquet"))+ assert all_bytes > live_bytes++ with (+ override_settings(BUCKET_URL=str(tmp_path)),+ patch.object(calc, "get_size_of_folder", side_effect=AssertionError("must not list S3")),+ patch(f"{_DELTA_TABLE_MODULE}.delta_storage_options", return_value={}),+ ):+ calculate_table_size_activity(+ CalculateTableSizeActivityInputs(team_id=team.id, schema_id=str(schema.id), job_id=str(job.id))+ )++ table.refresh_from_db()+ assert table.size_in_s3_mib == live_bytes / (1024 * 1024)++ def test_falls_back_to_listing_when_there_is_no_delta_log(self, tmp_path: Path) -> None:+ # A DeltaS3Wrapper table whose folder holds no `_delta_log` (a legacy layout) must keep the+ # size the listing gives instead of recording zero.+ team = _team()+ schema, table, job = _schema_table_job(+ team, table_format="DeltaS3Wrapper", queryable_folder="stripe_charge__query_a"+ )++ with (+ override_settings(BUCKET_URL=str(tmp_path)),+ patch.object(calc, "get_size_of_folder", return_value=3.5) as listing,+ patch(f"{_DELTA_TABLE_MODULE}.delta_storage_options", return_value={}),+ ):+ calculate_table_size_activity(+ CalculateTableSizeActivityInputs(team_id=team.id, schema_id=str(schema.id), job_id=str(job.id))+ )++ listing.assert_called_once_with(f"{tmp_path}/{schema.folder_path()}/stripe_charge__query_a")+ table.refresh_from_db()+ assert table.size_in_s3_mib == 3.5