:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): size deltalite merges by the files they rewrite (#110692)
Tom Owers3c747e5ae1ab
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.pyindex cc996a865ce5..4dc4f591f585 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@@ -26,13 +26,19 @@ Two layers, by design:governor predicted. The governor aims never to reach it; the backstop guarantees safety when aprediction is wrong.-The memory model (rust/deltalite ``REPORT.md`` §5.5–5.7): peak memory does **not** track the-target table size. It tracks the resident source batch (the floor — linear in source rows, and-no knob bounds it), the number of concurrent partition workers (``max_parallel_partitions``, the-memory dial) and the write buffers. So the only inputs that matter for sizing are the source-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).+The memory model (rust/deltalite ``REPORT.md`` §5.5–5.7): peak memory tracks the resident+source batch (the floor — linear in source rows, and no knob bounds it), the number of concurrent+partition workers (``max_parallel_partitions``, the memory dial) and the write buffers. 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).++The coefficients were fitted on small target partitions, so they do not see the existing files a+merge rewrites. A changed row forces its whole file to be rewritten, and merges that rewrite many+existing rows grow the pod far past their prediction. So the planner also charges each partition+worker for the existing files of the partition it rewrites (``RewriteProfile``), read from the+table's add actions with no object-store request. When even one worker exceeds the slice, the+upsert reserves more than one slice, and later admissions wait (bounded) for that room.Two knobs buy I/O overlap rather than memory: ``max_parallel_files`` (readers per partitionworker) and ``probe_concurrency`` (PK-column probes per worker). deltalite budgets every decoded@@ -45,15 +51,26 @@ as worker-equivalents, so a plan never predicts less memory than the measured shfrom __future__ import annotationsimport os+import time+import asyncioimport loggingimport threadingimport contextlib-from collections.abc import AsyncIterator+from collections import defaultdict, deque+from collections.abc import AsyncIterator, Awaitable, Callable, Sequencefrom dataclasses import dataclass, field-from typing import Literal+from typing import TYPE_CHECKING, Literalfrom django.conf import settings+import pyarrow as pa+import pyarrow.compute as pc++from posthog.dataclasses import frozen++if TYPE_CHECKING:+ import deltalake+logger = logging.getLogger(__name__)MB = 1024 * 1024@@ -108,6 +125,123 @@ _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+#: Resident bytes per stored byte of the existing files one partition worker rewrites: one+#: decoded copy (the footer ratio of decoded to stored bytes is about 1.4 on the tables that+#: overran their slot) with a little slack.+_REWRITE_MEMORY_FACTOR = 1.5+#: Ceiling on the rewrite memory charged to one partition worker. deltalite streams a partition,+#: so its working set must stop growing at some size; the largest single-partition merges seen in+#: production grew the pod by just under 4 GB. Without a ceiling, a small batch into a huge+#: unpartitioned table would reserve the whole pod.+_MAX_REWRITE_MB_PER_WORKER = 4096.0+#: How often a waiting admission checks for room.+_WAIT_POLL_S = 0.5+#: Rounding slack on the room check, so ``max_concurrent`` slice-sized reservations always fit.+_ROOM_TOLERANCE_MB = 1.0+++@frozen+class RewriteProfile:+ """Stored bytes of the existing files one merge can rewrite, per touched partition."""++ #: Largest first. A touched partition with no candidate files is left out.+ partition_bytes: tuple[int, ...]+ #: Candidate files over all touched partitions.+ files: int++ @property+ def total_mb(self) -> float:+ return sum(self.partition_bytes) / MB++ def rewrite_mb(self, mpp: int) -> float:+ """Memory the rewrite adds when the ``mpp`` largest partitions run at the same time."""+ return sum(+ min(_REWRITE_MEMORY_FACTOR * size / MB, _MAX_REWRITE_MB_PER_WORKER) for size in self.partition_bytes[:mpp]+ )+++def _files_that_can_match(add_actions: pa.Table, source: pa.Table, primary_keys: Sequence[str]) -> list[bool]:+ """Per file, False when its first-PK range cannot hold any key of the batch.++ String keys are not pruned: delta truncates long string stats, so a truncated max can sit below+ a key the file holds, and pruning on it would under-count the rewrite.+ """+ everything = [True] * add_actions.num_rows+ if not primary_keys or primary_keys[0] not in source.column_names:+ return everything+ pk = primary_keys[0]+ min_col, max_col = f"min.{pk}", f"max.{pk}"+ if min_col not in add_actions.column_names or max_col not in add_actions.column_names:+ return everything+ file_min, file_max = add_actions[min_col], add_actions[max_col]+ if (+ pa.types.is_string(file_min.type)+ or pa.types.is_large_string(file_min.type)+ or pa.types.is_binary(file_min.type)+ ):+ return everything+ bounds = pc.min_max(source[pk])+ low, high = bounds["min"], bounds["max"]+ if not low.is_valid or not high.is_valid:+ return everything+ try:+ disjoint = pc.or_kleene(+ pc.less(file_max, low.cast(file_max.type)), pc.greater(file_min, high.cast(file_min.type))+ )+ except (pa.ArrowInvalid, pa.ArrowNotImplementedError, pa.ArrowTypeError):+ return everything+ # A null comparison (a file with no stats for the key) proves nothing, so the file stays.+ return [d is not True for d in disjoint.to_pylist()]+++def rewrite_profile(+ add_actions: pa.Table, source: pa.Table, partition_col: str | None, primary_keys: Sequence[str]+) -> RewriteProfile:+ """Upper bound on the existing files a merge of ``source`` rewrites, from the table's add actions.++ A file is a candidate when it is in a partition the batch touches and its PK range overlaps the+ batch. Each source row replaces at most one existing row, so a partition rewrites at most as+ many files as it has source rows; the largest candidates are counted.+ """+ if add_actions.num_rows == 0 or source.num_rows == 0:+ return RewriteProfile(partition_bytes=(), files=0)++ if partition_col is None:+ rows_per_partition: dict[str | None, int] = {None: source.num_rows}+ file_partitions: list[str | None] = [None] * add_actions.num_rows+ else:+ counts = pc.value_counts(source[partition_col].cast(pa.string()))+ rows_per_partition = {+ value: int(count or 0)+ for value, count in zip(counts.field("values").to_pylist(), counts.field("counts").to_pylist())+ }+ file_partitions = add_actions[f"partition.{partition_col}"].cast(pa.string()).to_pylist()++ sizes_by_partition: dict[str | None, list[int]] = defaultdict(list)+ can_match = _files_that_can_match(add_actions, source, primary_keys)+ for partition, size, candidate in zip(file_partitions, add_actions["size_bytes"].to_pylist(), can_match):+ if candidate and partition in rows_per_partition:+ sizes_by_partition[partition].append(size or 0)++ partition_bytes: list[int] = []+ files = 0+ for partition, sizes in sizes_by_partition.items():+ largest = sorted(sizes, reverse=True)[: rows_per_partition[partition]]+ files += len(largest)+ partition_bytes.append(sum(largest))+ return RewriteProfile(partition_bytes=tuple(sorted(partition_bytes, reverse=True)), files=files)+++def estimate_rewrite_profile(+ table: deltalake.DeltaTable, source: pa.Table, partition_col: str | None, primary_keys: Sequence[str]+) -> RewriteProfile | None:+ """``rewrite_profile`` for a live table, or None when its add actions cannot be read."""+ try:+ add_actions = pa.table(table.get_add_actions(flatten=True))+ return rewrite_profile(add_actions, source, partition_col, primary_keys)+ except Exception as e: # noqa: BLE001 - an estimate must never fail a write; None sizes as before+ logger.debug("deltalite governor: could not estimate the rewrite size: %s", e)+ return None@dataclass(frozen=True)@@ -122,6 +256,8 @@ class UpsertPlan:#: False when even a single worker exceeds the available slice.fits: boolprobe_concurrency: int = _PROBE_CONCURRENCY+ #: The part of ``predicted_peak_mb`` charged for rewriting existing files, in MB.+ rewrite_mb: float = 0.0def as_upsert_kwargs(self) -> dict[str, int]:return {@@ -137,18 +273,32 @@ def _files_per_worker(mpp: int) -> int: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:+def _predict_marginal_mb(+ source_mb: float, mpp: int, files_per_worker: int = _MEASURED_FILES_PER_WORKER, rewrite_mb: float = 0.0+) -> 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 workerthat runs more readers is charged as that many worker-equivalents. That over-counts (a worker'sPK set and write buffer do not grow with its readers), which keeps the prediction conservative.+ ``rewrite_mb`` is the memory for the existing files the ``mpp`` workers rewrite at once+ (``RewriteProfile.rewrite_mb``)."""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:+ return (+ _MARGINAL_BASE_MB+ + _MARGINAL_PER_WORKER_MB * worker_equivalents+ + _MARGINAL_PER_SOURCE_MB * source_mb+ + rewrite_mb+ )+++def size_upsert(+ available_mb: float,+ source_mb: float,+ n_partitions: int | None = None,+ rewrite: RewriteProfile | 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@@ -157,22 +307,33 @@ def size_upsert(available_mb: float, source_mb: float, n_partitions: int | NoneWhen no such plan fits, try one worker at the measured reader count; if even that exceeds theslice, return it with ``fits=False``. The caller does not fall back on ``fits=False`` — it runsdeltalite at ``mpp=1`` anyway (still the memory floor, far below the MERGE) and flags- ``capacity_exceeded``.+ ``capacity_exceeded``. ``rewrite=None`` (sizes unknown) charges no rewrite memory."""partition_cap = _MAX_PARALLEL_PARTITIONSif n_partitions is not None and n_partitions >= 1:partition_cap = min(partition_cap, n_partitions)for mpp in range(partition_cap, 0, -1):+ rewrite_mb = rewrite.rewrite_mb(mpp) if rewrite is not None else 0.0# 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)+ predicted = _predict_marginal_mb(source_mb, mpp, files, rewrite_mb)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, _MEASURED_FILES_PER_WORKER, _DEFAULT_BUFFERED_BYTES, round(minimal, 1), fits=False)+ return UpsertPlan(+ mpp, files, _DEFAULT_BUFFERED_BYTES, round(predicted, 1), fits=True, rewrite_mb=round(rewrite_mb, 1)+ )++ rewrite_mb = rewrite.rewrite_mb(1) if rewrite is not None else 0.0+ minimal = _predict_marginal_mb(source_mb, 1, rewrite_mb=rewrite_mb)+ return UpsertPlan(+ 1,+ _MEASURED_FILES_PER_WORKER,+ _DEFAULT_BUFFERED_BYTES,+ round(minimal, 1),+ fits=False,+ rewrite_mb=round(rewrite_mb, 1),+ )# --- Reading the pod's real memory (cgroup v2, with v1 and psutil fallbacks) -----------------@@ -286,6 +447,9 @@ class GovernorConfig:reserve_mb: float = 2048.0#: Used only when the cgroup limit is unreadable (local dev). None + unreadable ⇒ deltalite defaults.limit_override_mb: float | None = None+ #: Longest an enforce-mode admission waits for room before it writes anyway. The wait holds no+ #: reservation, so it can never block a release; the bound keeps a waiter from stalling its slot.+ max_wait_s: float = 60.0@staticmethoddef from_env() -> GovernorConfig:@@ -300,6 +464,7 @@ class GovernorConfig:max_concurrent=GovernorConfig._resolve_max_concurrent(),reserve_mb=_env_float("DELTALITE_GOVERNOR_RESERVE_MB", 2048.0),limit_override_mb=float(override) if override else None,+ max_wait_s=max(0.0, _env_float("DELTALITE_GOVERNOR_MAX_WAIT_S", 60.0)),)@staticmethod@@ -332,7 +497,7 @@ class GovernorConfig:return _DEFAULT_MAX_CONCURRENT-@dataclass+@dataclass(frozen=False)class Admission:"""The knobs to write one upsert with, plus diagnostics.@@ -356,6 +521,16 @@ class Admission:capacity_exceeded: bool = False#: Filled in on release with the observed cgroup delta, for predicted-vs-actual calibration.observed_delta_mb: float | None = field(default=None)+ #: The part of ``predicted_peak_mb`` charged for rewriting existing files. None when sizes are unknown.+ rewrite_mb: float | None = None+ #: Stored MB of all candidate files the merge can rewrite, over every touched partition.+ rewrite_total_mb: float | None = None+ rewrite_files: int | None = None+ #: Slices this upsert holds (enforce) or would hold (advisory). Above 1 when even mpp=1 overflows.+ reserved_slots: float | None = None+ #: Time spent waiting for room before the write, and whether the wait ran out.+ wait_ms: int = 0+ wait_timed_out: bool = False# --- The governor ----------------------------------------------------------------------------@@ -373,12 +548,24 @@ class MemoryGovernor:a plain thread lock is both correct across loops and effectively uncontended."""- def __init__(self, config: GovernorConfig | None = None, pod: PodMemory | None = None) -> None:+ def __init__(+ self,+ config: GovernorConfig | None = None,+ pod: PodMemory | None = None,+ *,+ clock: Callable[[], float] = time.monotonic,+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,+ ) -> None:self.config = config or GovernorConfig.from_env()self.pod = pod or PodMemory(limit_override_mb=self.config.limit_override_mb)self._lock = threading.Lock()self._reserved_mb = 0.0self._inflight = 0+ self._clock = clock+ self._sleep = sleep+ #: Tickets of admissions waiting for room, oldest first.+ self._waiters: deque[int] = deque()+ self._next_ticket = 0# -- accounting --------------------------------------------------------------------------@@ -398,13 +585,64 @@ class MemoryGovernor:limit_mb = self.pod.limit_mb()return None if limit_mb is None else self._per_upsert_budget_mb(limit_mb)+ def _has_room(self, reserve_mb: float, usable_mb: float) -> bool:+ return self._reserved_mb + reserve_mb <= usable_mb + _ROOM_TOLERANCE_MB++ def _take(self, reserve_mb: float) -> None:+ self._reserved_mb += reserve_mb+ self._inflight += 1++ async def _reserve(self, reserve_mb: float, usable_mb: float) -> tuple[float, bool]:+ """Reserve ``reserve_mb`` once it fits the pod, oldest waiter first. Returns (waited_s, timed_out).++ While every upsert reserves at most one slice, ``max_concurrent`` of them always fit and+ nothing waits. Only an over-slice reservation can make the pod full. Then newcomers queue+ behind the oldest waiter rather than pile on, so the big upsert is not starved by small ones.+ A waiter holds no reservation, and a reservation is released whatever happens to its+ upsert, so a wait can only end. After ``max_wait_s`` the upsert reserves anyway and+ writes, because deltalite must always write.+ """+ with self._lock:+ if not self._waiters and self._has_room(reserve_mb, usable_mb):+ self._take(reserve_mb)+ return 0.0, False+ ticket = self._next_ticket+ self._next_ticket += 1+ self._waiters.append(ticket)+ started = self._clock()+ reserved = False+ try:+ while True:+ await self._sleep(_WAIT_POLL_S)+ with self._lock:+ now = self._clock()+ room = self._waiters[0] == ticket and self._has_room(reserve_mb, usable_mb)+ if room or now - started >= self.config.max_wait_s:+ self._waiters.remove(ticket)+ self._take(reserve_mb)+ reserved = True+ return now - started, not room+ finally:+ if not reserved:+ # Cancelled while it waited: give up the place in the queue.+ with self._lock:+ if ticket in self._waiters:+ self._waiters.remove(ticket)+@contextlib.asynccontextmanager- async def admit(self, *, source_bytes: int, n_partitions: int | None = None) -> AsyncIterator[Admission]:+ async def admit(+ self,+ *,+ source_bytes: int,+ n_partitions: int | None = None,+ rewrite: RewriteProfile | None = None,+ ) -> AsyncIterator[Admission]:"""Size one upsert to its memory slice and yield the knobs to run it with.Use as ``async with governor.admit(...) as adm``. deltalite always writes — the reservation- (for observability + oversubscription accounting) is held for the whole ``with`` block and- released on exit, even on exception.+ is held for the whole ``with`` block and released on exit, even on exception. In enforce+ mode an upsert predicted above its slice reserves up to the whole usable pod, and entry+ waits (bounded by ``max_wait_s``) until the reservation fits beside the ones in flight."""source_mb = source_bytes / MB@@ -420,18 +658,21 @@ class MemoryGovernor:returnbudget_mb = self._per_upsert_budget_mb(limit_mb)- plan = size_upsert(budget_mb, source_mb, n_partitions)+ usable_mb = budget_mb * self.config.max_concurrent+ plan = size_upsert(budget_mb, source_mb, n_partitions, rewrite)+ # Capped at the usable pod so an upsert alone always fits and never waits for itself.+ reserve_mb = min(plan.predicted_peak_mb, usable_mb)- # Read live usage now, in every mode, so the observed cgroup delta over the upsert can be- # logged against the prediction — the calibration advisory mode exists for. Only enforce- # reserves against the budget; advisory is a pure no-op on the accounting.- current_at_admit = self.pod.current_mb()+ # Only enforce reserves against the budget (and may wait for room); advisory is a pure+ # no-op on the accounting.admitted = False+ waited_s, timed_out = 0.0, Falseif self.config.mode == "enforce":- with self._lock:- self._reserved_mb += plan.predicted_peak_mb- self._inflight += 1- admitted = True+ waited_s, timed_out = await self._reserve(reserve_mb, usable_mb)+ admitted = True+ # Read live usage after any wait, in every mode, so the observed cgroup delta covers the+ # write itself — the calibration advisory mode exists for.+ current_at_admit = self.pod.current_mb()adm = Admission(upsert_kwargs=plan.as_upsert_kwargs() if admitted else {},@@ -440,6 +681,12 @@ class MemoryGovernor:budget_mb=round(budget_mb, 1),planned_mpp=plan.max_parallel_partitions,capacity_exceeded=not plan.fits,+ rewrite_mb=plan.rewrite_mb if rewrite is not None else None,+ rewrite_total_mb=round(rewrite.total_mb, 1) if rewrite is not None else None,+ rewrite_files=rewrite.files if rewrite is not None else None,+ reserved_slots=round(reserve_mb / budget_mb, 2) if budget_mb > 0 else None,+ wait_ms=round(waited_s * 1000),+ wait_timed_out=timed_out,)self._emit_decision(adm, source_mb)try:@@ -447,7 +694,7 @@ class MemoryGovernor:finally:if admitted:with self._lock:- self._reserved_mb -= plan.predicted_peak_mb+ self._reserved_mb -= reserve_mbself._inflight -= 1# Best-effort predicted-vs-actual, all modes (whole-process delta, so noisy under load).if current_at_admit is not None:@@ -461,12 +708,16 @@ class MemoryGovernor:"""Log the decision and emit metrics. Never raises into the write path."""if adm.capacity_exceeded:logger.warning(- "deltalite governor: source %.0f MB exceeds its %.0f MB per-upsert slice "- "(max_concurrent=%d); running deltalite at mpp=1. Chunk the source, raise the pod "- "memory limit, or lower max_concurrent.",+ "deltalite governor: source %.0f MB with %.0f MB of rewrite memory exceeds its "+ "%.0f MB per-upsert slice (max_concurrent=%d); running deltalite at mpp=1 and "+ "reserving %.2f slices (waited %d ms, timed out: %s).",source_mb,+ adm.rewrite_mb or 0.0,adm.budget_mb or 0.0,self.config.max_concurrent,+ adm.reserved_slots or 0.0,+ adm.wait_ms,+ adm.wait_timed_out,)try:from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (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.pyindex dce807ba5e59..685dd13ed2af 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@@ -1,10 +1,13 @@import asyncio+from pathlib import Pathimport pytest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.test import override_settings+import pyarrow as pa+import deltalakefrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta import memory_governor as _mg@@ -13,8 +16,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delGovernorConfig,MemoryGovernor,PodMemory,+ RewriteProfile,_predict_marginal_mb,configure_process_concurrency,+ estimate_rewrite_profile,+ rewrite_profile,size_upsert,)@@ -43,11 +49,14 @@ class _FakePod(PodMemory):return self._fake_current() if callable(self._fake_current) else self._fake_current-def _governor(mode="enforce", *, limit_mb=30_000.0, current_mb=1_000.0, max_concurrent=15, **cfg) -> MemoryGovernor:+def _governor(+ mode="enforce", *, limit_mb=30_000.0, current_mb=1_000.0, max_concurrent=15, clock=None, sleep=None, **cfg+) -> MemoryGovernor:# Clean arithmetic defaults: no safety derate, no reserve, so the per-upsert slice is exactly# limit / max_concurrent.config = GovernorConfig(mode=mode, safety=1.0, reserve_mb=0.0, max_concurrent=max_concurrent, **cfg)- return MemoryGovernor(config, _FakePod(limit_mb, current_mb))+ timing = {k: v for k, v in (("clock", clock), ("sleep", sleep)) if v is not None}+ return MemoryGovernor(config, _FakePod(limit_mb, current_mb), **timing)class TestSizeUpsert:@@ -294,3 +303,292 @@ class TestProcessConcurrency:with patch.dict("os.environ", env, clear=True):cfg = GovernorConfig.from_env()assert (cfg.safety, cfg.reserve_mb) == (0.7, 4096.0)+++_PART = "_ph_partition_key"+# (partition, stored bytes, min id, max id)+_FILES = [+ ("a", 100, 0, 99),+ ("a", 50, 100, 199),+ ("a", 30, 200, 299),+ ("b", 400, 0, 999),+ ("c", 70, 0, 99),+]+++def _add_actions(files=_FILES, *, with_stats=True) -> pa.Table:+ columns = {+ "path": [f"{_PART}={p}/f{i}.parquet" for i, (p, *_rest) in enumerate(files)],+ "size_bytes": pa.array([f[1] for f in files], pa.int64()),+ f"partition.{_PART}": [f[0] for f in files],+ }+ if with_stats:+ columns["min.id"] = pa.array([f[2] for f in files], pa.int64())+ columns["max.id"] = pa.array([f[3] for f in files], pa.int64())+ return pa.table(columns)+++def _source(rows: list[tuple[str, int]]) -> pa.Table:+ return pa.table({_PART: [p for p, _ in rows], "id": pa.array([i for _, i in rows], pa.int64())})+++class TestRewriteProfile:+ @parameterized.expand(+ [+ # The global PK range [150, 500] proves a's first file match-free; c is not touched.+ ("touched_partitions_and_pk_range", _source([("a", 150), ("a", 250), ("b", 500)]), _PART, (400, 80), 3),+ # One source row can force at most one file rewrite, so only a's largest file counts.+ ("one_row_counts_the_largest_file", _source([("a", 150)]), _PART, (50,), 1),+ ("append_into_new_partition", _source([("d", 1), ("d", 2)]), _PART, (), 0),+ ("keys_beyond_every_file", _source([("a", 1000), ("a", 1001)]), _PART, (), 0),+ ("unpartitioned_bounded_by_rows", _source([("x", 0), ("x", 950)]), None, (500,), 2),+ ]+ )+ def test_profile(self, _name, source, partition_col, expected_bytes, expected_files):+ profile = rewrite_profile(_add_actions(), source, partition_col, ["id"])+ assert profile.partition_bytes == expected_bytes+ assert profile.files == expected_files++ @parameterized.expand(+ [+ ("no_stats", _add_actions(with_stats=False), ["id"]),+ ("pk_not_first_in_stats", _add_actions(), ["other", "id"]),+ ]+ )+ def test_no_usable_stats_keeps_every_touched_file(self, _name, add_actions, primary_keys):+ source = _source([("a", 5000), ("a", 5001), ("a", 5002)])+ source = source.append_column("other", pa.array([1, 2, 3], pa.int64()))+ assert rewrite_profile(add_actions, source, _PART, primary_keys).partition_bytes == (180,)++ def test_string_keys_are_not_pruned(self):+ # Delta truncates long string stats, so a string max proves nothing.+ add_actions = (+ _add_actions()+ .set_column(4, "max.id", pa.array(["a", "a", "a", "a", "a"], pa.string()))+ .set_column(3, "min.id", pa.array(["a", "a", "a", "a", "a"], pa.string()))+ )+ source = pa.table({_PART: ["a", "a", "a"], "id": ["zzz", "zzzz", "zzzzz"]})+ assert rewrite_profile(add_actions, source, _PART, ["id"]).partition_bytes == (180,)++ @parameterized.expand(+ [+ ("empty_table", _add_actions(files=[])),+ ("empty_source", None),+ ]+ )+ def test_nothing_to_rewrite(self, _name, add_actions):+ source = _source([]) if add_actions is None else _source([("a", 1)])+ profile = rewrite_profile(add_actions if add_actions is not None else _add_actions(), source, _PART, ["id"])+ assert profile == RewriteProfile(partition_bytes=(), files=0)++ @parameterized.expand(+ [+ # 1.5 MB of memory per stored MB, per partition, the largest `mpp` partitions together.+ ("largest_partitions_first", (300 * MB, 200 * MB, 100 * MB), 2, 750.0),+ ("mpp_beyond_partitions", (100 * MB,), 4, 150.0),+ # One worker streams its partition, so its charge stops at the ceiling.+ ("worker_ceiling", (10_000 * MB, 100 * MB), 2, 4096.0 + 150.0),+ ("no_partitions", (), 4, 0.0),+ ]+ )+ def test_rewrite_mb(self, _name, partition_bytes, mpp, expected):+ assert RewriteProfile(partition_bytes=partition_bytes, files=1).rewrite_mb(mpp) == expected++ def test_estimate_reads_a_real_table(self, tmp_path: Path):+ existing = pa.table(+ {+ _PART: ["a"] * 3 + ["b"] * 3 + ["c"] * 3,+ "id": pa.array([1, 2, 3, 101, 102, 103, 201, 202, 203], pa.int64()),+ "v": ["x"] * 9,+ }+ )+ deltalake.write_deltalake(str(tmp_path), existing, partition_by=_PART)+ table = deltalake.DeltaTable(str(tmp_path))+ sizes = {path.split("/")[0]: size for path, size in table._table.get_add_file_sizes().items()}++ profile = estimate_rewrite_profile(table, _source([("a", 2), ("b", 102), ("d", 1)]), _PART, ["id"])++ assert profile is not None+ assert sorted(profile.partition_bytes) == sorted([sizes[f"{_PART}=a"], sizes[f"{_PART}=b"]])+ assert profile.files == 2++ def test_estimate_unreadable_table_is_unknown(self):+ broken = MagicMock()+ broken.get_add_actions.side_effect = RuntimeError("no snapshot")+ assert estimate_rewrite_profile(broken, _source([("a", 1)]), _PART, ["id"]) is None+++class TestSizeUpsertWithRewrite:+ # The production slice: (29 GiB x 0.8 - 2048) / 16.+ _SLOT = 1356.8++ @parameterized.expand(+ [+ # 10 MB source (7.3). Each 100 MB partition adds 150 MB per worker:+ # (4,4) = 220 + 532 + 7.3 + 600 = 1359.3 > slot; (3,5) = 220 + 498.75 + 7.3 + 450 = 1176.05.+ ("many_mid_partitions_step_down", (100 * MB,) * 20, 3, 5, True),+ # Each 300 MB partition adds 450 MB: only one worker fits, (1,8) = 220 + 266 + 7.3 + 450.+ ("many_big_partitions_one_worker", (300 * MB,) * 20, 1, 8, True),+ # 3 GB in one partition: even one worker at the ceiling (4096 MB) overflows the slot.+ ("single_huge_partition", (3_000 * MB,), 1, 4, False),+ # Small files in many partitions barely move the plan.+ ("many_tiny_partitions", (int(0.58 * MB),) * 1_349, 4, 4, True),+ ]+ )+ def test_rewrite_sizes_the_plan(self, _name, partition_bytes, exp_mpp, exp_files, exp_fits):+ rewrite = RewriteProfile(partition_bytes=partition_bytes, files=len(partition_bytes))+ plan = size_upsert(self._SLOT, 10.0, len(partition_bytes), rewrite)+ assert (plan.max_parallel_partitions, plan.max_parallel_files, plan.fits) == (exp_mpp, exp_files, exp_fits)+ assert plan.rewrite_mb == round(rewrite.rewrite_mb(exp_mpp), 1)++ @parameterized.expand(+ [+ ("unknown_sizes", None),+ ("append_with_no_existing_files", RewriteProfile(partition_bytes=(), files=0)),+ ]+ )+ def test_no_rewrite_keeps_todays_plan(self, _name, rewrite):+ assert size_upsert(self._SLOT, 50.0, 4, rewrite) == size_upsert(self._SLOT, 50.0, 4)+++class _FakeTime:+ """A clock that only moves when the governor sleeps, so waits cost no real time."""++ def __init__(self) -> None:+ self.now = 0.0+ self.sleeps = 0++ def clock(self) -> float:+ return self.now++ async def sleep(self, seconds: float) -> None:+ self.sleeps += 1+ self.now += seconds+ await asyncio.sleep(0)+++async def _settle(rounds: int = 5) -> None:+ for _ in range(rounds):+ await asyncio.sleep(0)+++class TestOverSlotReservation:+ # 4 slices of 1000 MB. A 50 MB source plans (4,4) = 788.5. The big upsert rewrites a 2 GB+ # partition: (1,4) = 220 + 133 + 36.5 + 3000 = 3389.5, so it reserves 3.39 slices.+ _BIG = RewriteProfile(partition_bytes=(2_000 * MB,), files=20)++ def _gov(self, mode: str = "enforce", fake: _FakeTime | None = None) -> MemoryGovernor:+ fake = fake or _FakeTime()+ return _governor(mode, limit_mb=4_000.0, max_concurrent=4, clock=fake.clock, sleep=fake.sleep)++ @staticmethod+ async def _enter(gov: MemoryGovernor, rewrite: RewriteProfile | None = None):+ cm = gov.admit(source_bytes=50 * MB, rewrite=rewrite)+ return cm, await cm.__aenter__()++ @staticmethod+ async def _exit(cm) -> None:+ await cm.__aexit__(None, None, None)++ async def test_alone_it_reserves_several_slices_without_waiting(self):+ fake = _FakeTime()+ gov = self._gov(fake=fake)+ cm, adm = await self._enter(gov, self._BIG)+ assert (adm.planned_mpp, adm.capacity_exceeded) == (1, True)+ assert adm.rewrite_mb == 3000.0 and adm.rewrite_total_mb == 2000.0 and adm.rewrite_files == 20+ assert adm.reserved_slots == 3.39 and gov._reserved_mb == 3389.5+ assert (adm.wait_ms, fake.sleeps) == (0, 0)+ await self._exit(cm)+ assert gov._reserved_mb == 0.0 and gov._inflight == 0++ async def test_slice_sized_upserts_never_wait(self):+ async def _no_sleep(_seconds: float) -> None:+ raise AssertionError("a slice-sized admission must not wait")++ gov = _governor("enforce", limit_mb=4_000.0, max_concurrent=4, sleep=_no_sleep)+ held = [await self._enter(gov) for _ in range(4)]+ assert gov._inflight == 4 and all(adm.reserved_slots == 0.79 for _cm, adm in held)+ for cm, _adm in held:+ await self._exit(cm)++ async def test_waits_until_the_reservation_fits(self):+ gov = self._gov()+ held = [await self._enter(gov) for _ in range(3)]+ big = asyncio.create_task(self._enter(gov, self._BIG))+ await _settle()+ assert not big.done()++ # 788.5 + 3389.5 is still above the 4000 MB pod.+ await self._exit(held[0][0])+ await self._exit(held[1][0])+ await _settle()+ assert not big.done()++ await self._exit(held[2][0])+ await _settle()+ cm, adm = big.result()+ assert adm.wait_ms > 0 and adm.wait_timed_out is False+ assert gov._reserved_mb == 3389.5 and not gov._waiters+ await self._exit(cm)++ async def test_newcomers_queue_behind_the_waiter(self):+ gov = self._gov()+ held = [await self._enter(gov) for _ in range(2)]+ big = asyncio.create_task(self._enter(gov, self._BIG))+ await _settle()+ # The small upsert fits beside the two in flight, but must not overtake the big one.+ small = asyncio.create_task(self._enter(gov))+ await _settle()+ assert not big.done() and not small.done()++ for cm, _adm in held:+ await self._exit(cm)+ await _settle()+ assert big.done() and not small.done() # 3389.5 + 788.5 does not fit++ await self._exit(big.result()[0])+ await _settle()+ assert small.done()+ await self._exit(small.result()[0])+ assert gov._reserved_mb == 0.0 and gov._inflight == 0++ async def test_wait_is_bounded_and_then_it_writes(self):+ fake = _FakeTime()+ gov = self._gov(fake=fake)+ held = [await self._enter(gov) for _ in range(3)]+ big = asyncio.create_task(self._enter(gov, self._BIG))+ for _ in range(500):+ if big.done():+ break+ await asyncio.sleep(0)+ cm, adm = big.result()+ assert adm.wait_timed_out is True and adm.wait_ms == 60_000+ assert adm.upsert_kwargs["max_parallel_partitions"] == 1+ # Over-committed on purpose: deltalite always writes.+ assert gov._reserved_mb == 3 * 788.5 + 3389.5 and gov._inflight == 4+ for c in [cm, *(c for c, _adm in held)]:+ await self._exit(c)++ async def test_cancelled_waiter_leaves_the_queue(self):+ gov = self._gov()+ held = [await self._enter(gov) for _ in range(3)]+ big = asyncio.create_task(self._enter(gov, self._BIG))+ await _settle()+ big.cancel()+ with pytest.raises(asyncio.CancelledError):+ await big+ assert not gov._waiters and gov._inflight == 3+ for cm, _adm in held:+ await self._exit(cm)+ # The next admission is not stuck behind a ticket that no longer waits.+ cm, adm = await self._enter(gov)+ assert adm.wait_ms == 0+ await self._exit(cm)++ async def test_advisory_logs_the_reservation_but_never_waits(self):+ fake = _FakeTime()+ gov = self._gov("advisory", fake=fake)+ cm, adm = await self._enter(gov, self._BIG)+ assert adm.upsert_kwargs == {} and adm.reserved_slots == 3.39 and adm.rewrite_mb == 3000.0+ assert (gov._reserved_mb, gov._inflight, fake.sleeps) == (0.0, 0, 0)+ await self._exit(cm)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.pyindex 3eb5f15d8a85..a9c7c9ce7d60 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,6 +26,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delDeltaLiteHandleCache,)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.memory_governor import (+ GovernorConfig,+ MemoryGovernor,+ reset_governor_for_tests,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (DELTA_TABLE_PROPERTIES,ensure_table_properties,@@ -1160,6 +1165,54 @@ class TestDeltaliteWritePath:assert log_kwargs["partitions_touched"] == 1assert "duration_ms" in log_kwargs+ @pytest.mark.asyncio+ async def test_sizes_the_upsert_by_the_files_it_rewrites(self, tmp_path: Path):+ existing_data = pa.table(+ {"id": pa.array([1, 2, 101], pa.int64()), PARTITION_KEY: ["a", "a", "b"], "v": ["x", "y", "z"]}+ )+ deltalake.write_deltalake(str(tmp_path), existing_data, partition_by=PARTITION_KEY)+ existing = deltalake.DeltaTable(str(tmp_path))+ partition_a_bytes = next(+ size+ for path, size in existing._table.get_add_file_sizes().items()+ if path.startswith(f"{PARTITION_KEY}=a/")+ )+ logger = make_logger()+ helper = DeltaTableRef(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=logger)+ fake_table = MagicMock()+ fake_table.upsert.return_value = SimpleNamespace(version=2, rows_inserted=0, rows_updated=1, rows_copied=1)+ fake_deltalite = MagicMock()+ fake_deltalite.DeltaLiteTable.open.return_value = fake_table+ pod = MagicMock()+ pod.limit_mb.return_value = 30_000.0+ pod.current_mb.return_value = 1_000.0+ governor = MemoryGovernor(GovernorConfig(mode="enforce", safety=1.0, reserve_mb=0.0, max_concurrent=15), pod)+ reset_governor_for_tests(governor)+ try:+ 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={}),+ # A fresh open keeps the fake deltalite handle out of the process-wide handle cache.+ patch(f"{DeltaWriter.__module__}._delta_table_identity", return_value=None),+ ):+ wrote = await DeltaWriter(helper)._write_via_deltalite(+ existing_delta_table=existing,+ data=pa.table({"id": pa.array([2], pa.int64()), PARTITION_KEY: ["a"], "v": ["w"]}),+ normalized_primary_keys=["id"],+ use_partitioning=True,+ commit_metadata=None,+ )+ finally:+ reset_governor_for_tests(None)+ assert wrote is True+ log_kwargs = logger.ainfo.call_args.kwargs+ assert log_kwargs["governor_rewrite_files"] == 1+ assert log_kwargs["governor_rewrite_total_mb"] == round(partition_a_bytes / (1024 * 1024), 1)+ assert log_kwargs["governor_rewrite_mb"] is not None+ assert log_kwargs["governor_reserved_slots"] is not None and log_kwargs["governor_wait_ms"] == 0+ assert fake_table.upsert.call_args.kwargs["max_parallel_partitions"] == 1+@pytest.mark.asyncioasync def test_falls_back_when_deltalite_raises(self):helper = self._helper()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.pyindex fc1adaa2d525..a2f07c7a57f2 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@@ -237,6 +237,7 @@ class DeltaWriter:get_handle_cache,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import (+ estimate_rewrite_profile,get_governor,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (@@ -260,8 +261,17 @@ class DeltaWriter:# so all MAX_CONCURRENT_ACTIVITIES upserts on this process are guaranteed to fit. deltalite# always writes — the governor never falls back to the delta-rs MERGE for capacity, because# the MERGE is the *more* memory-hungry path. A source too big for its slice just runs at- # mpp=1 (governor logs a capacity_exceeded ops signal).- async with get_governor().admit(source_bytes=data.nbytes, n_partitions=n_partitions) as adm:+ # mpp=1 (governor logs a capacity_exceeded ops signal). The existing files the merge can+ # rewrite are sized from the handle's add actions, so this costs no object-store request.+ governor = get_governor()+ rewrite = (+ await asyncio.to_thread(+ estimate_rewrite_profile, existing_delta_table, data, partition_key, normalized_primary_keys+ )+ if governor.config.mode != "off"+ else None+ )+ async with governor.admit(source_bytes=data.nbytes, n_partitions=n_partitions, rewrite=rewrite) as adm:def _run_upsert(table: Any, upsert_kwargs: dict[str, int]) -> Any:return table.upsert(@@ -317,6 +327,12 @@ class DeltaWriter:governor_budget_mb=adm.budget_mb,governor_capacity_exceeded=adm.capacity_exceeded,governor_mpp=adm.planned_mpp,+ governor_rewrite_mb=adm.rewrite_mb,+ governor_rewrite_total_mb=adm.rewrite_total_mb,+ governor_rewrite_files=adm.rewrite_files,+ governor_reserved_slots=adm.reserved_slots,+ governor_wait_ms=adm.wait_ms,+ governor_wait_timed_out=adm.wait_timed_out,**_deltalite_write_stats(stats),)DELTALITE_WRITE_TOTAL.labels(outcome="written").inc()