Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): time each loader batch step and reuse the table handle (#113412)

Tom Owersa88e8d212087
diff --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.py
index dbc83b131ca9..271620622644 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
@@ -353,6 +353,26 @@ class DeltaTableRef:
self._known_missing = False
self._expect_missing = False
+ async def adopt_open_table(self, table: deltalake.DeltaTable) -> bool:
+ """Take a handle that an earlier ref opened on this table, in place of a new open.
+
+ The handle first reads the commits that landed since its last use, which is one log listing
+ and one read for each new commit. A commit from another writer is thus in the snapshot before
+ any caller reads it. Returns False and keeps nothing when that read fails, so the next
+ `get_delta_table` opens the table and classifies the error as it always did.
+
+ Only for a caller that knows the table was not replaced under this URI since the handle was
+ last used: an incremental read cannot tell a new table from the old one.
+ """
+ try:
+ await asyncio.to_thread(table.update_incremental)
+ except Exception:
+ return False
+ self._cached_table = table
+ self._cached_table_stale = False
+ self._known_missing = False
+ return True
+
async def _refresh_cached_table(self, table: deltalake.DeltaTable) -> None:
try:
await asyncio.to_thread(table.update_incremental)
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.py
index 502bda9d0b7f..555414797660 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
@@ -172,6 +172,39 @@ class TestGetDeltaTableCache:
mock_delta_table.assert_not_called()
+class TestAdoptOpenTable:
+ @pytest.mark.asyncio
+ async def test_an_adopted_handle_reads_the_commits_it_missed(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ deltalake.write_deltalake(tmp, pa.table({"id": [1]}))
+ earlier_handle = deltalake.DeltaTable(tmp)
+ deltalake.write_deltalake(tmp, pa.table({"id": [2]}), mode="append")
+ table_ref = make_local_table_ref(tmp)
+
+ with patch.object(deltalake, "DeltaTable", wraps=deltalake.DeltaTable) as opens:
+ assert await table_ref.adopt_open_table(earlier_handle) is True
+ adopted = await table_ref.get_delta_table()
+
+ assert adopted is earlier_handle
+ assert opens.call_count == 0
+ assert adopted.version() == 1
+ assert len(adopted.file_uris()) == 2
+
+ @pytest.mark.asyncio
+ async def test_a_handle_that_cannot_catch_up_is_not_kept(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ deltalake.write_deltalake(tmp, pa.table({"id": [1]}))
+ earlier_handle = MagicMock()
+ earlier_handle.update_incremental.side_effect = deltalake.exceptions.DeltaError("log is gone")
+ table_ref = make_local_table_ref(tmp)
+
+ assert await table_ref.adopt_open_table(earlier_handle) is False
+ opened = await table_ref.get_delta_table()
+
+ assert opened is not None and opened is not earlier_handle
+ assert opened.version() == 0
+
+
def _no_table(path: Path) -> None:
pass
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/batch_steps.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/batch_steps.py
new file mode 100644
index 000000000000..83df44d4152b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/batch_steps.py
@@ -0,0 +1,44 @@
+import time
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
+ BATCH_STEP_DURATION_SECONDS,
+)
+
+BatchStep = Literal[
+ "job_load",
+ "idempotency_check",
+ "deliver",
+ "parquet_read",
+ "table_open",
+ "table_refresh",
+ "partition",
+ "cdc_resolve",
+ "schema_evolve",
+ "ownership_check",
+ "write",
+ "mark_processed",
+ "post_write",
+]
+
+
+class BatchStepTimer:
+ """Wall-clock time of each step of one batch load, for the batch's log line and a histogram."""
+
+ def __init__(self) -> None:
+ self._seconds: dict[str, float] = {}
+
+ @contextmanager
+ def step(self, name: BatchStep) -> Iterator[None]:
+ started = time.perf_counter()
+ try:
+ yield
+ finally:
+ elapsed = time.perf_counter() - started
+ self._seconds[name] = self._seconds.get(name, 0.0) + elapsed
+ BATCH_STEP_DURATION_SECONDS.labels(step=name).observe(elapsed)
+
+ def log_fields(self) -> dict[str, int]:
+ return {f"{name}_ms": round(seconds * 1000) for name, seconds in self._seconds.items()}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
index 2fd0faec4abd..65c120140c42 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
@@ -25,6 +25,15 @@ PARQUET_READ_DURATION_SECONDS = Histogram(
buckets=(0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0),
)
+# One series for each step and no team or schema label: every batch of every table observes each
+# step, so a tenant label would multiply the series by the number of schemas.
+BATCH_STEP_DURATION_SECONDS = Histogram(
+ "warehouse_load_batch_step_duration_seconds",
+ "Duration of one step of a batch load, by step",
+ labelnames=["step"],
+ buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0),
+)
+
# TODO: the `team_id`/`schema_id` labels below are high cardinality — keep only for the gated rollout
# so we can debug per-team behaviour, then drop them before fully rolling out (per-team diagnosability
# is also covered by the `warehouse_repartition_*` capture events).
diff --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.py
index 5800cdef3820..b4a86b2b531f 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
@@ -77,6 +77,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
runs_in_order,
set_violation,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.batch_steps import (
+ BatchStepTimer,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.idempotency import (
is_batch_already_processed,
mark_batch_as_processed,
@@ -89,6 +92,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
IDEMPOTENCY_HIT_TOTAL,
PARQUET_READ_DURATION_SECONDS,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.table_handles import (
+ GROUP_TABLE_HANDLES,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import (
ExportSignalMessage,
SyncTypeLiteral,
@@ -1076,6 +1082,10 @@ def _process_message_reported(
# Reconnect stale app-DB connections up front so the ORM queries below don't burn all batch attempts.
close_old_connections()
+ timer = BatchStepTimer()
+ # Taken before any step that can raise, so a batch that fails leaves no handle for its retry.
+ retained_table = GROUP_TABLE_HANDLES.take(export_signal, attempt=attempt)
+
# 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
@@ -1091,7 +1101,8 @@ def _process_message_reported(
# delta-history fallback when the Redis dedup flag is missing — the case
# where the writer crashed between `DeltaWriter.write` committing and
# `mark_batch_as_processed` being called.
- job = _load_job(export_signal.job_id)
+ with timer.step("job_load"):
+ job = _load_job(export_signal.job_id)
schema = job.schema
if schema is None:
raise ValueError(f"ExternalDataJob {export_signal.job_id} has no schema")
@@ -1111,36 +1122,38 @@ def _process_message_reported(
_process_external_destinations_only(export_signal, verify_ownership)
return
- 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 run_uuid, index in members:
- if is_batch_already_processed(
+ with timer.step("idempotency_check"):
+ 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 run_uuid, index in members:
+ if is_batch_already_processed(
+ export_signal.team_id,
+ export_signal.schema_id,
+ run_uuid,
+ index,
+ delta_table_ref=delta_table_ref,
+ is_first_attempt=attempt <= 1,
+ ):
+ raise CoalescingDeclined(f"batch {index} of run {run_uuid} was already processed")
+ already_processed = False
+ else:
+ already_processed = is_batch_already_processed(
export_signal.team_id,
export_signal.schema_id,
- run_uuid,
- index,
+ export_signal.run_uuid,
+ export_signal.batch_index,
delta_table_ref=delta_table_ref,
is_first_attempt=attempt <= 1,
- ):
- raise CoalescingDeclined(f"batch {index} of run {run_uuid} 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
# the warehouse's marker would strand a destination that failed, and gating publication
# on the write marker would leave a full refresh staged and never swapped in.
report_phase("deliver")
- deliver_batch_to_destinations(export_signal)
+ with timer.step("deliver"):
+ deliver_batch_to_destinations(export_signal)
if already_processed and not export_signal.is_final_batch:
IDEMPOTENCY_HIT_TOTAL.labels(team_id=team_id_str, schema_id=schema_id_str).inc()
@@ -1185,8 +1198,11 @@ def _process_message_reported(
sync_type=export_signal.sync_type,
)
+ primary_keys = export_signal.primary_keys
+ cdc_write_mode = export_signal.cdc_write_mode
+
report_phase("read")
- with PARQUET_READ_DURATION_SECONDS.time():
+ with timer.step("parquet_read"), PARQUET_READ_DURATION_SECONDS.time():
if constituents is not None:
pa_table = _read_constituents(constituents)
else:
@@ -1201,9 +1217,19 @@ def _process_message_reported(
column_names=pa_table.column_names,
)
- existing_delta_table = async_to_sync(delta_table_ref.get_delta_table)()
+ table_handle_reused = False
+ if retained_table is not None and cdc_write_mode is None:
+ with timer.step("table_refresh"):
+ table_handle_reused = async_to_sync(delta_table_ref.adopt_open_table)(retained_table)
+ retained_table = None
+ if table_handle_reused:
+ existing_delta_table = async_to_sync(delta_table_ref.get_delta_table)()
+ else:
+ with timer.step("table_open"):
+ existing_delta_table = async_to_sync(delta_table_ref.get_delta_table)()
- pa_table = _apply_partitioning(export_signal, pa_table, existing_delta_table, schema)
+ with timer.step("partition"):
+ pa_table = _apply_partitioning(export_signal, pa_table, existing_delta_table, schema)
# Capture file URIs before write for partial data loading. The listing is O(files in
# table), so skip it entirely when no consumer wants it — during a long first sync the
@@ -1214,8 +1240,6 @@ def _process_message_reported(
else []
)
- primary_keys = export_signal.primary_keys
- cdc_write_mode = export_signal.cdc_write_mode
deltalite_file_count_change: int | None = None
# Tag every delta commit with (run_uuid, batch_index) so that a redelivery after a writer
@@ -1234,43 +1258,46 @@ def _process_message_reported(
resolution_enabled = cdc_write_mode is not None
- pa_table = _enrich_cdc_rows(
- pa_table,
- primary_keys=primary_keys,
- cdc_write_mode=cdc_write_mode,
- existing_delta_table=existing_delta_table,
- batch_index=export_signal.batch_index,
- verify_deletes=resolution_enabled,
- team_id=team_id_str,
- )
-
- if resolution_enabled:
- pa_table = _resolve_cdc_positions(
+ with timer.step("cdc_resolve"):
+ pa_table = _enrich_cdc_rows(
pa_table,
- primary_keys=primary_keys or [],
+ primary_keys=primary_keys,
cdc_write_mode=cdc_write_mode,
+ existing_delta_table=existing_delta_table,
+ batch_index=export_signal.batch_index,
+ verify_deletes=resolution_enabled,
team_id=team_id_str,
)
- if existing_delta_table is not None:
- try:
- pa_table = evolve_pyarrow_schema(
+ if resolution_enabled:
+ pa_table = _resolve_cdc_positions(
pa_table,
- existing_delta_table.schema(),
- merge_key_columns=[*(primary_keys or []), *(export_signal.partition_keys or [])],
+ primary_keys=primary_keys or [],
+ cdc_write_mode=cdc_write_mode,
+ team_id=team_id_str,
)
- except SchemaColumnTypeChangedException as e:
- # A safe numeric widening is mechanically recoverable: stamp reset_pipeline so the
- # next scheduled sync resets and re-syncs the table, and reword the failure so
- # latest_error stops telling the customer to reset manually. Unsafe transitions
- # (and everything with the flag off) re-raise unchanged.
- amended_message = maybe_schedule_auto_widen_resync(schema=schema, job=job, error=e)
- if amended_message is not None:
- e.args = (amended_message,)
- raise
+
+ if existing_delta_table is not None:
+ with timer.step("schema_evolve"):
+ try:
+ pa_table = evolve_pyarrow_schema(
+ pa_table,
+ existing_delta_table.schema(),
+ merge_key_columns=[*(primary_keys or []), *(export_signal.partition_keys or [])],
+ )
+ except SchemaColumnTypeChangedException as e:
+ # A safe numeric widening is mechanically recoverable: stamp reset_pipeline so the
+ # next scheduled sync resets and re-syncs the table, and reword the failure so
+ # latest_error stops telling the customer to reset manually. Unsafe transitions
+ # (and everything with the flag off) re-raise unchanged.
+ amended_message = maybe_schedule_auto_widen_resync(schema=schema, job=job, error=e)
+ if amended_message is not None:
+ e.args = (amended_message,)
+ raise
if verify_ownership is not None:
- verify_ownership()
+ with timer.step("ownership_check"):
+ verify_ownership()
# The writer narrows this to `merge` for an upsert; an append stays `write` to its commit.
report_phase("write")
@@ -1281,9 +1308,12 @@ def _process_message_reported(
batch_index=export_signal.batch_index,
)
- with DELTA_WRITE_DURATION_SECONDS.labels(
- team_id=team_id_str, schema_id=schema_id_str, write_type="scd2_append"
- ).time():
+ with (
+ timer.step("write"),
+ DELTA_WRITE_DURATION_SECONDS.labels(
+ team_id=team_id_str, schema_id=schema_id_str, write_type="scd2_append"
+ ).time(),
+ ):
scd2_writer = Scd2DeltaWriter(
delta_table_ref,
valid_from_column=SCD2_VALID_FROM_COLUMN,
@@ -1308,9 +1338,12 @@ def _process_message_reported(
batch_index=export_signal.batch_index,
)
- with DELTA_WRITE_DURATION_SECONDS.labels(
- team_id=team_id_str, schema_id=schema_id_str, write_type=write_type
- ).time():
+ with (
+ timer.step("write"),
+ DELTA_WRITE_DURATION_SECONDS.labels(
+ team_id=team_id_str, schema_id=schema_id_str, write_type=write_type
+ ).time(),
+ ):
delta_writer = DeltaWriter(delta_table_ref)
delta_table = async_to_sync(delta_writer.write)(
data=pa_table,
@@ -1327,8 +1360,9 @@ def _process_message_reported(
# 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 run_uuid, index in members:
- mark_batch_as_processed(export_signal.team_id, export_signal.schema_id, run_uuid, index)
+ with timer.step("mark_processed"):
+ for run_uuid, index in members:
+ mark_batch_as_processed(export_signal.team_id, export_signal.schema_id, run_uuid, index)
# file_count is the signal that shows a table fragmenting during a long load, so it stays —
# but listing every file costs O(files in table), which is the very thing it measures. Sample
@@ -1345,18 +1379,19 @@ def _process_message_reported(
# can, so the readers of one go through the ref, which catches the handle up first. The
# sampled count needs that read only when the commit's own numbers cannot give it: batch 0
# is a sample, so the read would otherwise cost each run a log listing.
- if (sample_file_count and file_count is None) or _partial_data_loading_applies(export_signal, schema):
- current_delta_table = async_to_sync(delta_table_ref.get_delta_table)()
- if current_delta_table is not None:
- delta_table = current_delta_table
- if sample_file_count and file_count is None:
- file_count = len(delta_table.file_uris())
-
- 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.
- internal_schema.add_pyarrow_schema(pyarrow_schema_from_arrow_exportable(delta_table.schema()))
- internal_schema.add_pyarrow_table(pa_table)
+ with timer.step("post_write"):
+ if (sample_file_count and file_count is None) or _partial_data_loading_applies(export_signal, schema):
+ current_delta_table = async_to_sync(delta_table_ref.get_delta_table)()
+ if current_delta_table is not None:
+ delta_table = current_delta_table
+ if sample_file_count and file_count is None:
+ file_count = len(delta_table.file_uris())
+
+ 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.
+ internal_schema.add_pyarrow_schema(pyarrow_schema_from_arrow_exportable(delta_table.schema()))
+ internal_schema.add_pyarrow_table(pa_table)
logger.debug(
"batch_written_to_delta_lake",
@@ -1364,6 +1399,8 @@ def _process_message_reported(
batch_count=len(members),
delta_version=delta_table_ref.latest_known_version(delta_table),
file_count=file_count,
+ table_handle="reused" if table_handle_reused else "opened",
+ **timer.log_fields(),
)
async_to_sync(_handle_partial_data_loading)(
@@ -1397,6 +1434,15 @@ def _process_message_reported(
internal_schema=internal_schema,
verify_ownership=verify_ownership,
)
+
+ # A run that completed here ran its post-load maintenance, and the next run can reset the
+ # table, so only a write that stays inside one unfinished run hands its handle on.
+ if not finals and cdc_write_mode is None and all(run_uuid == export_signal.run_uuid for run_uuid, _ in members):
+ open_table = delta_table_ref.pop_cached_table()
+ if open_table is not None:
+ GROUP_TABLE_HANDLES.retain(
+ export_signal, open_table, last_batch_index=max(index for _, index in members)
+ )
except OwnershipLostError:
# Benign fencing abandon: the engine re-raises this without writing a
# failure status, so it must not count as a load failure in analytics either.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/table_handles.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/table_handles.py
new file mode 100644
index 000000000000..20044e6aeb16
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/table_handles.py
@@ -0,0 +1,116 @@
+"""Open delta-rs handles that the loader keeps between consecutive batches of one run.
+
+A delta-rs open of a table reads the last checkpoint and every commit after it, which is one
+listing and tens of reads against object storage, plus the snapshot build. The loader makes a new
+`DeltaTableRef` for each batch, so without this module each batch pays that open again for a table
+the same thread wrote a moment ago.
+
+A handle is kept only for the next batch of the same run in the same group, and it catches up with
+one incremental log read before any caller reads it (see `DeltaTableRef.adopt_open_table`). Every
+other batch opens the table: the first batch of a group run, batch 0, a redelivery, a batch of
+another run, and the batch after any failure. The steps that replace a table under its URI (a
+reset, a repartition swap, a corruption revive) run before a run stages its first batch, so the
+table cannot be replaced between two batches that this rule joins.
+"""
+
+import time
+import threading
+from collections.abc import Callable
+
+import deltalake
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
+
+# A handle that waited longer than this for its next batch is released. Consecutive batches of one
+# group run follow each other at once, so a longer wait means the group run ended without a release.
+RETAINED_HANDLE_MAX_IDLE_SECONDS = 60.0
+
+
+@frozen
+class _RetainedHandle:
+ table: deltalake.DeltaTable
+ job_id: str
+ run_uuid: str
+ resource_name: str
+ last_batch_index: int
+ retained_at: float
+
+
+class GroupTableHandles:
+ """At most one retained handle for each (team, schema) group, safe to share across worker threads.
+
+ The queue runs one batch of a group at a time, so the number of retained handles never exceeds
+ the number of groups in flight, which is also the number of handles open without this class.
+ """
+
+ def __init__(
+ self,
+ *,
+ max_idle_seconds: float = RETAINED_HANDLE_MAX_IDLE_SECONDS,
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self._max_idle_seconds = max_idle_seconds
+ self._clock = clock
+ self._lock = threading.Lock()
+ self._handles: dict[tuple[int, str], _RetainedHandle] = {}
+
+ def __len__(self) -> int:
+ with self._lock:
+ return len(self._handles)
+
+ def take(self, export_signal: ExportSignalMessage, *, attempt: int) -> deltalake.DeltaTable | None:
+ """Remove the group's handle and return it when this batch is the one it was kept for.
+
+ The handle leaves the registry in every case. A batch that fails thus leaves nothing
+ behind, and its retry opens the table.
+ """
+ with self._lock:
+ self._release_idle()
+ retained = self._handles.pop(_group_key(export_signal), None)
+ if retained is None or attempt > 1:
+ return None
+ if (
+ retained.job_id != export_signal.job_id
+ or retained.run_uuid != export_signal.run_uuid
+ or retained.resource_name != export_signal.resource_name
+ or export_signal.batch_index != retained.last_batch_index + 1
+ ):
+ return None
+ return retained.table
+
+ def retain(self, export_signal: ExportSignalMessage, table: deltalake.DeltaTable, *, last_batch_index: int) -> None:
+ """Keep `table` for the batch that follows `last_batch_index` in the same run."""
+ with self._lock:
+ self._release_idle()
+ self._handles[_group_key(export_signal)] = _RetainedHandle(
+ table=table,
+ job_id=export_signal.job_id,
+ run_uuid=export_signal.run_uuid,
+ resource_name=export_signal.resource_name,
+ last_batch_index=last_batch_index,
+ retained_at=self._clock(),
+ )
+
+ def release(self, team_id: int, schema_id: str) -> None:
+ with self._lock:
+ self._handles.pop((team_id, str(schema_id)), None)
+
+ def _release_idle(self) -> None:
+ now = self._clock()
+ for key, retained in list(self._handles.items()):
+ if now - retained.retained_at > self._max_idle_seconds:
+ del self._handles[key]
+
+
+def _group_key(export_signal: ExportSignalMessage) -> tuple[int, str]:
+ return export_signal.team_id, str(export_signal.schema_id)
+
+
+GROUP_TABLE_HANDLES = GroupTableHandles()
+
+
+def release_group_table_handle(team_id: int, schema_id: str) -> None:
+ """Release the handle of a group whose run on this process ended."""
+ GROUP_TABLE_HANDLES.release(team_id, schema_id)
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.py
index f43614b3dad7..5c385675eb6b 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
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import PostLoadResult
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.table import DeltaTableRef
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (
make_local_table_ref,
)
@@ -47,6 +48,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
process_message,
process_messages,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.table_handles import (
+ GroupTableHandles,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.test_mocks import mock_delta_table
from products.warehouse_sources_queue.backend.core.batch_consumer import CoalescingDeclined
@@ -62,6 +66,17 @@ def _no_close_old_connections():
yield
[email protected](autouse=True)
+def _table_handles() -> Iterator[GroupTableHandles]:
+ # The loader's registry is process-wide, so a handle that one test left would reach the next.
+ handles = GroupTableHandles()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.GROUP_TABLE_HANDLES",
+ handles,
+ ):
+ yield handles
+
+
class TestGetWriteType:
@parameterized.expand(
[
@@ -1632,3 +1647,190 @@ class TestBatchPhaseReports:
assert [call.args[0] for call in mock_report_phase.call_args_list] == ["deliver", "post_load", "finalize"]
assert _post_load_summary(mock_logger)["phase_names"] == ["job_completion", "post_import_trigger"]
+
+
+def _batch_rows(index: int) -> pa.Table:
+ # Each batch updates one row of the batch before it and adds two rows.
+ ids = [index * 2, index * 2 + 1, index * 2 + 2]
+ return pa.table({"id": ids, "name": [f"batch_{index}_{row_id}" for row_id in ids]})
+
+
+def _data_commits(table_path: str) -> list[tuple[str, str | None]]:
+ commits = [commit for commit in DeltaTable(table_path).history() if commit["operation"] != "SET TBLPROPERTIES"]
+ return [(commit["operation"], commit.get("batch_index")) for commit in reversed(commits)]
+
+
+class TestTableHandleReuse:
+ _SEED = pa.table({"id": [0, 1], "name": ["seed_0", "seed_1"]})
+
+ @contextmanager
+ def _loader(self, table_path: str, opens: list[int]) -> Iterator[None]:
+ open_table = DeltaTableRef._open_delta_table
+
+ async def counted_open(ref: DeltaTableRef) -> DeltaTable | None:
+ opens.append(1)
+ return await open_table(ref)
+
+ with ExitStack() as stack:
+ stack.enter_context(patch(f"{_PROCESSOR}.posthoganalytics"))
+ stack.enter_context(patch(f"{_PROCESSOR}.mark_batch_as_processed"))
+ stack.enter_context(patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False))
+ stack.enter_context(
+ patch(f"{_PROCESSOR}.read_parquet", side_effect=lambda path: _batch_rows(int(path.rsplit("/", 1)[1])))
+ )
+ stack.enter_context(
+ patch(f"{_PROCESSOR}.DeltaTableRef", side_effect=lambda **kwargs: make_local_table_ref(table_path))
+ )
+ stack.enter_context(patch.object(DeltaTableRef, "_open_delta_table", counted_open))
+ stack.enter_context(
+ patch(f"{_PROCESSOR}.run_post_load_operations", new=AsyncMock(return_value=_POST_LOAD_RESULT))
+ )
+ stack.enter_context(patch(f"{_PROCESSOR}._complete_run"))
+ job_model = stack.enter_context(patch(f"{_PROCESSOR}.ExternalDataJob"))
+ job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()
+ yield
+
+ @staticmethod
+ def _batch(index: int, **overrides: Any) -> dict[str, Any]:
+ return _message(**{"batch_index": index, "s3_path": f"s3://bucket/run-1/{index}", **overrides})
+
+ @parameterized.expand(
+ [
+ ("append", "append", 1),
+ ("merge", "incremental", 1),
+ ("full_refresh", "full_refresh", 0),
+ ]
+ )
+ def test_reuse_gives_the_table_and_the_commits_of_an_open_per_batch(
+ self, _name: str, sync_type: str, first_index: int
+ ) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ reused_path, opened_path = f"{tmp}/reused", f"{tmp}/opened"
+ reused_opens: list[int] = []
+ opened_opens: list[int] = []
+ for table_path, opens, reuse in ((reused_path, reused_opens, True), (opened_path, opened_opens, False)):
+ write_deltalake(table_path, self._SEED)
+ with ExitStack() as stack:
+ stack.enter_context(self._loader(table_path, opens))
+ if not reuse:
+ stack.enter_context(patch.object(GroupTableHandles, "take", return_value=None))
+ for index in range(first_index, first_index + 4):
+ process_message(self._batch(index, sync_type=sync_type))
+
+ assert (len(reused_opens), len(opened_opens)) == (1, 4)
+ reused_rows = (
+ DeltaTable(reused_path).to_pyarrow_table().sort_by([("id", "ascending"), ("name", "ascending")])
+ )
+ opened_rows = (
+ DeltaTable(opened_path).to_pyarrow_table().sort_by([("id", "ascending"), ("name", "ascending")])
+ )
+ assert reused_rows.num_rows > self._SEED.num_rows
+ assert reused_rows.to_pydict() == opened_rows.to_pydict()
+ assert _data_commits(reused_path) == _data_commits(opened_path)
+
+ @parameterized.expand(
+ [
+ ("redelivery", {"attempt": 2}, {}),
+ ("another_run", {}, {"run_uuid": "run-2", "job_id": "job-2"}),
+ ("another_resource", {}, {"resource_name": "other"}),
+ ("batch_gap", {}, {"batch_index": 4}),
+ ("same_batch_again", {}, {"batch_index": 2}),
+ ("first_batch", {}, {"batch_index": 0, "is_resume": True}),
+ ]
+ )
+ def test_a_batch_the_handle_was_not_kept_for_opens_the_table(
+ self, _name: str, process_kwargs: dict[str, Any], overrides: dict[str, Any]
+ ) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ write_deltalake(tmp, self._SEED)
+ opens: list[int] = []
+ with self._loader(tmp, opens):
+ process_message(self._batch(2, sync_type="append"))
+ process_message(self._batch(3, sync_type="append", **overrides), **process_kwargs)
+
+ assert len(opens) == 2
+
+ @parameterized.expand(
+ [
+ ("lease_lost",),
+ ("read_failed",),
+ ("final_batch",),
+ ("group_run_ended",),
+ ("waited_too_long",),
+ ]
+ )
+ def test_the_handle_is_released(self, case: str) -> None:
+ now = [0.0]
+ handles = GroupTableHandles(max_idle_seconds=60.0, clock=lambda: now[0])
+
+ def lose_lease() -> None:
+ raise _LeaseLost()
+
+ with tempfile.TemporaryDirectory() as tmp, patch(f"{_PROCESSOR}.GROUP_TABLE_HANDLES", handles):
+ write_deltalake(tmp, self._SEED)
+ opens: list[int] = []
+ with self._loader(tmp, opens):
+ process_message(self._batch(2, sync_type="append"))
+ assert len(handles) == 1
+
+ if case == "lease_lost":
+ with pytest.raises(_LeaseLost):
+ process_message(self._batch(3, sync_type="append"), verify_ownership=lose_lease)
+ elif case == "read_failed":
+ with (
+ patch(f"{_PROCESSOR}.read_parquet", side_effect=OSError("read failed")),
+ pytest.raises(OSError),
+ ):
+ process_message(self._batch(3, sync_type="append"))
+ elif case == "final_batch":
+ process_message(self._batch(3, sync_type="append", is_final_batch=True, total_rows=6))
+ elif case == "group_run_ended":
+ handles.release(1, "schema-1")
+ else:
+ now[0] = 61.0
+ process_message(self._batch(9, sync_type="append", schema_id="schema-2"))
+ handles.release(1, "schema-2")
+
+ assert len(handles) == 0
+ opens_before = len(opens)
+ next_index = 4 if case == "final_batch" else 3
+ process_message(self._batch(next_index, sync_type="append"))
+
+ assert len(opens) == opens_before + 1
+
+ def test_a_commit_from_another_writer_is_in_the_reused_snapshot(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ write_deltalake(tmp, self._SEED)
+ opens: list[int] = []
+ seen_columns: list[list[str]] = []
+ apply_partitioning = _apply_partitioning
+
+ def record_snapshot(export_signal: Any, pa_table: pa.Table, existing: DeltaTable, schema: Any) -> pa.Table:
+ seen_columns.append([field.name for field in existing.schema().fields])
+ return apply_partitioning(export_signal, pa_table, existing, schema)
+
+ with (
+ self._loader(tmp, opens),
+ patch(f"{_PROCESSOR}._apply_partitioning", side_effect=record_snapshot),
+ patch(f"{_PROCESSOR}.logger") as mock_logger,
+ ):
+ process_message(self._batch(2, sync_type="append"))
+ write_deltalake(
+ tmp, pa.table({"id": [100], "name": ["other"], "added": ["x"]}), mode="append", schema_mode="merge"
+ )
+ process_message(self._batch(3, sync_type="append"))
+
+ assert len(opens) == 1
+ assert seen_columns == [["id", "name"], ["id", "name", "added"]]
+ written = [
+ call.kwargs
+ for call in mock_logger.debug.call_args_list
+ if call.args[0] == "batch_written_to_delta_lake"
+ ]
+ assert [fields["table_handle"] for fields in written] == ["opened", "reused"]
+ assert "table_open_ms" in written[0] and "table_refresh_ms" not in written[0]
+ assert "table_refresh_ms" in written[1] and "table_open_ms" not in written[1]
+ assert {"parquet_read_ms", "partition_ms", "schema_evolve_ms", "write_ms"} <= written[1].keys()
+ rows = DeltaTable(tmp).to_pyarrow_table()
+ assert rows.sort_by("id").column("id").to_pylist() == [0, 1, 4, 5, 6, 6, 7, 8, 100]
+ assert rows.schema.names == ["id", "name", "added"]
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.py
index 1dccbd37aecf..67654de72d39 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
@@ -44,6 +44,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (
DESTINATION_CONFIGURATION_ERROR_MARKER,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.table_handles import (
+ release_group_table_handle,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
release_v3_pipeline_lock,
@@ -1086,6 +1089,14 @@ class BatchConsumer(SharedBatchConsumer):
process_batches=process_set_with_ownership_check if process_batches is not None else None,
)
+ async def _process_group(self, key: tuple[int, str], batches: list[PendingBatch]) -> None:
+ try:
+ await super()._process_group(key, batches)
+ finally:
+ # The loader keeps the table handle of the last batch for the next batch of this group
+ # run. No batch follows now, so the handle must not hold its file list in memory.
+ release_group_table_handle(*key)
+
def _make_verify_ownership(self, batch: PendingBatch) -> Callable[[], None]:
"""Sync ownership check for the worker thread: the engine's lease checks bracket
the batch but can't see a loss mid-write. Fails closed — an unverified lease is lost."""
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.py
index 50a99e70cbb8..b678f2e44827 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
@@ -4,7 +4,7 @@ from datetime import UTC, datetime
from typing import Any, NamedTuple, cast
import pytest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.db import OperationalError as DjangoOperationalError
from django.test import override_settings
@@ -25,6 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
DestinationConfigurationError,
DestinationDeliveryError,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.table_handles import (
+ GROUP_TABLE_HANDLES,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue import (
consumer as consumer_module,
)
@@ -441,6 +445,9 @@ class TestProcessGroup:
consumer._process_batch = AsyncMock(side_effect=RuntimeError("crash"))
batches = [_make_batch()]
+ GROUP_TABLE_HANDLES.retain(
+ ExportSignalMessage.from_dict(batches[0].to_export_signal()), MagicMock(), last_batch_index=0
+ )
with (
patch(
@@ -462,6 +469,7 @@ class TestProcessGroup:
await consumer._process_group((1, "schema-1"), batches)
mock_unlock.assert_called_once()
+ assert len(GROUP_TABLE_HANDLES) == 0
@pytest.mark.asyncio
async def test_halts_group_when_batch_does_not_succeed(self):