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.

perf(data-warehouse): faster deltalite probes and a lazy handle refresh (#107906)

Tom Owers0f61b474b1e4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py
index 6c384fa919c9..4774bdf32f4e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py
@@ -4,7 +4,8 @@ deltalite runs as Temporal activity threads inside a single worker process: ever
concurrent upsert — plus every delta-rs MERGE fallback and full-sync ``write_deltalake`` —
shares one address space and one cgroup memory limit. This governor decides, per upsert and
how large an upsert to run: it picks the per-call knobs
-(``max_parallel_partitions`` / ``max_parallel_files`` / ``max_buffered_bytes``) sized to a fixed
+(``max_parallel_partitions`` / ``max_parallel_files`` / ``max_buffered_bytes`` /
+``probe_concurrency``) sized to a fixed
per-upsert slice of pod memory. The slice is ``(pod limit × safety − reserve) / max_concurrent``,
so however many upserts run at once (up to the pod's ``MAX_CONCURRENT_ACTIVITIES``) their peaks sum
to less than the pod. deltalite therefore **always writes** — it never falls back to the delta-rs
@@ -32,6 +33,13 @@ memory dial) and the write buffers. So the only inputs that matter for sizing ar
batch size and how many partition workers we permit. The coefficients below mirror
``rust/deltalite/python/deltalite_planner.py`` and are conservative starting points — validate
against real load and re-fit if needed (the process-global backstop holds either way).
+
+Two knobs buy I/O overlap rather than memory: ``max_parallel_files`` (readers per partition
+worker) and ``probe_concurrency`` (PK-column probes per worker). deltalite budgets every decoded
+batch, probe or rewrite, against ``max_buffered_bytes``, so neither knob can push decoded bytes
+past that cap. The governor keeps ``max_parallel_partitions × max_parallel_files`` under the
+reader count of the largest plan the coefficients were measured on, and charges extra readers
+as worker-equivalents, so a plan never predicts less memory than the measured shape it exceeds.
"""
from __future__ import annotations
@@ -81,9 +89,24 @@ _MARGINAL_PER_WORKER_MB = 133.0
_MARGINAL_PER_SOURCE_MB = 0.73
#: Beyond 4 partition workers the measured wall-clock gains vanish while memory keeps climbing.
_MAX_PARALLEL_PARTITIONS = 4
-#: Per-call knobs the governor does not tune (mpp is the memory dial): deltalite's defaults, kept
-#: explicit so the write is deterministic.
-_MAX_PARALLEL_FILES = 4
+#: Concurrent file readers inside one partition worker, the shape the per-worker coefficient
+#: was measured at (deltalite's own default).
+_MEASURED_FILES_PER_WORKER = 4
+#: Readers a partition worker may run once the reader ceiling below allows it. The decoded
+#: survivor bytes stay under ``max_buffered_bytes`` whatever this is; what grows with it is the
+#: compressed row group each open reader holds, which the ceiling bounds.
+_MAX_PARALLEL_FILES = 8
+#: Ceiling on ``max_parallel_partitions × max_parallel_files`` for one upsert: the reader count of
+#: the largest plan the measured defaults could produce. A plan with more readers per worker
+#: therefore never holds more row groups in flight than the model was fitted on.
+_MAX_READERS_PER_UPSERT = _MAX_PARALLEL_PARTITIONS * _MEASURED_FILES_PER_WORKER
+#: Concurrent PK-column probes per partition worker. Each probe holds a Parquet footer and one
+#: decoded batch of the PK columns, and that batch takes byte-budget permits like a rewrite batch,
+#: so probe memory is capped by ``max_buffered_bytes`` at any concurrency. Insert-only batches
+#: into tables with many files are bound by probe round trips, and this overlaps them.
+_PROBE_CONCURRENCY = 32
+#: deltalite's default, kept explicit so the write is deterministic. The per-call cap on decoded
+#: bytes in flight; the reader and probe knobs above scale latency overlap, not this.
_DEFAULT_BUFFERED_BYTES = 64 * MB
@@ -98,40 +121,58 @@ class UpsertPlan:
predicted_peak_mb: float
#: False when even a single worker exceeds the available slice.
fits: bool
+ probe_concurrency: int = _PROBE_CONCURRENCY
def as_upsert_kwargs(self) -> dict[str, int]:
return {
"max_parallel_partitions": self.max_parallel_partitions,
"max_parallel_files": self.max_parallel_files,
"max_buffered_bytes": self.max_buffered_bytes,
+ "probe_concurrency": self.probe_concurrency,
}
-def _predict_marginal_mb(source_mb: float, mpp: int) -> float:
- """Marginal peak RSS one upsert adds while running concurrently (threaded model, REPORT §5.6)."""
- return _MARGINAL_BASE_MB + _MARGINAL_PER_WORKER_MB * mpp + _MARGINAL_PER_SOURCE_MB * source_mb
+def _files_per_worker(mpp: int) -> int:
+ """Readers per partition worker that keep the upsert under ``_MAX_READERS_PER_UPSERT``."""
+ return max(1, min(_MAX_PARALLEL_FILES, _MAX_READERS_PER_UPSERT // mpp))
+
+
+def _predict_marginal_mb(source_mb: float, mpp: int, files_per_worker: int = _MEASURED_FILES_PER_WORKER) -> float:
+ """Marginal peak RSS one upsert adds while running concurrently (threaded model, REPORT §5.6).
+
+ The per-worker coefficient was measured with ``_MEASURED_FILES_PER_WORKER`` readers, so a worker
+ that runs more readers is charged as that many worker-equivalents. That over-counts (a worker's
+ PK set and write buffer do not grow with its readers), which keeps the prediction conservative.
+ """
+ worker_equivalents = mpp * files_per_worker / _MEASURED_FILES_PER_WORKER
+ return _MARGINAL_BASE_MB + _MARGINAL_PER_WORKER_MB * worker_equivalents + _MARGINAL_PER_SOURCE_MB * source_mb
def size_upsert(available_mb: float, source_mb: float, n_partitions: int | None = None) -> UpsertPlan:
"""Pick the largest ``max_parallel_partitions`` whose marginal peak fits ``available_mb``.
``available_mb`` is the per-upsert memory slice, not the whole pod. Start at the cap and step
- down. If even a single worker exceeds the slice, return ``mpp=1`` with ``fits=False``. The caller
- does not fall back on ``fits=False`` — it runs deltalite at ``mpp=1`` anyway (still the memory
- floor, far below the MERGE) and flags ``capacity_exceeded``. mpp is the memory dial; the other
- knobs stay at deltalite's defaults.
+ down. Each step gets as many readers per worker as the reader ceiling allows, so an upsert with
+ few partitions overlaps more file reads without exceeding the in-flight readers of a full plan.
+ When no such plan fits, try one worker at the measured reader count; if even that exceeds the
+ slice, return it with ``fits=False``. The caller does not fall back on ``fits=False`` — it runs
+ deltalite at ``mpp=1`` anyway (still the memory floor, far below the MERGE) and flags
+ ``capacity_exceeded``.
"""
partition_cap = _MAX_PARALLEL_PARTITIONS
if n_partitions is not None and n_partitions >= 1:
partition_cap = min(partition_cap, n_partitions)
for mpp in range(partition_cap, 0, -1):
- predicted = _predict_marginal_mb(source_mb, mpp)
- if predicted <= available_mb:
- return UpsertPlan(mpp, _MAX_PARALLEL_FILES, _DEFAULT_BUFFERED_BYTES, round(predicted, 1), fits=True)
+ # Partition workers come first: a plan with more workers beats one with more readers per
+ # worker, so every plan the measured defaults could produce is still reachable.
+ for files in sorted({_files_per_worker(mpp), _MEASURED_FILES_PER_WORKER}, reverse=True):
+ predicted = _predict_marginal_mb(source_mb, mpp, files)
+ if predicted <= available_mb:
+ return UpsertPlan(mpp, files, _DEFAULT_BUFFERED_BYTES, round(predicted, 1), fits=True)
minimal = _predict_marginal_mb(source_mb, 1)
- return UpsertPlan(1, _MAX_PARALLEL_FILES, _DEFAULT_BUFFERED_BYTES, round(minimal, 1), fits=False)
+ return UpsertPlan(1, _MEASURED_FILES_PER_WORKER, _DEFAULT_BUFFERED_BYTES, round(minimal, 1), fits=False)
# --- Reading the pod's real memory (cgroup v2, with v1 and psutil fallbacks) -----------------
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 b32ad3e2eb52..7de69e30510f 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
@@ -164,6 +164,10 @@ class DeltaTableRef:
_logger: FilteringBoundLogger
_is_first_sync: bool
_cached_table: deltalake.DeltaTable | None
+ #: True while a deltalite commit has advanced the log past the cached handle's snapshot.
+ _cached_table_stale: bool
+ #: The newest version deltalite reported committing through this ref, if any.
+ _deltalite_version: int | None
_table_uri: str | None
def __init__(
@@ -174,6 +178,8 @@ class DeltaTableRef:
self._logger = logger
self._is_first_sync = is_first_sync
self._cached_table = None
+ self._cached_table_stale = False
+ self._deltalite_version = None
self._table_uri = None
@property
@@ -246,7 +252,7 @@ class DeltaTableRef:
raise TransientObjectStoreError(str(e)) from e
capture_exception(e)
- async def get_delta_table(self) -> deltalake.DeltaTable | None:
+ async def get_delta_table(self, *, allow_stale: bool = False) -> deltalake.DeltaTable | None:
"""Open the table once and hand back the same handle for the rest of this ref's life.
The cache is per instance on purpose. A process-wide slot lets any other table in flight on
@@ -254,29 +260,72 @@ class DeltaTableRef:
object storage. Writes through the handle keep it current, so it stays valid until this ref's
own `invalidate_cached_table` (reset, repartition swap) says otherwise. A missing table is
never cached, so a table created after the first probe is found by the next call.
+
+ A deltalite write commits past this handle (see `note_deltalite_commit`), after which the
+ cached snapshot is behind the log by that commit: same table id, same columns, same
+ partition layout, but an older version and file list. The handle catches up on the next call
+ with one incremental log read. `allow_stale` skips that read for a caller whose reads a
+ deltalite commit cannot change; anything that reads the version, the file list or the
+ per-file statistics must leave it False.
"""
if self._cached_table is not None:
+ if self._cached_table_stale and not allow_stale:
+ await self._refresh_cached_table(self._cached_table)
return self._cached_table
table = await self._open_delta_table()
self._cached_table = table
+ self._cached_table_stale = False
return table
+ async def _refresh_cached_table(self, table: deltalake.DeltaTable) -> None:
+ try:
+ await asyncio.to_thread(table.update_incremental)
+ except Exception as e:
+ # The handle stays marked, so the next reader tries again instead of reading a snapshot
+ # that is known to be behind.
+ await self._capture_unless_transient(e)
+ raise
+ self._cached_table_stale = False
+
+ def note_deltalite_commit(self, version: int | None) -> None:
+ """Record that deltalite committed `version` to this table outside the cached handle.
+
+ The cached delta-rs handle is marked behind the log until the next `get_delta_table` call
+ refreshes it. The version is kept so `latest_known_version` can report it in the meantime.
+ """
+ self._cached_table_stale = True
+ if version is not None and (self._deltalite_version is None or version > self._deltalite_version):
+ self._deltalite_version = version
+
+ def latest_known_version(self, delta_table: deltalake.DeltaTable) -> int:
+ """The newest version this ref knows the table reached: the handle's, or a later deltalite commit."""
+ version = delta_table.version()
+ if self._deltalite_version is not None and self._deltalite_version > version:
+ return self._deltalite_version
+ return version
+
def invalidate_cached_table(self) -> None:
"""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
+ self._forget_cached_table()
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."""
table = self._cached_table
- self._cached_table = None
+ self._forget_cached_table()
return table
+ def _forget_cached_table(self) -> None:
+ # A version noted for the old handle describes a table incarnation this ref is done with.
+ self._cached_table = None
+ self._cached_table_stale = False
+ self._deltalite_version = None
+
async def _open_delta_table(self) -> deltalake.DeltaTable | None:
delta_uri = await self._get_delta_table_uri()
storage_options = self._get_credentials()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py
index d12b46b94be3..dce807ba5e59 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py
@@ -51,31 +51,49 @@ def _governor(mode="enforce", *, limit_mb=30_000.0, current_mb=1_000.0, max_conc
class TestSizeUpsert:
- # threaded model: marginal(source, mpp) = 220 + 133*mpp + 0.73*source. For source_mb=50 (36.5):
+ # threaded model: marginal(source, mpp, files) = 220 + 133*(mpp*files/4) + 0.73*source.
+ # For source_mb=50 (36.5), at the measured 4 files per worker:
# mpp1=389.5 mpp2=522.5 mpp3=655.5 mpp4=788.5
+ # and with the reader ceiling of 16 filled: (1,8)=522.5 (2,8)=788.5 (3,5)=755.25
@parameterized.expand(
[
- ("roomy_takes_max_mpp", 5_000.0, 50.0, None, 4, True),
- ("steps_down_to_two", 600.0, 50.0, None, 2, True), # mpp2=522.5<=600, mpp3=655.5>600
- ("steps_down_to_one", 450.0, 50.0, None, 1, True), # mpp1=389.5<=450, mpp2=522.5>450
- ("does_not_fit", 300.0, 50.0, None, 1, False), # mpp1=389.5>300
- ("partition_cap_limits_mpp", 5_000.0, 50.0, 2, 2, True), # budget allows 4, only 2 partitions
+ ("roomy_takes_max_mpp", 5_000.0, 50.0, None, 4, 4, True),
+ ("steps_down_to_two", 600.0, 50.0, None, 2, 4, True), # (2,4)=522.5<=600, (2,8)=788.5>600
+ ("steps_down_to_one", 450.0, 50.0, None, 1, 4, True), # (1,4)=389.5<=450, (1,8)=522.5>450
+ ("does_not_fit", 300.0, 50.0, None, 1, 4, False), # (1,4)=389.5>300
+ ("partition_cap_fills_readers", 5_000.0, 50.0, 2, 2, 8, True), # budget allows 4, only 2 partitions
+ ("single_partition_gets_the_widest_worker", 5_000.0, 50.0, 1, 1, 8, True),
+ ("three_partitions_share_the_ceiling", 5_000.0, 50.0, 3, 3, 5, True), # 16 // 3
]
)
- def test_sizing(self, _name, available_mb, source_mb, n_partitions, exp_mpp, exp_fits):
+ def test_sizing(self, _name, available_mb, source_mb, n_partitions, exp_mpp, exp_files, exp_fits):
plan = size_upsert(available_mb, source_mb, n_partitions)
- assert plan.max_parallel_partitions == exp_mpp
+ assert (plan.max_parallel_partitions, plan.max_parallel_files) == (exp_mpp, exp_files)
assert plan.fits is exp_fits
- assert set(plan.as_upsert_kwargs()) == {
+ # The in-flight reader count of a full plan at the measured defaults (4 workers x 4 files)
+ # is the ceiling every plan stays under.
+ assert plan.max_parallel_partitions * plan.max_parallel_files <= 16
+ kwargs = plan.as_upsert_kwargs()
+ assert set(kwargs) == {
"max_parallel_partitions",
"max_parallel_files",
"max_buffered_bytes",
+ "probe_concurrency",
}
+ # Probes are budgeted against max_buffered_bytes, so the raised concurrency goes out in
+ # every plan; leaving it out would silently hand deltalite its default of 8.
+ assert kwargs["probe_concurrency"] == 32
def test_predicted_peak_monotonic_in_mpp_and_source(self):
assert _predict_marginal_mb(50, 1) < _predict_marginal_mb(50, 4)
assert _predict_marginal_mb(50, 2) < _predict_marginal_mb(500, 2)
+ def test_extra_readers_are_charged_as_worker_equivalents(self):
+ # One worker with twice the measured readers is predicted like two measured workers, so a
+ # wider worker can never claim less memory than the shape the coefficient came from.
+ assert _predict_marginal_mb(50, 1, files_per_worker=8) == _predict_marginal_mb(50, 2)
+ assert _predict_marginal_mb(50, 1, files_per_worker=4) < _predict_marginal_mb(50, 1, files_per_worker=8)
+
class TestPodMemory:
@parameterized.expand(
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 66afa737c3ec..b82b63daaae6 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
@@ -66,14 +66,81 @@ class TestGetDeltaTableCache:
with patch(f"{self._MODULE}.deltalake.DeltaTable") as mock_delta_table:
mock_delta_table.is_deltatable.return_value = True
- mock_delta_table.side_effect = lambda table_uri, storage_options: MagicMock()
+ mock_delta_table.side_effect = lambda table_uri, storage_options: MagicMock(
+ version=MagicMock(return_value=1)
+ )
stale = await ref.get_delta_table()
+ ref.note_deltalite_commit(9)
getattr(ref, method)()
- fresh = await ref.get_delta_table()
+ fresh = cast(MagicMock, await ref.get_delta_table())
assert fresh is not stale
assert mock_delta_table.call_count == 2
+ # The deltalite commit belonged to the dropped incarnation: the fresh open is current as is,
+ # and the old version must not outrank the new table's own.
+ fresh.update_incremental.assert_not_called()
+ assert ref.latest_known_version(fresh) == 1
+
+ @pytest.mark.asyncio
+ async def test_a_deltalite_commit_is_caught_up_on_the_next_read_only(self):
+ # deltalite commits past the delta-rs handle. A reader of the version or the file list
+ # (post-load, maintenance) must see that commit; a reader that opts out must not pay the
+ # log read for it; and the catch-up happens once, not on every later call.
+ ref = _openable_table_ref("s3://bucket/team/job/t")
+
+ with patch(f"{self._MODULE}.deltalake.DeltaTable") as mock_delta_table:
+ mock_delta_table.is_deltatable.return_value = True
+ mock_delta_table.side_effect = lambda table_uri, storage_options: MagicMock(
+ version=MagicMock(return_value=3)
+ )
+
+ handle = cast(MagicMock, await ref.get_delta_table())
+ ref.note_deltalite_commit(4)
+
+ assert await ref.get_delta_table(allow_stale=True) is handle
+ handle.update_incremental.assert_not_called()
+ assert ref.latest_known_version(handle) == 4
+
+ assert await ref.get_delta_table() is handle
+ handle.update_incremental.assert_called_once()
+ await ref.get_delta_table()
+ handle.update_incremental.assert_called_once()
+
+ assert mock_delta_table.call_count == 1
+
+ @parameterized.expand(
+ [
+ ("transient_blip", OSError("Generic S3 error: connection reset"), TransientObjectStoreError, False),
+ ("other_error", RuntimeError("something else went wrong"), RuntimeError, True),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_a_failed_catch_up_keeps_the_handle_behind(
+ self, _name: str, error: Exception, expected: type[Exception], captured: bool
+ ):
+ # A refresh that fails must not clear the mark, or the next reader would trust a snapshot
+ # that is known to be behind the log. Classification mirrors the open path so a transient
+ # blip is not reported as a defect.
+ ref = _openable_table_ref("s3://bucket/team/job/t")
+
+ with (
+ patch(f"{self._MODULE}.deltalake.DeltaTable") as mock_delta_table,
+ patch(f"{self._MODULE}.capture_exception") as capture,
+ ):
+ mock_delta_table.is_deltatable.return_value = True
+ mock_delta_table.side_effect = lambda table_uri, storage_options: MagicMock()
+
+ handle = cast(MagicMock, await ref.get_delta_table())
+ handle.update_incremental.side_effect = [error, None]
+ ref.note_deltalite_commit(4)
+
+ with pytest.raises(expected):
+ await ref.get_delta_table()
+ assert await ref.get_delta_table() is handle
+
+ assert handle.update_incremental.call_count == 2
+ assert capture.called is captured
@pytest.mark.asyncio
async def test_pop_never_opens_the_table(self):
diff --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.py
index a39b99f52cdf..3eb5f15d8a85 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
@@ -26,7 +26,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
DeltaLiteHandleCache,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import ensure_table_properties
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (
+ DELTA_TABLE_PROPERTIES,
+ ensure_table_properties,
+)
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 (
decimal_array,
@@ -874,9 +877,9 @@ class TestCreateRaceWithExistingTable:
real_get_delta_table = helper.get_delta_table
calls = {"n": 0}
- async def flaky_first_check():
+ async def flaky_first_check(**kwargs: Any):
calls["n"] += 1
- return None if calls["n"] == 1 else await real_get_delta_table()
+ return None if calls["n"] == 1 else await real_get_delta_table(**kwargs)
batch = pa.table({"id": [2, 3]})
@@ -1119,6 +1122,7 @@ class TestDeltaliteWritePath:
logger = make_logger() # captured so we can inspect the structured log without hitting the typed attr
helper = DeltaTableRef(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=logger)
existing = MagicMock()
+ existing.version.return_value = 4
# SimpleNamespace stands in for the pyo3 UpsertStats: predictable scalar getters for the structured log.
fake_stats = SimpleNamespace(
version=5, partitions_touched=1, rows_inserted=3, rows_updated=2, rows_copied=10, null_pk_rows=0
@@ -1144,7 +1148,10 @@ class TestDeltaliteWritePath:
fake_table.upsert.assert_called_once()
# PARTITION_KEY is passed as the partition arg when the table is partitioned.
assert fake_table.upsert.call_args.args[2] == PARTITION_KEY
- existing.update_incremental.assert_called_once()
+ # The delta-rs handle is not refreshed on the write path (a log listing per batch); the ref
+ # knows the version deltalite reached and catches the handle up on its next read.
+ existing.update_incremental.assert_not_called()
+ assert helper.latest_known_version(existing) == 5
# The commit is logged with the UpsertStats fields as structured keys + a duration, so it's parseable.
logger.ainfo.assert_called_once()
log_kwargs = logger.ainfo.call_args.kwargs
@@ -1168,27 +1175,30 @@ class TestDeltaliteWritePath:
wrote = await self._call(helper)
assert wrote is False # deltalite blew up -> caller falls through to the delta-rs MERGE
- @parameterized.expand([("refresh",), ("log",)])
+ @parameterized.expand([("log",), ("metric",)])
@pytest.mark.asyncio
async def test_post_commit_failure_does_not_fall_back(self, failing_step: str):
- # Once the upsert commits, NO post-commit step (handle refresh, log, metric) may raise into the
- # caller — that would return False / bubble up and re-run the MERGE on top of deltalite's commit.
+ # Once the upsert commits, NO post-commit step (log, metric) may raise into the caller — that
+ # would return False / bubble up and re-run the MERGE on top of deltalite's commit.
logger = make_logger() # set the side effect on the mock before it becomes the typed _logger attr
existing = MagicMock()
- if failing_step == "refresh":
- existing.update_incremental.side_effect = RuntimeError("post-commit refresh boom")
- else:
+ existing.version.return_value = 4
+ if failing_step == "log":
logger.ainfo.side_effect = RuntimeError("post-commit log boom")
helper = DeltaTableRef(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=logger)
fake_table = MagicMock()
fake_table.upsert.return_value = MagicMock(version=5, rows_inserted=1, rows_updated=0, rows_copied=0)
fake_deltalite = MagicMock()
fake_deltalite.DeltaLiteTable.open.return_value = fake_table
+ metrics_module = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics"
with (
patch.dict("sys.modules", {"deltalite": fake_deltalite}),
patch.object(helper, "_get_delta_table_uri", AsyncMock(return_value="s3://b/t")),
patch.object(helper, "_get_credentials", return_value={}),
+ patch(f"{metrics_module}.DELTALITE_WRITE_TOTAL") as write_total,
):
+ if failing_step == "metric":
+ write_total.labels.side_effect = RuntimeError("post-commit metric boom")
wrote = await DeltaWriter(helper)._write_via_deltalite(
existing_delta_table=existing,
data=pa.table({"id": pa.array([1], pa.int64())}),
@@ -1198,6 +1208,47 @@ class TestDeltaliteWritePath:
)
assert wrote is True # committed; the post-commit failure is swallowed
fake_table.upsert.assert_called_once()
+ # The commit is recorded on the ref before any best-effort step, so a failure there cannot
+ # leave a later reader on the pre-commit snapshot.
+ assert helper.latest_known_version(existing) == 5
+
+
+class TestWriteAfterDeltaliteCommit:
+ """`write` hands back the delta-rs handle without refreshing it after deltalite commits; the ref
+ catches the handle up once, on the first read that asks for the current snapshot."""
+
+ @pytest.mark.asyncio
+ async def test_write_skips_the_refresh_and_the_next_read_pays_it_once(self, tmp_path: Path) -> None:
+ delta_path = str(tmp_path / "table")
+ # Created with the table properties already set, so the write's tail makes no commit of its own.
+ deltalake.write_deltalake(
+ delta_path, pa.table({"id": pa.array([1, 2], pa.int64())}), configuration=DELTA_TABLE_PROPERTIES
+ )
+ helper = make_local_table_ref(delta_path)
+
+ async def _commit_via_deltalite(**kwargs: Any) -> bool:
+ helper.note_deltalite_commit(kwargs["existing_delta_table"].version() + 1)
+ return True
+
+ with (
+ patch.object(DeltaWriter, "_write_via_deltalite", AsyncMock(side_effect=_commit_via_deltalite)),
+ patch.object(deltalake.DeltaTable, "update_incremental") as refresh,
+ ):
+ returned = await DeltaWriter(helper).write(
+ data=pa.table({"id": pa.array([2, 3], pa.int64())}),
+ write_type="incremental",
+ should_overwrite_table=False,
+ primary_keys=["id"],
+ )
+ # The write path reads only what the commit cannot change, so it pays no log listing.
+ refresh.assert_not_called()
+ assert helper.latest_known_version(returned) == returned.version() + 1
+
+ # Post-load reads (file list, maintenance) go through the ref and get the current snapshot.
+ assert await helper.get_delta_table() is returned
+ refresh.assert_called_once()
+ await helper.get_delta_table()
+ refresh.assert_called_once()
class TestRealignDecimalBuffers:
@@ -1412,6 +1463,32 @@ class TestDeltaliteHandleReuseInWriter:
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_delta_rs_handle_left_behind_by_deltalite_still_reuses_the_cached_handle(self) -> None:
+ # The delta-rs handle is no longer refreshed after a deltalite commit, so on the next batch it
+ # still reports the version before that commit. The cached deltalite handle is ahead of it
+ # for a good reason; without the noted commit the cache would judge it ahead of the live log
+ # and pay a full snapshot load on every batch.
+ helper = DeltaTableRef(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=make_logger())
+ fake_table = _fake_handle(4)
+ fake_table.upsert.return_value = SimpleNamespace(version=4)
+ fake_deltalite = MagicMock()
+ fake_deltalite.DeltaLiteTable.open.return_value = fake_table
+ cache = DeltaLiteHandleCache(maxsize=4)
+ existing = self._existing("tid", 3)
+ 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, existing) is True
+ assert await self._write(helper, existing) is True
+
+ existing.update_incremental.assert_not_called()
+ 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())
diff --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.py
index 501d3a49fd65..302cbc97ef99 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,17 +93,19 @@ def _deltalite_write_stats(stats: Any) -> dict[str, int | float | str | bool]:
return fields
-def _delta_table_identity(delta_table: deltalake.DeltaTable) -> tuple[str, int] | None:
+def _delta_table_identity(delta_table: deltalake.DeltaTable, table_ref: "DeltaTableRef") -> tuple[str, int] | None:
"""The (table id, version) a delta-rs handle observes, or None when it cannot say.
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.
+ only safe when the caller can prove which table the cached snapshot belongs to. The version is
+ the newest `table_ref` knows of, so a handle that a deltalite commit left behind does not make
+ the cached deltalite handle look ahead of the live log.
"""
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()
+ version: object = table_ref.latest_known_version(delta_table)
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):
@@ -111,6 +113,12 @@ def _delta_table_identity(delta_table: deltalake.DeltaTable) -> tuple[str, int]
return table_id, version
+def _committed_version(stats: Any) -> int | None:
+ """The table version a deltalite ``UpsertStats`` reports, or None from a double without one."""
+ version = getattr(stats, "version", None)
+ return version if isinstance(version, int) else None
+
+
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)."""
@@ -236,7 +244,7 @@ class DeltaWriter:
)
# 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)
+ live_identity = _delta_table_identity(existing_delta_table, self._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
@@ -276,14 +284,16 @@ class DeltaWriter:
pass
return False
- # Committed — the real table is now deltalite's output. NOTHING past this point may raise into
- # the caller: an exception here would leave `deltalite_wrote` unset and either fail/retry the
- # sync or re-run the delta-rs MERGE on top of deltalite's already-committed write. So every
- # post-commit step (handle refresh, log, metric) is wrapped best-effort and we always return True.
+ # Committed — the real table is now deltalite's output. The delta-rs handle is not refreshed
+ # here: that costs a log listing per batch, and most batches never read the handle's version
+ # or file list again. The ref refreshes it on the next `get_delta_table` call instead.
+ self._table.note_deltalite_commit(_committed_version(stats))
+
+ # NOTHING past this point may raise into the caller: an exception here would leave
+ # `deltalite_wrote` unset and either fail/retry the sync or re-run the delta-rs MERGE on top of
+ # deltalite's already-committed write. So every post-commit step (log, metric) is wrapped
+ # best-effort and we always return True.
try:
- # Refresh the in-memory delta-rs handle to deltalite's new version so the table returned by
- # write (and any subsequent reads) reflects the real state.
- await asyncio.to_thread(existing_delta_table.update_incremental)
# Structured, parseable stats (parity with the old `Delta Merge Stats: {json}` line): every
# UpsertStats field becomes its own log key, plus the wall-clock duration. `_deltalite_write_stats`
# enumerates the pyo3 getters, so fields added crate-side later (e.g. per-phase timings) flow
@@ -615,7 +625,13 @@ class DeltaWriter:
self._logger,
)
- delta_table = await self._table.get_delta_table()
+ # After a deltalite write the handle is one commit behind the log. The property check reads
+ # only the table configuration, which deltalite never changes, and the commit it may make
+ # goes through delta-rs's own conflict check, which rejects a commit built on a superseded
+ # metadata and lets `execute_with_conflict_retry` refresh and retry. The returned handle
+ # carries the same lag; a caller that needs the version or the file list must read them
+ # through `get_delta_table()`, which catches the handle up.
+ delta_table = await self._table.get_delta_table(allow_stale=True)
assert delta_table is not None
await ensure_table_properties(delta_table, self._logger)
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 20ceae738aba..098a72241b86 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
@@ -1147,20 +1147,29 @@ def _process_message_reported(
for index in batch_indexes:
mark_batch_as_processed(export_signal.team_id, export_signal.schema_id, export_signal.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
+ # it instead: the trend is what matters, and the version is cheap enough to log every batch.
+ sample_file_count = export_signal.batch_index % FILE_COUNT_LOG_SAMPLE_EVERY == 0
+
+ # The handle `write` returns can be one deltalite commit behind the log. Column names and
+ # types cannot differ across that commit, so the schema below reads it as is; a file list
+ # can, so the readers of one go through the ref, which catches the handle up first.
+ if sample_file_count 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
+
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)
- # 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
- # it instead: the trend is what matters, and the version is cheap enough to log every batch.
- sample_file_count = export_signal.batch_index % FILE_COUNT_LOG_SAMPLE_EVERY == 0
logger.debug(
"batch_written_to_delta_lake",
batch_index=export_signal.batch_index,
- delta_version=delta_table.version(),
+ delta_version=delta_table_ref.latest_known_version(delta_table),
file_count=len(delta_table.file_uris()) if sample_file_count else None,
)
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 43c72d126435..2abbe8a3577f 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
@@ -523,6 +523,54 @@ class TestRedeliveredFinalBatchPostLoad:
assert mock_post_load.await_args.kwargs["cdc_write_mode"] == cdc_write_mode
+class TestPostWriteHandleReads:
+ # `DeltaWriter.write` can return a handle one deltalite commit behind the log. Column names and
+ # types survive that lag, a file list does not: partial data loading must read its file list
+ # through the ref, which catches the handle up, and a plain batch must not pay that read.
+
+ @parameterized.expand([("plain_batch", False, 1), ("partial_data_loading", True, 2)])
+ @patch(f"{_PROCESSOR}.posthoganalytics")
+ @patch(f"{_PROCESSOR}.mark_batch_as_processed")
+ @patch(f"{_PROCESSOR}._handle_partial_data_loading", new_callable=AsyncMock)
+ @patch(f"{_PROCESSOR}.supports_partial_data_loading", return_value=True)
+ @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_file_list_readers_go_through_the_ref(
+ self,
+ _case: str,
+ is_first_ever_sync: bool,
+ expected_handle_reads: int,
+ mock_job_model: MagicMock,
+ mock_helper_cls: MagicMock,
+ mock_writer_cls: MagicMock,
+ _already: MagicMock,
+ _read: MagicMock,
+ _supports: MagicMock,
+ mock_partial: AsyncMock,
+ _mark: MagicMock,
+ _analytics: MagicMock,
+ ) -> None:
+ returned = MagicMock()
+ returned.schema.return_value = pa.schema([_COL_ID])
+ current = MagicMock()
+ current.schema.return_value = pa.schema([_COL_ID])
+ current.file_uris.return_value = []
+ helper = mock_helper_cls.return_value
+ helper.get_delta_table = AsyncMock(return_value=current)
+ mock_writer_cls.return_value.write = AsyncMock(return_value=returned)
+ mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()
+
+ process_message(_message(batch_index=1, is_first_ever_sync=is_first_ever_sync))
+
+ # One read opens the table before the write; only a file-list reader adds a second.
+ assert helper.get_delta_table.await_count == expected_handle_reads
+ assert mock_partial.await_args is not None
+ assert mock_partial.await_args.kwargs["delta_table"] is (current if is_first_ever_sync else returned)
+
+
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
diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rs
index e34b83efc00c..57cadea482d5 100644
--- a/rust/deltalite/core/src/upsert.rs
+++ b/rust/deltalite/core/src/upsert.rs
@@ -1742,8 +1742,9 @@ async fn probe_file(
}
/// Probe `files` with bounded concurrency, splitting them into (files that contain at
-/// least one match, count of files proven match-free). Order is preserved. A kept file
-/// carries the footer its probe parsed; a skipped file's footer is dropped here.
+/// least one match, count of files proven match-free). Order is preserved. Up to one
+/// reader wave of kept files carries the footer its probe parsed; retaining every hit
+/// footer would make memory grow with the partition's file count before rewrites start.
#[allow(clippy::too_many_arguments)]
async fn probe_files(
store: &Arc<dyn ObjectStore>,
@@ -1755,33 +1756,34 @@ async fn probe_files(
opts: &UpsertOptions,
budgets: &Budgets,
) -> Result<(Vec<TargetFile>, usize)> {
- let results: Vec<(TargetFile, bool, Arc<ParquetMetaData>)> =
- futures::stream::iter(files.into_iter().map(|f| {
- let store = store.clone();
- async move {
- let (hit, metadata) = probe_file(
- &store,
- &f,
- pkset,
- table_schema,
- partition_col,
- partition_value,
- opts,
- budgets,
- )
- .await?;
- Ok::<_, Error>((f, hit, metadata))
- }
- }))
- .buffered(opts.probe_concurrency.max(1))
- .try_collect()
- .await?;
+ let results = futures::stream::iter(files.into_iter().map(|f| {
+ let store = store.clone();
+ async move {
+ let (hit, metadata) = probe_file(
+ &store,
+ &f,
+ pkset,
+ table_schema,
+ partition_col,
+ partition_value,
+ opts,
+ budgets,
+ )
+ .await?;
+ Ok::<_, Error>((f, hit, metadata))
+ }
+ }))
+ .buffered(opts.probe_concurrency.max(1));
+ futures::pin_mut!(results);
+ let retained_footer_limit = opts.max_parallel_files.max(1);
let mut keep = Vec::new();
let mut skipped = 0usize;
- for (mut f, hit, metadata) in results {
+ while let Some((mut f, hit, metadata)) = results.try_next().await? {
if hit {
- f.metadata = Some(metadata);
+ if keep.len() < retained_footer_limit {
+ f.metadata = Some(metadata);
+ }
keep.push(f);
} else {
skipped += 1;
diff --git a/rust/deltalite/core/tests/handle_and_open.rs b/rust/deltalite/core/tests/handle_and_open.rs
index 893ca56bcd90..cbea07e2e9f1 100644
--- a/rust/deltalite/core/tests/handle_and_open.rs
+++ b/rust/deltalite/core/tests/handle_and_open.rs
@@ -844,12 +844,10 @@ async fn files_carry_partition_values() {
assert_eq!(partitions, [Some("x".to_string()), Some("y".to_string())]);
}
-/// A file the probe found a match in is rewritten with the footer the probe parsed, and
-/// that footer arrives in one GET: one footer round trip per hit file for the whole
-/// upsert, not two (probe and rewrite each opening the file) times two (trailer, then
-/// metadata).
+/// Footer reuse is limited to one reader wave so metadata retained between the probe
+/// and rewrite phases cannot grow with the partition's file count.
#[tokio::test]
-async fn hit_files_are_opened_once_across_probe_and_rewrite() {
+async fn hit_file_footer_reuse_is_bounded_by_reader_concurrency() {
register_counting_scheme();
let dir = tempfile::tempdir().expect("tempdir");
let table_dir = dir.path().join("t9");
@@ -861,6 +859,8 @@ async fn hit_files_are_opened_once_across_probe_and_rewrite() {
&["a0", "a1", "a2", "a3"],
&["b0", "b1", "b2", "b3"],
&["c0", "c1", "c2", "c3"],
+ &["d0", "d1", "d2", "d3"],
+ &["e0", "e1", "e2", "e3"],
],
)
.await;
@@ -874,35 +874,35 @@ async fn hit_files_are_opened_once_across_probe_and_rewrite() {
.into_iter()
.map(|f| format!("{root}/{}", f.path))
.collect();
- assert_eq!(hit_files.len(), 3);
+ assert_eq!(hit_files.len(), 5);
- // One key from every file: each is probed, hit, and rewritten.
let start = ops_len();
let stats = handle
.upsert(
vec![batch(
&s,
- &["a2", "b2", "c2"],
- vec![Some(7), Some(7), Some(7)],
+ &["a2", "b2", "c2", "d2", "e2"],
+ vec![Some(7), Some(7), Some(7), Some(7), Some(7)],
)],
s.clone(),
- opts(),
+ UpsertOptions {
+ max_parallel_files: 2,
+ ..opts()
+ },
MultipartConfig::default(),
)
.await
.expect("upsert");
- assert_eq!(stats.files_probed, 3);
- assert_eq!(stats.files_removed, 3);
+ assert_eq!(stats.files_probed, 5);
+ assert_eq!(stats.files_removed, 5);
let footer_gets = data_file_footer_gets(&ops_since(start, &root), &root);
- for path in &hit_files {
- assert_eq!(
- footer_gets.get(path).copied().unwrap_or(0),
- 1,
- "{path}: expected the probe's one footer GET, reused by the rewrite \
- (footer GETs per file: {footer_gets:?})"
- );
- }
+ let counts: Vec<usize> = hit_files
+ .iter()
+ .map(|path| footer_gets.get(path).copied().unwrap_or(0))
+ .collect();
+ assert_eq!(counts.iter().filter(|&&count| count == 1).count(), 2);
+ assert_eq!(counts.iter().filter(|&&count| count == 2).count(), 3);
}
/// After the commit the handle adopts the state delta-rs derived for it instead of