: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 file shape and measure their real peak (#111436)
Tom Owersb609de9eaa99
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 4dc4f591f585..9cecaa93490f 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@@ -10,8 +10,8 @@ per-upsert slice of pod memory. The slice is ``(pod limit × safety − reserve)so however many upserts run at once (up to the pod's ``MAX_CONCURRENT_ACTIVITIES``) their peaks sumto less than the pod. deltalite therefore **always writes** — it never falls back to the delta-rsMERGE for capacity, because the MERGE is the *more* memory-hungry path and falling back to it under-pressure is exactly what would OOM the pod. A source too big for its slice runs at ``mpp=1`` (the-memory floor, still far below the MERGE) and raises an ops signal, rather than falling back.+pressure is exactly what would OOM the pod. A source too big for its slice runs at the smallest+plan (the memory floor, still far below the MERGE) and raises an ops signal, rather than falling back.Two layers, by design:@@ -19,45 +19,39 @@ Two layers, by design:per-upsert slices (one per concurrent activity) and sizes each upsert's knobs to its slice, sothe concurrent upserts always fit. Memory for *non-deltalite* writers (full syncs, the raregenuine-error MERGE fallback whose RSS tracks table size, interpreter and allocator slack) is- held back up front as ``reserve_mb``. It also reads live cgroup usage to log the actual memory- delta against the prediction, for calibration.+ held back up front as ``reserve_mb``. It also samples the process RSS while each upsert runs,+ so the logs carry the real peak next to the prediction.* ``deltalite_core::limits`` (the ``DELTALITE_PROCESS_*`` env ceilings) is the **hard backstop**in Rust: process-global semaphores that cap total in-flight work regardless of what thegovernor 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 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 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.+The memory model follows the shape of the files a merge rewrites, not their total size. A+partition worker in deltalite 0.1.9 holds three things at its peak:++* **Readers.** Each of its ``max_parallel_files`` readers fetches one whole compressed row group+ before it decodes it, and no budget covers that fetch. A worker therefore holds about the sum of+ its largest ``max_parallel_files`` candidate row groups.+* **Writer.** The write buffer grows to ``target_file_size`` before it flushes, and the flush+ copies it once more. A partition that writes less than the target only buffers what it writes.+* **Decode.** Decoded survivor batches in flight, capped per call by ``max_buffered_bytes``.++Profiling on Linux showed that peak memory does not grow with the partition count, the file count+or the total bytes a merge rewrites — only with these per-worker terms. The terms are named+constants, so a deltalite release that budgets the fetch or streams the write changes one number."""from __future__ import annotationsimport osimport time+import heapqimport asyncioimport loggingimport threadingimport contextlib-from collections import defaultdict, deque-from collections.abc import AsyncIterator, Awaitable, Callable, Sequence+from collections import deque+from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Literal@@ -68,6 +62,12 @@ import pyarrow.compute as pcfrom posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.rss_sampler import (+ RssPeakSampler,+ RssWindow,+ psutil_rss_mb,+)+if TYPE_CHECKING:import deltalake@@ -87,36 +87,65 @@ _DEFAULT_MAX_CONCURRENT = 100#: an env var so the governor uses the loader's actual source of truth. None until declared._PROCESS_MAX_CONCURRENT: int | None = None-# --- Memory model coefficients (threaded process model; REPORT.md §5.6, deltalite_planner's-# ProcessCalibration) ---------------------------------------------------------------------------+# --- File-shape memory model (deltalite 0.1.9) -------------------------------------------------#-# Production runs upserts as concurrent threads in ONE worker process. They share the interpreter,-# tokio runtime and object-store pools (paid once, covered by ``reserve_mb``) and, crucially, do not-# peak at the same instant — so the memory ONE upsert adds is far below its standalone peak. Measured-# (bench/threaded_bench.py): ~0.73 MB per MB of source, ~133 MB per concurrent partition worker, on a-# ~220 MB per-upsert base. This replaces the old single-upsert coefficients (floor 300 + 2·source +-# 250·mpp + buffer), which over-predicted ~2-3x and needlessly capped mpp — validated on prod, where-# observed per-upsert cgroup deltas were a small fraction of the single-upsert estimate.--#: Per concurrent upsert, before any partition worker or source (snapshot/log state, plan, channels).-_MARGINAL_BASE_MB = 220.0-#: Additional per concurrent upsert, per ``max_parallel_partitions`` worker.-_MARGINAL_PER_WORKER_MB = 133.0-#: Additional per concurrent upsert, per MB of that upsert's source batch.-_MARGINAL_PER_SOURCE_MB = 0.73+# Fitted on a Linux harness that runs the loader's exact upsert (glibc, 30-column tables): small+# files over 100 to 1,000 partitions, single partitions of 57 MB and 99 MiB single-row-group files,+# and four partitions of 57 MB files, with max_parallel_files 1, 2 and 4 and target_file_size 32+# and 100 MiB. The model predicts malloc in-use bytes; ``_rss_retention`` turns that into RSS,+# which is what the cgroup limit counts.++#: Resident bytes per stored byte of the row group one reader fetches. deltalite 0.1.9 fetches the+#: whole compressed row group before it decodes it, outside every budget. Lower this when deltalite+#: budgets or streams the fetch.+_READER_BYTES_PER_ROW_GROUP_BYTE = 1.0+#: Each reader also holds decompressed pages next to the fetched row group: ~22 MB per reader on+#: 57 MB and 99 MiB row groups of the 30-column harness tables, far less on small row groups.+_READER_PAGE_BUFFER_MB = 22.0+#: Cap on the page buffers as a share of the row group, which keeps small row groups small.+_READER_PAGE_BUFFER_SHARE = 0.4+#: Resident bytes per byte of ``target_file_size`` in one partition worker's writer: the buffer+#: grows to the target before it flushes, and the flush copies it. Lower this when deltalite+#: streams the write.+_WRITER_BYTES_PER_TARGET_BYTE = 2.3+#: Part of ``max_buffered_bytes`` that decoded batches actually fill at the peak.+_DECODE_BUDGET_FILL = 0.875+#: Decoded bytes per stored byte, used only to cap the decode term for small files.+_DECODED_BYTES_PER_STORED_BYTE = 1.5+#: Per upsert, before any partition worker: channels, tasks, the commit.+_BASE_INUSE_MB = 6.0+#: Per candidate file, the plan state deltalite keeps for it (its add action, the remove it may+#: write). Fitted on 600 to 6,000 candidate files.+_PLAN_KB_PER_CANDIDATE_FILE = 2.6+#: Per upsert, per MB of its source batch (the cast copy and the PK sets). Kept from the earlier+#: threaded benchmark: the harness sources were too small to fit it again.+_SOURCE_INUSE_PER_MB = 0.73+#: deltalite keeps one add action per table file in its snapshot. Measured at ~2.2 KB per file on+#: the 30-column harness tables (6,000 files hold 12 MB more than 600 files).+_SNAPSHOT_KB_PER_FILE = 2.2+#: deltalite and delta-rs both default to 100 MiB when the table does not set ``delta.targetFileSize``.+_DEFAULT_TARGET_FILE_SIZE = 100 * MB++#: RSS per byte of malloc in-use memory. glibc keeps freed memory in its arenas, and with its+#: default mmap threshold the large Arrow buffers stay there too. RSS ran 1.25–2.1× in-use in most+#: cases and 4.8× in one, so this is a middle value, not a bound.+_RSS_RETENTION_GLIBC_DEFAULT = 2.0+#: With ``MALLOC_MMAP_THRESHOLD_`` at 128 KiB, large buffers go back to the kernel on free: RSS ran+#: 1.2–1.4× in-use.+_RSS_RETENTION_LOW_MMAP_THRESHOLD = 1.4+#: Highest ``MALLOC_MMAP_THRESHOLD_`` that earns the lower retention. 1 MiB still retained 1.6×.+_LOW_MMAP_THRESHOLD_BYTES = 256 * 1024+#: Beyond 4 partition workers the measured wall-clock gains vanish while memory keeps climbing._MAX_PARALLEL_PARTITIONS = 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.+#: Concurrent file readers inside one partition worker at deltalite's own default.+_DEFAULT_FILES_PER_WORKER = 4+#: Most readers one partition worker may run. A partition with few, small row groups gains I/O+#: overlap from more; the reader term charges every extra reader its row group._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+#: Ceiling on ``max_parallel_partitions × max_parallel_files`` for one upsert, the process-wide+#: reader limit deltalite enforces by default.+_MAX_READERS_PER_UPSERT = 16#: 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@@ -125,39 +154,89 @@ _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+#: How often the RSS sampler reads the process RSS while an upsert runs.+_DEFAULT_RSS_SAMPLE_MS = 100.0+++def _rss_retention(environ: Mapping[str, str] = os.environ) -> float:+ """RSS per in-use byte for this process's allocator settings.++ glibc reads ``MALLOC_MMAP_THRESHOLD_`` at startup from this same environment, so the variable+ says which retention applies. ``DELTALITE_GOVERNOR_RSS_RETENTION`` overrides both.+ """+ explicit = environ.get("DELTALITE_GOVERNOR_RSS_RETENTION", "").strip()+ if explicit:+ try:+ return max(1.0, float(explicit))+ except ValueError:+ logger.warning("invalid DELTALITE_GOVERNOR_RSS_RETENTION=%r; ignoring it", explicit)+ threshold = environ.get("MALLOC_MMAP_THRESHOLD_", "").strip()+ try:+ if threshold and int(threshold) <= _LOW_MMAP_THRESHOLD_BYTES:+ return _RSS_RETENTION_LOW_MMAP_THRESHOLD+ except ValueError:+ pass+ return _RSS_RETENTION_GLIBC_DEFAULT@frozen-class RewriteProfile:- """Stored bytes of the existing files one merge can rewrite, per touched partition."""+class PartitionShape:+ """The part of one touched partition that sizes its worker."""- #: Largest first. A touched partition with no candidate files is left out.- partition_bytes: tuple[int, ...]- #: Candidate files over all touched partitions.+ #: Stored bytes of the largest files the merge can rewrite, largest first. Only as many as one+ #: worker can read at once are kept; each bounds the row group a reader fetches.+ largest_file_bytes: tuple[int, ...]+ #: All candidate files in the partition, and their stored bytes.files: int+ stored_bytes: int+ #: Bytes of the source rows that land in this partition.+ source_bytes: int = 0++ @staticmethod+ def of(file_bytes: Sequence[int], source_bytes: int = 0) -> PartitionShape:+ ordered = sorted(file_bytes, reverse=True)+ return PartitionShape(+ largest_file_bytes=tuple(ordered[:_MAX_PARALLEL_FILES]),+ files=len(ordered),+ stored_bytes=sum(ordered),+ source_bytes=source_bytes,+ )+++@frozen+class RewriteProfile:+ """The touched partitions of one merge, read from the table's add actions."""++ #: One entry per touched partition, including partitions that only receive inserts.+ partitions: tuple[PartitionShape, ...]+ #: Files in the whole table. deltalite holds an add action for each of them.+ table_files: int = 0+ #: The table's ``delta.targetFileSize``, which deltalite uses as its write-buffer flush point.+ target_file_size: int = _DEFAULT_TARGET_FILE_SIZE++ @property+ def files(self) -> int:+ return sum(p.files for p in self.partitions)@propertydef total_mb(self) -> float:- return sum(self.partition_bytes) / MB+ return sum(p.stored_bytes for p in self.partitions) / 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]- )+ @property+ def max_row_group_mb(self) -> float:+ """Upper bound on the largest row group a reader fetches: the largest candidate file.++ Add actions carry each file's size but not its row-group count, and the footer that has it+ costs one request per file. A file holds at least one row group, so its size bounds its+ largest one. The bound is exact for single-row-group files, which is what deltalite and+ delta-rs write while a file stays under the 1M-row row-group limit. For files with several+ row groups it over-counts (about 1.5× on 2–3 row-group files), so it errs toward a smaller plan.+ """+ return max((p.largest_file_bytes[0] for p in self.partitions if p.largest_file_bytes), default=0) / MBdef _files_that_can_match(add_actions: pa.Table, source: pa.Table, primary_keys: Sequence[str]) -> list[bool]:@@ -195,16 +274,21 @@ def _files_that_can_match(add_actions: pa.Table, source: pa.Table, primary_keys:def rewrite_profile(- add_actions: pa.Table, source: pa.Table, partition_col: str | None, primary_keys: Sequence[str]+ add_actions: pa.Table,+ source: pa.Table,+ partition_col: str | None,+ primary_keys: Sequence[str],+ target_file_size: int = _DEFAULT_TARGET_FILE_SIZE,) -> 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.+ batch. Every candidate is counted because duplicate target keys can make one source row match+ several files. Every touched partition gets an entry with its share of the source, also when it+ has no candidate files."""- if add_actions.num_rows == 0 or source.num_rows == 0:- return RewriteProfile(partition_bytes=(), files=0)+ if source.num_rows == 0:+ return RewriteProfile(partitions=(), table_files=add_actions.num_rows, target_file_size=target_file_size)if partition_col is None:rows_per_partition: dict[str | None, int] = {None: source.num_rows}@@ -215,21 +299,38 @@ def rewrite_profile(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()+ file_partitions = (+ add_actions[f"partition.{partition_col}"].cast(pa.string()).to_pylist() if add_actions.num_rows else []+ )++ sizes_by_partition: dict[str | None, list[int]] = {partition: [] for partition in rows_per_partition}+ if add_actions.num_rows:+ 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 sizes_by_partition:+ sizes_by_partition[partition].append(size or 0)++ bytes_per_row = source.nbytes / source.num_rows+ partitions = [+ PartitionShape.of(+ sizes,+ source_bytes=round(bytes_per_row * rows_per_partition[partition]),+ )+ for partition, sizes in sizes_by_partition.items()+ ]+ return RewriteProfile(+ partitions=tuple(sorted(partitions, key=lambda p: p.stored_bytes + p.source_bytes, reverse=True)),+ table_files=add_actions.num_rows,+ target_file_size=target_file_size,+ )- 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 _table_target_file_size(table: deltalake.DeltaTable) -> int:+ raw = table.metadata().configuration.get("delta.targetFileSize")+ try:+ return int(raw) if raw and int(raw) > 0 else _DEFAULT_TARGET_FILE_SIZE+ except ValueError:+ return _DEFAULT_TARGET_FILE_SIZEdef estimate_rewrite_profile(@@ -238,12 +339,122 @@ def estimate_rewrite_profile("""``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+ return rewrite_profile(add_actions, source, partition_col, primary_keys, _table_target_file_size(table))+ except Exception as e: # noqa: BLE001 - an estimate must never fail a write; None sizes conservativelylogger.debug("deltalite governor: could not estimate the rewrite size: %s", e)return None+@frozen+class MemoryEstimate:+ """Predicted peak of one upsert, by term, in MB."""++ reader_mb: float+ writer_mb: float+ decode_mb: float+ #: Plan state, the source batch and the table snapshot.+ fixed_mb: float+ #: malloc in-use bytes at the peak: the sum of the terms above.+ inuse_mb: float+ #: ``inuse_mb`` times the allocator's retention: what the cgroup limit counts.+ rss_mb: float+++@frozen+class WorkerTerms:+ """Memory terms for one partition worker."""++ reader_mb: float+ writer_mb: float+ held_mb: float+++@frozen+class WorkerBounds:+ """Independent upper bounds for worker memory terms."""++ terms: tuple[WorkerTerms, ...]+ held_mb: tuple[float, ...]+++def _worker_terms(shape: PartitionShape, files_per_worker: int, target_mb: float) -> WorkerTerms:+ row_groups_mb = [size / MB for size in shape.largest_file_bytes[:files_per_worker]]+ held = sum(row_groups_mb)+ pages = sum(min(_READER_PAGE_BUFFER_MB, _READER_PAGE_BUFFER_SHARE * rg) for rg in row_groups_mb)+ written = (shape.stored_bytes + shape.source_bytes) / MB+ return WorkerTerms(+ reader_mb=_READER_BYTES_PER_ROW_GROUP_BYTE * held + pages,+ writer_mb=_WRITER_BYTES_PER_TARGET_BYTE * min(target_mb, written),+ held_mb=held,+ )+++def _unknown_shapes(n_partitions: int | None, source_mb: float, target_mb: float) -> tuple[PartitionShape, ...]:+ """Stand-in partitions when the add actions could not be read.++ Every worker is assumed to rewrite single-row-group files of ``target_file_size``: the largest+ row group the writers of these tables produce. The guess is conservative, so a failed estimate+ errs toward a smaller plan.+ """+ count = max(1, min(n_partitions or _MAX_PARALLEL_PARTITIONS, _MAX_PARALLEL_PARTITIONS))+ shape = PartitionShape.of([round(target_mb * MB)] * _MAX_PARALLEL_FILES, source_bytes=round(source_mb * MB / count))+ return (shape,) * count+++def _costliest_workers(profile: RewriteProfile, files_per_worker: int) -> WorkerBounds:+ """Independent bounds for the costliest workers' reader/writer and decode terms."""+ target_mb = profile.target_file_size / MB+ terms = [_worker_terms(shape, files_per_worker, target_mb) for shape in profile.partitions]+ return WorkerBounds(+ terms=tuple(+ heapq.nlargest(+ _MAX_PARALLEL_PARTITIONS,+ terms,+ key=lambda worker: worker.reader_mb + worker.writer_mb,+ )+ ),+ held_mb=tuple(heapq.nlargest(_MAX_PARALLEL_PARTITIONS, (worker.held_mb for worker in terms))),+ )+++def predict_upsert_memory(+ profile: RewriteProfile,+ source_mb: float,+ mpp: int,+ files_per_worker: int,+ buffered_bytes: int = _DEFAULT_BUFFERED_BYTES,+ retention: float = _RSS_RETENTION_GLIBC_DEFAULT,+ costliest: WorkerBounds | None = None,+) -> MemoryEstimate:+ """Peak memory of one upsert with ``mpp`` partition workers of ``files_per_worker`` readers.++ Reader/writer and decode occupancy use independent upper bounds across the ``mpp`` costliest+ partitions. ``costliest`` is ``_costliest_workers(profile, files_per_worker)`` when the caller+ already has it.+ """+ if costliest is None:+ costliest = _costliest_workers(profile, files_per_worker)+ workers = costliest.terms[:mpp]+ reader_mb = sum(w.reader_mb for w in workers)+ writer_mb = sum(w.writer_mb for w in workers)+ held_mb = sum(costliest.held_mb[:mpp])+ decode_mb = _DECODE_BUDGET_FILL * min(buffered_bytes / MB, _DECODED_BYTES_PER_STORED_BYTE * held_mb)+ fixed_mb = (+ _BASE_INUSE_MB+ + _SOURCE_INUSE_PER_MB * source_mb+ + (_SNAPSHOT_KB_PER_FILE * profile.table_files + _PLAN_KB_PER_CANDIDATE_FILE * profile.files) / 1024+ )+ inuse_mb = reader_mb + writer_mb + decode_mb + fixed_mb+ return MemoryEstimate(+ reader_mb=round(reader_mb, 1),+ writer_mb=round(writer_mb, 1),+ decode_mb=round(decode_mb, 1),+ fixed_mb=round(fixed_mb, 1),+ inuse_mb=round(inuse_mb, 1),+ rss_mb=round(inuse_mb * retention, 1),+ )++@dataclass(frozen=True)class UpsertPlan:"""A sizing decision for one upsert: the knobs, and the memory it is predicted to add."""@@ -251,13 +462,12 @@ class UpsertPlan:max_parallel_partitions: intmax_parallel_files: intmax_buffered_bytes: int- #: Predicted marginal peak RSS this upsert adds while running concurrently with others, in MB.+ #: Predicted peak RSS this upsert adds, in MB. The slice is an RSS budget, so this is what fits it.predicted_peak_mb: float- #: False when even a single worker exceeds the available slice.+ #: False when even the smallest plan exceeds the available slice.fits: bool+ estimate: MemoryEstimateprobe_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 {@@ -268,29 +478,10 @@ class UpsertPlan:}-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, 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 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.- ``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- + rewrite_mb- )+def _reader_options(mpp: int) -> list[int]:+ """Readers per worker to try at ``mpp`` workers, most first, under ``_MAX_READERS_PER_UPSERT``."""+ widest = max(1, min(_MAX_PARALLEL_FILES, _MAX_READERS_PER_UPSERT // mpp))+ return sorted({f for f in (widest, _DEFAULT_FILES_PER_WORKER, 2, 1) if f <= widest}, reverse=True)def size_upsert(@@ -298,42 +489,48 @@ def size_upsert(source_mb: float,n_partitions: int | None = None,rewrite: RewriteProfile | None = None,+ retention: float = _RSS_RETENTION_GLIBC_DEFAULT,) -> 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. 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``. ``rewrite=None`` (sizes unknown) charges no rewrite memory.+ """Pick the widest plan whose predicted peak RSS fits ``available_mb``.++ ``available_mb`` is the per-upsert memory slice, not the whole pod. Partition workers come+ first: the search starts at the most workers and, for each count, tries the most readers per+ worker before fewer. A worker's readers cost its largest row groups, so a partition of big+ single-row-group files steps its readers down before the plan loses a worker. When no plan+ fits, return one worker with one reader and ``fits=False``. The caller does not fall back on+ ``fits=False`` — it runs deltalite with that plan anyway (the memory floor, far below the MERGE)+ and flags ``capacity_exceeded``. ``rewrite=None`` (shape unknown) assumes target-sized files."""- partition_cap = _MAX_PARALLEL_PARTITIONS+ profile = rewrite+ if profile is None:+ target_mb = _DEFAULT_TARGET_FILE_SIZE / MB+ profile = RewriteProfile(partitions=_unknown_shapes(n_partitions, source_mb, target_mb))+ elif not profile.partitions:+ # An empty source touches no partition; size it as one worker that writes nothing.+ profile = RewriteProfile(+ partitions=(PartitionShape.of([]),),+ table_files=profile.table_files,+ target_file_size=profile.target_file_size,+ )++ partition_cap = min(_MAX_PARALLEL_PARTITIONS, max(1, len(profile.partitions)))if n_partitions is not None and n_partitions >= 1:partition_cap = min(partition_cap, n_partitions)+ # One pass over the partitions per reader count, however many plans are tried.+ costliest: dict[int, WorkerBounds] = {}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, rewrite_mb)- if predicted <= available_mb:- 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),- )+ for files in _reader_options(mpp):+ if files not in costliest:+ costliest[files] = _costliest_workers(profile, files)+ estimate = predict_upsert_memory(+ profile, source_mb, mpp, files, retention=retention, costliest=costliest[files]+ )+ if estimate.rss_mb <= available_mb:+ return UpsertPlan(mpp, files, _DEFAULT_BUFFERED_BYTES, estimate.rss_mb, fits=True, estimate=estimate)++ estimate = predict_upsert_memory(profile, source_mb, 1, 1, retention=retention)+ return UpsertPlan(1, 1, _DEFAULT_BUFFERED_BYTES, estimate.rss_mb, fits=False, estimate=estimate)# --- Reading the pod's real memory (cgroup v2, with v1 and psutil fallbacks) -----------------@@ -345,7 +542,8 @@ class PodMemory:cgroup v2 (``memory.max`` / ``memory.current``) first, then v1(``memory.limit_in_bytes`` / ``memory.usage_in_bytes``), then psutil for usage on hosts withno cgroup (local dev / macOS). The limit is read once and cached (it does not change under a- running pod); usage is read live on every admission.+ running pod). Usage counts page cache and every other upsert on the pod, so it sizes nothing+ here; compaction logs it as context."""_V2_MAX = "/sys/fs/cgroup/memory.max"@@ -396,12 +594,7 @@ class PodMemory:v = self._read_int(path)if v is not None:return v / MB- try:- import psutil-- return psutil.Process().memory_info().rss / MB- except Exception: # noqa: BLE001 - no cgroup and no psutil: caller degrades to conservative mode- return None+ return psutil_rss_mb()# --- Governor configuration ------------------------------------------------------------------@@ -450,6 +643,10 @@ class GovernorConfig:#: 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+ #: How often the RSS sampler reads the process RSS while an upsert runs. 0 turns sampling off.+ rss_sample_ms: float = _DEFAULT_RSS_SAMPLE_MS+ #: RSS per byte of predicted in-use memory. Read from the allocator settings by default.+ rss_retention: float = _RSS_RETENTION_GLIBC_DEFAULT@staticmethoddef from_env() -> GovernorConfig:@@ -465,6 +662,8 @@ class GovernorConfig: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)),+ rss_sample_ms=max(0.0, _env_float("DELTALITE_GOVERNOR_RSS_SAMPLE_MS", _DEFAULT_RSS_SAMPLE_MS)),+ rss_retention=_rss_retention(),)@staticmethod@@ -504,8 +703,8 @@ class Admission:There is no "decline": deltalite ALWAYS writes. The governor only decides how many partitionworkers this upsert may use, sized to a fixed per-upsert slice of pod memory so all``max_concurrent`` upserts are guaranteed to fit. If a source is so big that even one worker- exceeds its slice, ``capacity_exceeded`` is set and we still run deltalite at ``mpp=1`` (the- memory floor, still far below the MERGE) rather than fall back to it.+ exceeds its slice, ``capacity_exceeded`` is set and we still run deltalite with the smallest+ plan (the memory floor, still far below the MERGE) rather than fall back to it."""upsert_kwargs: dict[str, int]@@ -513,20 +712,26 @@ class Admission:predicted_peak_mb: float | None#: The per-upsert memory slice this upsert was sized against, in MB.budget_mb: float | None- #: The max_parallel_partitions the governor would use — recorded in every mode (including- #: advisory, where ``upsert_kwargs`` stays empty) so we can see the planned parallelism.+ #: The max_parallel_partitions and max_parallel_files the governor would use — recorded in+ #: every mode (including advisory, where ``upsert_kwargs`` stays empty) so we can see the plan.planned_mpp: int | None = None- #: True when even mpp=1 overflows the slice: an ops signal to chunk the source, raise the pod- #: limit, or lower max_concurrent. Not a failure — deltalite still runs at mpp=1.+ planned_mpf: int | None = None+ #: True when even the smallest plan overflows the slice: an ops signal to chunk the source,+ #: raise the pod limit, or lower max_concurrent. Not a failure — deltalite still runs.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+ #: The predicted peak by term, in-use and RSS.+ estimate: MemoryEstimate | None = None+ #: Largest candidate file, the bound on the largest row group a reader fetches. None when unknown.+ max_row_group_mb: float | None = None#: Stored MB of all candidate files the merge can rewrite, over every touched partition.rewrite_total_mb: float | None = Nonerewrite_files: int | None = None- #: Slices this upsert holds (enforce) or would hold (advisory). Above 1 when even mpp=1 overflows.+ #: Upserts admitted in this process at admission, this one included (every mode but off).+ concurrent_upserts: int | None = None+ #: What the RSS sampler saw from admission to release. Process-wide: see ``RssPeakSampler``.+ rss: RssWindow | None = field(default=None)+ #: Slices this upsert holds (enforce) or would hold (advisory). Above 1 when even the smallest+ #: plan overflows.reserved_slots: float | None = None#: Time spent waiting for room before the write, and whether the wait ran out.wait_ms: int = 0@@ -555,6 +760,7 @@ class MemoryGovernor:*,clock: Callable[[], float] = time.monotonic,sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,+ rss_sampler: RssPeakSampler | None = None,) -> None:self.config = config or GovernorConfig.from_env()self.pod = pod or PodMemory(limit_override_mb=self.config.limit_override_mb)@@ -566,6 +772,11 @@ class MemoryGovernor:#: Tickets of admissions waiting for room, oldest first.self._waiters: deque[int] = deque()self._next_ticket = 0+ #: Admissions in flight in every mode but off, for the concurrency the logs report.+ self._active = 0+ self._sampler = rss_sampler+ if self._sampler is None and self.config.rss_sample_ms > 0:+ self._sampler = RssPeakSampler(self.config.rss_sample_ms / 1000)# -- accounting --------------------------------------------------------------------------@@ -643,6 +854,7 @@ class MemoryGovernor:is held for the whole ``with`` block and released on exit, even on exception. In enforcemode an upsert predicted above its slice reserves up to the whole usable pod, and entrywaits (bounded by ``max_wait_s``) until the reservation fits beside the ones in flight.+ In every mode but off, the process RSS is sampled from the end of any wait until exit."""source_mb = source_bytes / MB@@ -651,56 +863,62 @@ class MemoryGovernor:returnlimit_mb = self.pod.limit_mb()+ plan: UpsertPlan | None = None+ budget_mb: float | None = None+ usable_mb = reserve_mb = 0.0# No cgroup limit visible (local dev / unreadable): we can't size a slice, so use deltalite's# own defaults. Still always deltalite.- if limit_mb is None:- yield Admission({}, self.config.mode, None, None)- return-- budget_mb = self._per_upsert_budget_mb(limit_mb)- 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)+ if limit_mb is not None:+ budget_mb = self._per_upsert_budget_mb(limit_mb)+ usable_mb = budget_mb * self.config.max_concurrent+ plan = size_upsert(budget_mb, source_mb, n_partitions, rewrite, self.config.rss_retention)+ # 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)# Only enforce reserves against the budget (and may wait for room); advisory is a pure# no-op on the accounting.admitted = Falsewaited_s, timed_out = 0.0, False- if self.config.mode == "enforce":+ if plan is not None and self.config.mode == "enforce":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()+ with self._lock:+ self._active += 1+ concurrent = self._activeadm = Admission(- upsert_kwargs=plan.as_upsert_kwargs() if admitted else {},+ upsert_kwargs=plan.as_upsert_kwargs() if plan is not None and admitted else {},mode=self.config.mode,- predicted_peak_mb=plan.predicted_peak_mb,- 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,+ predicted_peak_mb=plan.predicted_peak_mb if plan is not None else None,+ budget_mb=round(budget_mb, 1) if budget_mb is not None else None,+ planned_mpp=plan.max_parallel_partitions if plan is not None else None,+ planned_mpf=plan.max_parallel_files if plan is not None else None,+ capacity_exceeded=plan is not None and not plan.fits,+ estimate=plan.estimate if plan is not None else None,+ max_row_group_mb=round(rewrite.max_row_group_mb, 1) 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,+ concurrent_upserts=concurrent,+ reserved_slots=round(reserve_mb / budget_mb, 2) if budget_mb else None,wait_ms=round(waited_s * 1000),wait_timed_out=timed_out,)- self._emit_decision(adm, source_mb)+ if plan is not None:+ self._emit_decision(adm, source_mb)try:- yield adm+ # Sampling starts after any wait, so the window covers the write itself.+ if self._sampler is None:+ yield adm+ else:+ with self._sampler.window() as window:+ adm.rss = window+ yield admfinally:- if admitted:- with self._lock:+ with self._lock:+ self._active -= 1+ if admitted: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:- now = self.pod.current_mb()- if now is not None:- adm.observed_delta_mb = round(now - current_at_admit, 1)# -- observability -----------------------------------------------------------------------@@ -708,11 +926,11 @@ 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 with %.0f MB of rewrite memory exceeds its "- "%.0f MB per-upsert slice (max_concurrent=%d); running deltalite at mpp=1 and "+ "deltalite governor: source %.0f MB with %.0f MB row groups exceeds its %.0f MB "+ "per-upsert slice (max_concurrent=%d); running deltalite at mpp=1, mpf=1 and ""reserving %.2f slices (waited %d ms, timed out: %s).",source_mb,- adm.rewrite_mb or 0.0,+ adm.max_row_group_mb or 0.0,adm.budget_mb or 0.0,self.config.max_concurrent,adm.reserved_slots or 0.0,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/rss_sampler.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/rss_sampler.pynew file mode 100644index 000000000000..e1b1e245c218--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/rss_sampler.py@@ -0,0 +1,136 @@+"""A process RSS sampler that measures the real peak of each deltalite upsert.++The governor predicts an upsert's peak before it runs; this measures it while it runs. One daemon+thread reads ``/proc/self/statm`` at a fixed interval while at least one upsert window is open,+and every open window keeps the highest value it saw.+"""++from __future__ import annotations++import resource+import threading+import contextlib+from collections.abc import Callable, Iterator+from dataclasses import dataclass++MB = 1024 * 1024++_PAGE_SIZE = resource.getpagesize()+++def psutil_rss_mb() -> float | None:+ try:+ import psutil++ return psutil.Process().memory_info().rss / MB+ except Exception: # noqa: BLE001 - no psutil: the caller treats None as unknown+ return None+++def read_process_rss_mb() -> float | None:+ """This process's resident set in MB: one small ``/proc`` read on Linux, psutil elsewhere."""+ try:+ with open("/proc/self/statm", "rb") as f:+ return int(f.read().split()[1]) * _PAGE_SIZE / MB+ except (OSError, ValueError, IndexError):+ return psutil_rss_mb()+++# Identity equality: two windows with the same readings are still different upserts.+@dataclass(frozen=False, eq=False)+class RssWindow:+ """What the sampler saw while one upsert ran. RSS is process-wide, so concurrent upserts share it."""++ start_mb: float | None = None+ peak_mb: float | None = None+ #: Most upserts that had a window open at the same time as this one, itself included.+ max_concurrent: int = 1+ samples: int = 0++ def observe(self, rss_mb: float | None) -> None:+ if rss_mb is None:+ return+ self.samples += 1+ rss_mb = round(rss_mb, 1)+ self.peak_mb = rss_mb if self.peak_mb is None else max(self.peak_mb, rss_mb)++ @property+ def delta_mb(self) -> float | None:+ if self.start_mb is None or self.peak_mb is None:+ return None+ return round(self.peak_mb - self.start_mb, 1)+++class RssPeakSampler:+ """One daemon thread that samples process RSS while at least one upsert window is open.++ The thread starts with the first open window and exits once the last one closes, so an idle+ process runs no sampler. Each sample is one ``/proc/self/statm`` read, shared by every open+ window. The peak is process-wide: with other upserts in flight it covers their memory too, so+ ``RssWindow.max_concurrent`` says when a window ran alone. glibc reuses memory it kept from+ earlier upserts without growing RSS, so a delta can also read low after a larger upsert.+ """++ def __init__(self, interval_s: float, read_rss_mb: Callable[[], float | None] = read_process_rss_mb) -> None:+ self._interval_s = interval_s+ self._read = read_rss_mb+ self._lock = threading.Lock()+ self._open: list[RssWindow] = []+ self._wake = threading.Event()+ self._thread: threading.Thread | None = None++ def _safe_read(self) -> float | None:+ try:+ return self._read()+ except Exception: # noqa: BLE001 - a failed read is a missing sample, never an error+ return None++ def _run(self) -> None:+ me = threading.current_thread()+ try:+ while True:+ self._wake.wait(self._interval_s)+ rss_mb = self._safe_read()+ with self._lock:+ self._wake.clear()+ # Exit under the same lock that a new window checks, so a window that opens+ # now either sees this thread still running or starts a new one.+ if not self._open:+ self._thread = None+ return+ for window in self._open:+ window.observe(rss_mb)+ except BaseException:+ with self._lock:+ if self._thread is me:+ self._thread = None+ raise++ @contextlib.contextmanager+ def window(self) -> Iterator[RssWindow]:+ start = self._safe_read()+ window = RssWindow(start_mb=round(start, 1) if start is not None else None)+ window.observe(start)+ with self._lock:+ self._open.append(window)+ running = len(self._open)+ for other in self._open:+ other.max_concurrent = max(other.max_concurrent, running)+ if self._thread is None:+ self._wake.clear()+ self._thread = threading.Thread(target=self._run, name="deltalite-rss-sampler", daemon=True)+ self._thread.start()+ try:+ yield window+ finally:+ end = self._safe_read()+ with self._lock:+ self._open.remove(window)+ window.observe(end)+ if not self._open:+ self._wake.set()++ def thread(self) -> threading.Thread | None:+ """The running sampler thread, if any. Tests only."""+ with self._lock:+ return self._threaddiff --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 685dd13ed2af..63e6b8a35aa1 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@@ -15,14 +15,17 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delMB,GovernorConfig,MemoryGovernor,+ PartitionShape,PodMemory,RewriteProfile,- _predict_marginal_mb,+ _rss_retention,configure_process_concurrency,estimate_rewrite_profile,+ predict_upsert_memory,rewrite_profile,size_upsert,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.rss_sampler import RssPeakSampler@pytest.fixture(autouse=True)@@ -50,38 +53,162 @@ class _FakePod(PodMemory):def _governor(- mode="enforce", *, limit_mb=30_000.0, current_mb=1_000.0, max_concurrent=15, clock=None, sleep=None, **cfg+ mode="enforce",+ *,+ limit_mb=30_000.0,+ current_mb=1_000.0,+ max_concurrent=15,+ clock=None,+ sleep=None,+ rss_sampler=None,+ **cfg,) -> MemoryGovernor:# Clean arithmetic defaults: no safety derate, no reserve, so the per-upsert slice is exactly- # limit / max_concurrent.+ # limit / max_concurrent. No real RSS sampling unless a test passes a sampler.+ cfg.setdefault("rss_sample_ms", 0.0)config = GovernorConfig(mode=mode, safety=1.0, reserve_mb=0.0, max_concurrent=max_concurrent, **cfg)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)+ return MemoryGovernor(config, _FakePod(limit_mb, current_mb), rss_sampler=rss_sampler, **timing)+++def _profile(*partitions: list[float], target_mb: float = 100.0, table_files: int = 0) -> RewriteProfile:+ """A profile from per-partition candidate file sizes in MB."""+ return RewriteProfile(+ partitions=tuple(PartitionShape.of([round(size * MB) for size in sizes]) for sizes in partitions),+ table_files=table_files,+ target_file_size=round(target_mb * MB),+ )+++def _fake_sampler(*readings: float | None) -> RssPeakSampler:+ """A sampler whose thread never ticks during a test: the window sees its start and end reads."""+ values = iter(readings)+ return RssPeakSampler(3600.0, read_rss_mb=lambda: next(values, None))+++#: Ten partitions of six 0.5 MB files: the small-file shape of most incremental merges.+_SMALL = _profile(*([[0.5] * 6] * 10))+#: One partition of 57 MB single-row-group files.+_WIDE = _profile([57.0] * 24)+#: The production slice: (29 GiB x 0.8 - 2048) / 16.+_SLOT = 1356.8+++class TestPredictUpsertMemory:+ # Per reader: the row group plus min(22, 0.4 x row group) of page buffers.+ # Per worker: 2.3 x min(target, partition bytes written). Decode: 0.875 x min(64, 1.5 x held).+ # Fixed: 6 + 0.73 x source + (2.2 KB x table files + 2.6 KB x candidate files) / 1024.+ @parameterized.expand(+ [+ # 4 x 4 x (0.5 + 0.2) = 11.2; 4 x 2.3 x 3 = 27.6; 0.875 x 1.5 x 8 = 10.5; 6 + 60 x 2.6 / 1024.+ ("small_files", _SMALL, 0.0, 4, 4, (11.2, 27.6, 10.5, 6.2)),+ # 4 x (100 + 22) = 488: the reader term follows the row group, not the 1 GB partition.+ ("single_large_row_groups", _profile([100.0] * 10), 0.0, 1, 4, (488.0, 230.0, 56.0, 6.0)),+ ("one_reader", _profile([100.0] * 10), 0.0, 1, 1, (122.0, 230.0, 56.0, 6.0)),+ ("small_target_file_size", _profile([100.0] * 10, target_mb=32.0), 0.0, 1, 4, (488.0, 73.6, 56.0, 6.0)),+ # (100 + 22) + (10 + 4) + (1 + 0.4) + 4 x 0.7 = 140.2; 230 + 2.3 x 3 = 236.9.+ (+ "mixed_partitions_both_run",+ _profile([100.0, 10.0, 1.0], [0.5] * 6),+ 0.0,+ 2,+ 4,+ (140.2, 236.9, 56.0, 6.0),+ ),+ (+ "one_worker_takes_the_costliest",+ _profile([0.5] * 6, [100.0, 10.0, 1.0]),+ 0.0,+ 1,+ 4,+ (137.4, 230.0, 56.0, 6.0),+ ),+ ("more_workers_than_partitions", _profile([100.0]), 0.0, 4, 4, (122.0, 230.0, 56.0, 6.0)),+ # 6 + 0.73 x 10 = 13.3.+ (+ "insert_only_partition",+ RewriteProfile(partitions=(PartitionShape.of([], source_bytes=10 * MB),)),+ 10.0,+ 1,+ 4,+ (0.0, 23.0, 0.0, 13.3),+ ),+ # 6 + (2.2 x 10000 + 2.6 x 60) / 1024 = 27.6.+ (+ "large_table_snapshot",+ _profile(*([[0.5] * 6] * 10), table_files=10_000),+ 0.0,+ 4,+ 4,+ (11.2, 27.6, 10.5, 27.6),+ ),+ ]+ )+ def test_terms(self, _name, profile, source_mb, mpp, mpf, expected):+ estimate = predict_upsert_memory(profile, source_mb, mpp, mpf, retention=2.0)+ assert (estimate.reader_mb, estimate.writer_mb, estimate.decode_mb, estimate.fixed_mb) == expected+ assert estimate.inuse_mb == pytest.approx(sum(expected), abs=0.2)+ assert estimate.rss_mb == pytest.approx(estimate.inuse_mb * 2.0, abs=0.2)++ @parameterized.expand(+ [+ ("more_partitions_of_the_same_shape", _profile(*([[0.5] * 6] * 10)), _profile(*([[0.5] * 6] * 1000))),+ ("more_files_of_the_same_shape", _profile([57.0] * 24), _profile([57.0] * 48)),+ ]+ )+ def test_peak_does_not_follow_the_rewrite_size(self, _name, smaller, larger):+ # Profiling showed the peak tracks the files one worker holds, not how much the merge rewrites.+ # Only the plan state, a few KB per candidate file, grows.+ a = predict_upsert_memory(smaller, 0.0, 4, 4)+ b = predict_upsert_memory(larger, 0.0, 4, 4)+ assert (a.reader_mb, a.writer_mb, a.decode_mb) == (b.reader_mb, b.writer_mb, b.decode_mb)+ assert b.fixed_mb - a.fixed_mb < 0.003 * (larger.files - smaller.files)++ def test_decode_uses_an_independent_costliest_worker_bound(self):+ profile = RewriteProfile(+ partitions=(+ PartitionShape.of([], source_bytes=50 * MB),+ PartitionShape.of([25 * MB]),+ )+ )+ estimate = predict_upsert_memory(profile, 50.0, 1, 1, retention=1.0)+ assert estimate.writer_mb == pytest.approx(115.0)+ assert estimate.decode_mb == pytest.approx(32.8)++ def test_retention_scales_only_the_rss(self):+ low = predict_upsert_memory(_WIDE, 0.0, 1, 4, retention=1.4)+ high = predict_upsert_memory(_WIDE, 0.0, 1, 4, retention=2.0)+ assert low.inuse_mb == high.inuse_mb+ assert low.rss_mb == pytest.approx(low.inuse_mb * 1.4, abs=0.2)+ assert high.rss_mb == pytest.approx(high.inuse_mb * 2.0, abs=0.2)class TestSizeUpsert:- # 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, 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+ ("small_files_take_the_widest_plan", _SMALL, None, 2.0, 4, 4, True),+ # (1, 8) = 2 x 931.4 does not fit; (1, 4) = 2 x 615.4 does.+ ("large_row_groups_step_readers_down", _WIDE, None, 2.0, 1, 4, True),+ ("lower_retention_allows_more_readers", _WIDE, None, 1.4, 1, 8, True),+ ("larger_row_groups_step_further", _profile([99.0] * 12 + [8.5] * 12), None, 2.0, 1, 2, True),+ # Two workers of two readers beat one worker of four: workers come first.+ ("workers_before_readers", _profile(*([[57.0] * 6] * 4)), None, 1.4, 2, 2, True),+ ("partition_cap_fills_readers", _SMALL, 2, 2.0, 2, 8, True),+ ("single_small_partition_gets_the_widest_worker", _profile([0.5] * 6), None, 2.0, 1, 8, True),+ ("three_partitions_share_the_reader_ceiling", _profile(*([[0.5] * 6] * 3)), None, 2.0, 3, 5, True),+ # One 1 GB row group per reader: even (1, 1) is 2 x (1024 + 22 + 230 + 56 + 13.3) > slot.+ ("huge_row_group_does_not_fit", _profile([1024.0] * 3), None, 2.0, 1, 1, False),+ # Unknown shapes assume target-sized files: (1, 2) = 2 x (244 + 230 + 56 + 13.4).+ ("unknown_shape_is_conservative", None, 4, 2.0, 1, 2, True),])- 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, plan.max_parallel_files) == (exp_mpp, exp_files)- assert plan.fits is exp_fits- # 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.+ def test_sizing(self, _name, profile, n_partitions, retention, exp_mpp, exp_files, exp_fits):+ plan = size_upsert(_SLOT, 10.0, n_partitions, profile, retention)+ assert (plan.max_parallel_partitions, plan.max_parallel_files, plan.fits) == (exp_mpp, exp_files, exp_fits)assert plan.max_parallel_partitions * plan.max_parallel_files <= 16+ assert plan.predicted_peak_mb == plan.estimate.rss_mb+ if exp_fits:+ assert plan.predicted_peak_mb <= _SLOTkwargs = plan.as_upsert_kwargs()assert set(kwargs) == {"max_parallel_partitions",@@ -93,15 +220,34 @@ class TestSizeUpsert:# 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_the_chosen_plan_is_the_first_that_fits(self):+ plan = size_upsert(_SLOT, 10.0, None, _WIDE)+ wider = predict_upsert_memory(_WIDE, 10.0, 1, 8)+ assert wider.rss_mb > _SLOT >= plan.predicted_peak_mb- 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)+ def test_empty_source_sizes_one_idle_worker(self):+ plan = size_upsert(_SLOT, 0.0, None, RewriteProfile(partitions=(), table_files=10))+ assert (plan.max_parallel_partitions, plan.fits) == (1, True)+ assert plan.estimate.reader_mb == plan.estimate.writer_mb == 0.0++ @parameterized.expand(+ [+ ("unset_is_glibc_default", {}, 2.0),+ ("low_mmap_threshold", {"MALLOC_MMAP_THRESHOLD_": "131072"}, 1.4),+ ("threshold_at_the_limit", {"MALLOC_MMAP_THRESHOLD_": "262144"}, 1.4),+ ("high_mmap_threshold", {"MALLOC_MMAP_THRESHOLD_": "1048576"}, 2.0),+ ("unparseable_threshold", {"MALLOC_MMAP_THRESHOLD_": "lots"}, 2.0),+ (+ "explicit_override_wins",+ {"MALLOC_MMAP_THRESHOLD_": "131072", "DELTALITE_GOVERNOR_RSS_RETENTION": "3"},+ 3.0,+ ),+ ("override_never_below_one", {"DELTALITE_GOVERNOR_RSS_RETENTION": "0.5"}, 1.0),+ ("bad_override_is_ignored", {"DELTALITE_GOVERNOR_RSS_RETENTION": "x"}, 2.0),+ ]+ )+ def test_rss_retention(self, _name, environ, expected):+ assert _rss_retention(environ) == expectedclass TestPodMemory:@@ -137,95 +283,129 @@ class TestPerUpsertBudget:class TestGovernorModes:async def test_off_yields_defaults_and_no_accounting(self):- gov = _governor("off")- async with gov.admit(source_bytes=50 * MB) as adm:+ gov = _governor("off", rss_sampler=_fake_sampler(1_000.0, 1_100.0))+ async with gov.admit(source_bytes=50 * MB, rewrite=_SMALL) as adm:assert adm.upsert_kwargs == {}- assert gov._inflight == 0 # off never reserves+ assert gov._inflight == 0 and gov._active == 0 # off never reserves nor counts+ assert adm.rss is None # the kill switch also stops the samplerasync def test_advisory_computes_but_uses_defaults(self):- gov = _governor("advisory") # 30000 / 15 = 2000 slice -> would pick mpp4- async with gov.admit(source_bytes=50 * MB) as adm:- # Advisory plans (predicted peak + budget + the planned mpp) but must not change the- # write or reserve — planned_mpp is recorded even though upsert_kwargs stays empty.+ gov = _governor("advisory") # 30000 / 15 = 2000 slice -> small files plan (4, 4)+ async with gov.admit(source_bytes=50 * MB, rewrite=_SMALL) as adm:+ # Advisory plans (predicted peak + budget + the planned knobs) but must not change the+ # write or reserve; the plan is recorded even though upsert_kwargs stays empty.assert adm.upsert_kwargs == {}assert adm.predicted_peak_mb is not None and adm.budget_mb is not None- assert adm.planned_mpp == 4+ assert (adm.planned_mpp, adm.planned_mpf) == (4, 4)+ assert adm.estimate is not None and adm.estimate.rss_mb == adm.predicted_peak_mbassert gov._inflight == 0 and gov._reserved_mb == 0.0- async def test_advisory_records_observed_delta_without_reserving(self):+ async def test_advisory_measures_the_peak_without_reserving(self):# The calibration signal must be captured in advisory too (its whole purpose), even though# advisory never reserves.- reads = iter([1_000.0, 1_250.0])- gov = _governor("advisory", limit_mb=30_000.0, current_mb=lambda: next(reads))- async with gov.admit(source_bytes=50 * MB) as adm:- assert gov._inflight == 0 # advisory never reserves- assert adm.observed_delta_mb == 250.0+ gov = _governor("advisory", rss_sampler=_fake_sampler(1_000.0, 1_250.0))+ async with gov.admit(source_bytes=50 * MB, rewrite=_SMALL) as adm:+ assert gov._inflight == 0+ assert adm.rss is not None+ assert (adm.rss.start_mb, adm.rss.peak_mb, adm.rss.delta_mb) == (1_000.0, 1_250.0, 250.0)async def test_enforce_applies_sized_knobs_and_reserves(self):- # limit 30000 / 15 = 2000 slice -> mpp4 (1464) fits.gov = _governor("enforce", limit_mb=30_000.0, max_concurrent=15)- async with gov.admit(source_bytes=50 * MB) as adm:- assert adm.upsert_kwargs["max_parallel_partitions"] == 4+ async with gov.admit(source_bytes=50 * MB, rewrite=_SMALL) as adm:+ assert (adm.upsert_kwargs["max_parallel_partitions"], adm.upsert_kwargs["max_parallel_files"]) == (4, 4)assert adm.capacity_exceeded is Falseassert gov._inflight == 1 and gov._reserved_mb == adm.predicted_peak_mbassert gov._inflight == 0 and gov._reserved_mb == 0.0 # released on exit- async def test_enforce_no_cgroup_limit_degrades_to_defaults(self):- gov = _governor("enforce", limit_mb=None)+ async def test_no_cgroup_limit_degrades_to_defaults_but_still_measures(self):+ gov = _governor("enforce", limit_mb=None, rss_sampler=_fake_sampler(500.0, 600.0))async with gov.admit(source_bytes=50 * MB) as adm:assert adm.upsert_kwargs == {} # can't size a slice, so deltalite defaults+ assert adm.predicted_peak_mb is Noneassert gov._inflight == 0+ assert adm.rss is not None and adm.rss.delta_mb == 100.0+ assert adm.concurrent_upserts == 1+ async def test_sampling_can_be_turned_off(self):+ gov = MemoryGovernor(GovernorConfig(mode="advisory", rss_sample_ms=0.0), _FakePod(30_000.0, 1_000.0))+ async with gov.admit(source_bytes=MB, rewrite=_SMALL) as adm:+ pass+ assert adm.rss is None++ @parameterized.expand([("advisory",), ("enforce",)])+ async def test_counts_concurrent_upserts(self, mode):+ gov = _governor(mode)+ async with gov.admit(source_bytes=MB, rewrite=_SMALL) as first:+ async with gov.admit(source_bytes=MB, rewrite=_SMALL) as second:+ assert gov._active == 2+ async with gov.admit(source_bytes=MB, rewrite=_SMALL) as third:+ pass+ assert (first.concurrent_upserts, second.concurrent_upserts, third.concurrent_upserts) == (1, 2, 2)+ assert gov._active == 0-class TestGovernorSizing:- async def test_tight_slice_sizes_mpp_down(self):- # 6750 / 15 = 450 slice -> mpp1 (389.5) fits, mpp2 (522.5) does not.- gov = _governor("enforce", limit_mb=6_750.0, max_concurrent=15)- async with gov.admit(source_bytes=50 * MB) as adm:- assert adm.upsert_kwargs["max_parallel_partitions"] == 1- assert adm.capacity_exceeded is False- async def test_source_too_big_still_runs_deltalite_at_mpp1(self):- # 30000 / 15 = 2000 slice; a 2300 MB source makes even mpp1 (220+133+0.73*2300 = 2032)- # overshoot. Never falls back: runs deltalite at mpp1 and flags capacity_exceeded.+class TestGovernorSizing:+ async def test_tight_slice_sizes_the_plan_down(self):+ # 10 partitions of 57 MB files. 30000 / 15 = 2000 fits more than 4500 / 15 = 300 does.+ profile = _profile(*([[57.0] * 6] * 10))+ roomy = _governor("enforce", limit_mb=30_000.0, max_concurrent=15)+ tight = _governor("enforce", limit_mb=15_000.0, max_concurrent=15)+ async with roomy.admit(source_bytes=MB, rewrite=profile) as wide:+ pass+ async with tight.admit(source_bytes=MB, rewrite=profile) as narrow:+ pass+ assert narrow.planned_mpp is not None and narrow.planned_mpf is not None+ assert wide.planned_mpp is not None and wide.planned_mpf is not None+ assert narrow.planned_mpp * narrow.planned_mpf < wide.planned_mpp * wide.planned_mpf+ assert narrow.capacity_exceeded is False+ assert narrow.predicted_peak_mb is not None and narrow.predicted_peak_mb <= 1_000.0++ async def test_source_too_big_still_runs_deltalite_with_the_smallest_plan(self):+ # 30000 / 15 = 2000 slice; a 2300 MB source alone is 2 x 0.73 x 2300 = 3358 MB of RSS.+ # Never falls back: runs deltalite at (1, 1) and flags capacity_exceeded.gov = _governor("enforce", limit_mb=30_000.0, max_concurrent=15)- async with gov.admit(source_bytes=2300 * MB) as adm:+ async with gov.admit(source_bytes=2300 * MB, rewrite=_SMALL) as adm:assert adm.capacity_exceeded is True- assert adm.upsert_kwargs["max_parallel_partitions"] == 1 # still deltalite, minimal+ assert (adm.upsert_kwargs["max_parallel_partitions"], adm.upsert_kwargs["max_parallel_files"]) == (1, 1)assert gov._inflight == 1 # still admitted and reservedasync def test_advisory_source_too_big_flags_but_no_reserve(self):gov = _governor("advisory", limit_mb=30_000.0, max_concurrent=15)- async with gov.admit(source_bytes=2300 * MB) as adm:+ async with gov.admit(source_bytes=2300 * MB, rewrite=_SMALL) as adm:assert adm.capacity_exceeded is Trueassert adm.upsert_kwargs == {} # advisory never changes the writeassert gov._inflight == 0+ async def test_logs_the_file_shape(self):+ gov = _governor("advisory")+ async with gov.admit(source_bytes=MB, rewrite=_WIDE) as adm:+ pass+ assert (adm.max_row_group_mb, adm.rewrite_files, adm.rewrite_total_mb) == (57.0, 24, 1368.0)+ assert adm.estimate is not None and adm.estimate.reader_mb > adm.estimate.writer_mb+async def test_reservation_released_on_exception(self):- gov = _governor("enforce")+ sampler = _fake_sampler(1_000.0, 1_000.0)+ gov = _governor("enforce", rss_sampler=sampler)with pytest.raises(ValueError):- async with gov.admit(source_bytes=50 * MB) as adm:+ async with gov.admit(source_bytes=50 * MB, rewrite=_SMALL) as adm:assert gov._inflight == 1 and gov._reserved_mb == adm.predicted_peak_mb+ thread = sampler.thread()raise ValueError("boom")- assert gov._inflight == 0 and gov._reserved_mb == 0.0+ assert gov._inflight == 0 and gov._reserved_mb == 0.0 and gov._active == 0+ assert thread is not None+ thread.join(timeout=5)+ assert not thread.is_alive()async def test_concurrent_reservations_accumulate(self):gov = _governor("enforce", limit_mb=30_000.0, max_concurrent=15)- async with gov.admit(source_bytes=50 * MB) as first:+ async with gov.admit(source_bytes=50 * MB, rewrite=_SMALL) as first:assert gov._inflight == 1- async with gov.admit(source_bytes=50 * MB) as second:+ async with gov.admit(source_bytes=50 * MB, rewrite=_SMALL) as second:assert gov._inflight == 2assert first.predicted_peak_mb is not None and second.predicted_peak_mb is not Noneassert gov._reserved_mb == first.predicted_peak_mb + second.predicted_peak_mbassert gov._inflight == 0 and gov._reserved_mb == 0.0- async def test_observed_delta_recorded_on_release(self):- reads = iter([1_000.0, 1_300.0]) # admit reads 1000, release reads 1300- gov = _governor("enforce", limit_mb=30_000.0, current_mb=lambda: next(reads))- async with gov.admit(source_bytes=50 * MB) as adm:- pass- assert adm.observed_delta_mb == 300.0-def test_usable_across_separate_event_loops(self):# Regression: the V3 loader drives the governor via async_to_sync in worker threads, each on# its own short-lived event loop. A loop-bound asyncio.Lock would raise "bound to a different@@ -234,7 +414,7 @@ class TestGovernorSizing:gov = _governor("enforce")async def _once() -> float | None:- async with gov.admit(source_bytes=50 * MB) as adm:+ async with gov.admit(source_bytes=50 * MB, rewrite=_SMALL) as adm:assert gov._inflight == 1return adm.predicted_peak_mb@@ -299,10 +479,19 @@ class TestProcessConcurrency:"DELTALITE_GOVERNOR_MODE": "enforce","DELTALITE_GOVERNOR_SAFETY": "0.7","DELTALITE_GOVERNOR_RESERVE_MB": "4096",+ "DELTALITE_GOVERNOR_RSS_SAMPLE_MS": "250",+ "MALLOC_MMAP_THRESHOLD_": "131072",}with patch.dict("os.environ", env, clear=True):cfg = GovernorConfig.from_env()- assert (cfg.safety, cfg.reserve_mb) == (0.7, 4096.0)+ assert (cfg.safety, cfg.reserve_mb, cfg.rss_sample_ms, cfg.rss_retention) == (0.7, 4096.0, 250.0, 1.4)++ @parameterized.expand([("default", {}, 100.0), ("off", {"DELTALITE_GOVERNOR_RSS_SAMPLE_MS": "0"}, 0.0)])+ def test_rss_sampling_interval(self, _name, env, expected):+ with patch.dict("os.environ", env, clear=True):+ config = GovernorConfig.from_env()+ assert config.rss_sample_ms == expected+ assert (MemoryGovernor(config, _FakePod(None, None))._sampler is None) is (expected == 0.0)_PART = "_ph_partition_key"@@ -336,18 +525,35 @@ 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),+ (+ "touched_partitions_and_pk_range",+ _source([("a", 150), ("a", 250), ("b", 500)]),+ _PART,+ ((400,), (50, 30)),+ 3,+ ),+ ("one_row_counts_its_candidate_file", _source([("a", 150)]), _PART, ((50,),), 1),+ # A partition with no files still runs a worker that writes the inserts.+ ("append_into_new_partition", _source([("d", 1), ("d", 2)]), _PART, ((),), 0),+ ("keys_beyond_every_file", _source([("a", 1000), ("a", 1001)]), _PART, ((),), 0),+ (+ "unpartitioned_counts_all_candidates",+ _source([("x", 0), ("x", 950)]),+ None,+ ((400, 100, 70, 50, 30),),+ 5,+ ),])- def test_profile(self, _name, source, partition_col, expected_bytes, expected_files):+ def test_profile(self, _name, source, partition_col, expected_files, expected_count):profile = rewrite_profile(_add_actions(), source, partition_col, ["id"])- assert profile.partition_bytes == expected_bytes- assert profile.files == expected_files+ assert tuple(p.largest_file_bytes for p in profile.partitions) == expected_files+ assert profile.files == expected_count+ assert profile.table_files == len(_FILES)+ # Each partition carries its share of the source, for the bytes its worker writes.+ assert sum(p.source_bytes for p in profile.partitions) == pytest.approx(+ source.nbytes, abs=len(profile.partitions)+ )@parameterized.expand([@@ -358,7 +564,13 @@ class TestRewriteProfile: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,)+ profile = rewrite_profile(add_actions, source, _PART, primary_keys)+ assert [(p.largest_file_bytes, p.stored_bytes) for p in profile.partitions] == [((100, 50, 30), 180)]++ def test_one_source_row_can_match_duplicate_keys_in_multiple_files(self):+ files = [("a", 100, 100, 200), ("a", 50, 150, 250)]+ profile = rewrite_profile(_add_actions(files), _source([("a", 175)]), _PART, ["id"])+ assert (profile.partitions[0].largest_file_bytes, profile.files) == ((100, 50), 2)def test_string_keys_are_not_pruned(self):# Delta truncates long string stats, so a string max proves nothing.@@ -368,33 +580,37 @@ class TestRewriteProfile:.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,)+ assert rewrite_profile(add_actions, source, _PART, ["id"]).partitions[0].stored_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)+ def test_keeps_only_the_files_one_worker_can_read_at_once(self):+ files = [("a", size, 0, 99) for size in range(1, 21)]+ source = _source([("a", i) for i in range(20)])+ shape = rewrite_profile(_add_actions(files), source, _PART, ["id"]).partitions[0]+ assert shape.largest_file_bytes == (20, 19, 18, 17, 16, 15, 14, 13)+ assert (shape.files, shape.stored_bytes) == (20, sum(range(1, 21)))@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),+ ("empty_table", [], _source([("a", 1)]), ((),), 0),+ ("empty_source", _FILES, _source([]), (), 5),])- def test_rewrite_mb(self, _name, partition_bytes, mpp, expected):- assert RewriteProfile(partition_bytes=partition_bytes, files=1).rewrite_mb(mpp) == expected+ def test_nothing_to_rewrite(self, _name, files, source, expected_files, table_files):+ profile = rewrite_profile(_add_actions(files), source, _PART, ["id"])+ assert tuple(p.largest_file_bytes for p in profile.partitions) == expected_files+ assert (profile.files, profile.total_mb, profile.max_row_group_mb, profile.table_files) == (+ 0,+ 0.0,+ 0.0,+ table_files,+ )- def test_estimate_reads_a_real_table(self, tmp_path: Path):+ @pytest.mark.parametrize(+ "configuration,expected_target",+ [(None, 100 * MB), ({"delta.targetFileSize": str(32 * MB)}, 32 * MB)],+ ids=["table_default", "table_sets_a_target"],+ )+ def test_estimate_reads_a_real_table(self, configuration, expected_target, tmp_path: Path):existing = pa.table({_PART: ["a"] * 3 + ["b"] * 3 + ["c"] * 3,@@ -402,15 +618,18 @@ class TestRewriteProfile:"v": ["x"] * 9,})- deltalake.write_deltalake(str(tmp_path), existing, partition_by=_PART)+ deltalake.write_deltalake(str(tmp_path), existing, partition_by=_PART, configuration=configuration)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+ assert sorted(p.stored_bytes for p in profile.partitions) == sorted(+ [0, sizes[f"{_PART}=a"], sizes[f"{_PART}=b"]]+ )+ assert (profile.files, profile.table_files, profile.target_file_size) == (2, 3, expected_target)+ assert profile.max_row_group_mb == max(sizes[f"{_PART}=a"], sizes[f"{_PART}=b"]) / MBdef test_estimate_unreadable_table_is_unknown(self):broken = MagicMock()@@ -418,39 +637,6 @@ class TestRewriteProfile: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."""@@ -473,16 +659,20 @@ async def _settle(rounds: int = 5) -> None: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)+ # 4 slices of 1000 MB. The big upsert rewrites 2 GB single-row-group files: even (1, 1) is+ # predicted above the whole usable pod, so it reserves the pod (4 slices).+ _BIG = _profile([2_048.0] * 4)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):+ def _small_peak() -> float:+ return size_upsert(1_000.0, 50.0, None, _SMALL).predicted_peak_mb++ @staticmethod+ async def _enter(gov: MemoryGovernor, rewrite: RewriteProfile = _SMALL):cm = gov.admit(source_bytes=50 * MB, rewrite=rewrite)return cm, await cm.__aenter__()@@ -490,13 +680,14 @@ class TestOverSlotReservation:async def _exit(cm) -> None:await cm.__aexit__(None, None, None)- async def test_alone_it_reserves_several_slices_without_waiting(self):+ async def test_alone_it_reserves_the_pod_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.planned_mpp, adm.planned_mpf, adm.capacity_exceeded) == (1, 1, True)+ assert adm.predicted_peak_mb is not None and adm.predicted_peak_mb > 4_000.0+ assert (adm.max_row_group_mb, adm.rewrite_total_mb, adm.rewrite_files) == (2_048.0, 8_192.0, 4)+ assert adm.reserved_slots == 4.0 and gov._reserved_mb == 4_000.0assert (adm.wait_ms, fake.sleeps) == (0, 0)await self._exit(cm)assert gov._reserved_mb == 0.0 and gov._inflight == 0@@ -507,7 +698,8 @@ class TestOverSlotReservation: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)+ assert gov._inflight == 4+ assert all(adm.reserved_slots == round(self._small_peak() / 1_000.0, 2) < 1 for _cm, adm in held)for cm, _adm in held:await self._exit(cm)@@ -518,7 +710,7 @@ class TestOverSlotReservation:await _settle()assert not big.done()- # 788.5 + 3389.5 is still above the 4000 MB pod.+ # One small reservation beside the pod-sized one is still above the 4000 MB pod.await self._exit(held[0][0])await self._exit(held[1][0])await _settle()@@ -528,7 +720,7 @@ class TestOverSlotReservation: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+ assert gov._reserved_mb == 4_000.0 and not gov._waitersawait self._exit(cm)async def test_newcomers_queue_behind_the_waiter(self):@@ -544,7 +736,7 @@ class TestOverSlotReservation: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+ assert big.done() and not small.done() # the pod-sized reservation leaves no roomawait self._exit(big.result()[0])await _settle()@@ -563,9 +755,9 @@ class TestOverSlotReservation: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+ assert (adm.upsert_kwargs["max_parallel_partitions"], adm.upsert_kwargs["max_parallel_files"]) == (1, 1)# Over-committed on purpose: deltalite always writes.- assert gov._reserved_mb == 3 * 788.5 + 3389.5 and gov._inflight == 4+ assert gov._reserved_mb == pytest.approx(3 * self._small_peak() + 4_000.0) and gov._inflight == 4for c in [cm, *(c for c, _adm in held)]:await self._exit(c)@@ -577,7 +769,7 @@ class TestOverSlotReservation:big.cancel()with pytest.raises(asyncio.CancelledError):await big- assert not gov._waiters and gov._inflight == 3+ assert not gov._waiters and gov._inflight == 3 and gov._active == 3for cm, _adm in held:await self._exit(cm)# The next admission is not stuck behind a ticket that no longer waits.@@ -589,6 +781,6 @@ class TestOverSlotReservation: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 adm.upsert_kwargs == {} and adm.reserved_slots == 4.0assert (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_rss_sampler.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_rss_sampler.pynew file mode 100644index 000000000000..70723de6ed84--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_rss_sampler.py@@ -0,0 +1,164 @@+import time+import threading+from pathlib import Path++import pytest+from unittest.mock import mock_open, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta import rss_sampler+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.rss_sampler import (+ MB,+ RssPeakSampler,+ RssWindow,+ read_process_rss_mb,+)++_THREAD_NAME = "deltalite-rss-sampler"+++class _Readings:+ """Returns the queued readings in order, then repeats the last one. Counts the reads."""++ def __init__(self, *values: float | None) -> None:+ self._values = list(values)+ self._lock = threading.Lock()+ self.reads = 0++ def __call__(self) -> float | None:+ with self._lock:+ self.reads += 1+ return self._values.pop(0) if len(self._values) > 1 else self._values[0]+++def _raise_oserror() -> float | None:+ raise OSError("gone")+++def _wait_for(condition, timeout_s: float = 5.0) -> None:+ deadline = time.monotonic() + timeout_s+ while not condition():+ assert time.monotonic() < deadline, "timed out"+ time.sleep(0.001)+++def _sampler_threads() -> list[threading.Thread]:+ return [t for t in threading.enumerate() if t.name == _THREAD_NAME]+++def _stopped(sampler: RssPeakSampler, thread: threading.Thread | None) -> bool:+ assert thread is not None+ thread.join(timeout=5)+ return not thread.is_alive() and sampler.thread() is None+++class TestRssPeakSampler:+ def test_window_keeps_the_start_and_the_highest_sample(self):+ readings = _Readings(100.0, 300.0, 200.0, 150.0)+ sampler = RssPeakSampler(0.001, read_rss_mb=readings)+ with sampler.window() as window:+ _wait_for(lambda: readings.reads >= 4)+ assert (window.start_mb, window.peak_mb, window.delta_mb) == (100.0, 300.0, 200.0)+ assert window.samples >= 4++ def test_thread_runs_only_while_a_window_is_open(self):+ sampler = RssPeakSampler(0.001, read_rss_mb=_Readings(1.0))+ assert sampler.thread() is None+ with sampler.window():+ first = sampler.thread()+ with sampler.window():+ # Overlapping windows share the one thread.+ assert sampler.thread() is first+ assert first is not None and first.is_alive()+ assert _stopped(sampler, first)++ def test_no_thread_leaks_over_many_windows(self):+ sampler = RssPeakSampler(0.001, read_rss_mb=_Readings(1.0))+ before = len(_sampler_threads())+ threads = []+ for _ in range(25):+ with sampler.window():+ threads.append(sampler.thread())+ for thread in threads:+ assert thread is not None+ thread.join(timeout=5)+ assert sampler.thread() is None+ assert len(_sampler_threads()) == before++ def test_a_long_interval_still_stops_at_once(self):+ # Closing the last window wakes the thread, so it never lingers for a full interval.+ sampler = RssPeakSampler(3600.0, read_rss_mb=_Readings(1.0))+ with sampler.window():+ thread = sampler.thread()+ started = time.monotonic()+ assert _stopped(sampler, thread)+ assert time.monotonic() - started < 5++ def test_concurrent_windows_report_the_overlap(self):+ sampler = RssPeakSampler(3600.0, read_rss_mb=_Readings(1.0))+ with sampler.window() as a:+ with sampler.window() as b:+ pass+ with sampler.window() as c:+ pass+ with sampler.window() as alone:+ pass+ assert (a.max_concurrent, b.max_concurrent, c.max_concurrent, alone.max_concurrent) == (2, 2, 2, 1)++ def test_window_closes_when_the_upsert_raises(self):+ sampler = RssPeakSampler(0.001, read_rss_mb=_Readings(10.0, 20.0))+ with pytest.raises(RuntimeError):+ with sampler.window():+ thread = sampler.thread()+ raise RuntimeError("upsert failed")+ assert _stopped(sampler, thread)++ @parameterized.expand(+ [+ ("raises", _raise_oserror),+ ("unknown", lambda: None),+ ]+ )+ def test_failed_reads_are_missing_samples(self, _name, reader):+ sampler = RssPeakSampler(0.001, read_rss_mb=reader)+ with sampler.window() as window:+ thread = sampler.thread()+ time.sleep(0.01)+ assert (window.start_mb, window.peak_mb, window.delta_mb, window.samples) == (None, None, None, 0)+ assert _stopped(sampler, thread)+++class TestRssWindow:+ @parameterized.expand(+ [+ ("rises", 100.0, [150.0, 120.0], 150.0, 50.0),+ ("never_rises", 100.0, [90.0], 100.0, 0.0),+ ("no_start", None, [90.0], 90.0, None),+ ("rounds_to_a_tenth", 100.04, [100.26], 100.3, 0.3),+ ]+ )+ def test_peak_and_delta(self, _name, start, samples, peak, delta):+ window = RssWindow(start_mb=round(start, 1) if start is not None else None)+ window.observe(start)+ for value in samples:+ window.observe(value)+ assert (window.peak_mb, window.delta_mb) == (peak, delta)+++class TestReadProcessRss:+ def test_reads_resident_pages_from_statm(self):+ with patch("builtins.open", mock_open(read_data=b"5000 256 100 1 0 300 0\n")):+ assert read_process_rss_mb() == 256 * rss_sampler._PAGE_SIZE / MB++ def test_falls_back_to_psutil_without_proc(self):+ with (+ patch("builtins.open", side_effect=FileNotFoundError),+ patch.object(rss_sampler, "psutil_rss_mb", return_value=42.0),+ ):+ assert read_process_rss_mb() == 42.0++ @pytest.mark.skipif(not Path("/proc/self/statm").exists(), reason="needs Linux /proc")+ def test_reads_this_process(self):+ rss = read_process_rss_mb()+ assert rss is not None and rss > 0diff --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 a9c7c9ce7d60..3690033480e5 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@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delDELTA_TABLE_PROPERTIES,ensure_table_properties,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.rss_sampler import RssPeakSamplerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableReffrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (decimal_array,@@ -1186,7 +1187,11 @@ class TestDeltaliteWritePath:pod = MagicMock()pod.limit_mb.return_value = 30_000.0pod.current_mb.return_value = 1_000.0- governor = MemoryGovernor(GovernorConfig(mode="enforce", safety=1.0, reserve_mb=0.0, max_concurrent=15), pod)+ governor = MemoryGovernor(+ GovernorConfig(mode="enforce", safety=1.0, reserve_mb=0.0, max_concurrent=15),+ pod,+ rss_sampler=RssPeakSampler(3600.0, read_rss_mb=iter([500.0, 650.0]).__next__),+ )reset_governor_for_tests(governor)try:with (@@ -1209,9 +1214,15 @@ class TestDeltaliteWritePath:log_kwargs = logger.ainfo.call_args.kwargsassert log_kwargs["governor_rewrite_files"] == 1assert 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_max_row_group_mb"] == round(partition_a_bytes / (1024 * 1024), 1)+ assert log_kwargs["governor_reader_mb"] is not None and log_kwargs["governor_writer_mb"] is not Noneassert 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+ # The measured peak sits next to the prediction, with the concurrency to filter solo runs.+ assert (log_kwargs["governor_peak_rss_mb"], log_kwargs["governor_rss_delta_mb"]) == (650.0, 150.0)+ assert log_kwargs["governor_concurrent_upserts"] == log_kwargs["governor_max_concurrent_upserts"] == 1+ assert "governor_observed_delta_mb" not in log_kwargs+ upsert_kwargs = fake_table.upsert.call_args.kwargs+ assert (upsert_kwargs["max_parallel_partitions"], upsert_kwargs["max_parallel_files"]) == (1, 8)@pytest.mark.asyncioasync def test_falls_back_when_deltalite_raises(self):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 a2f07c7a57f2..ef90d533aa15 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@@ -260,9 +260,10 @@ class DeltaWriter:# 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# 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). The existing files the merge can- # rewrite are sized from the handle's add actions, so this costs no object-store request.+ # the MERGE is the *more* memory-hungry path. A source too big for its slice just runs with+ # the smallest plan (governor logs a capacity_exceeded ops signal). The shape of the files+ # the merge can rewrite comes from the handle's add actions, so this costs no object-store+ # request.governor = get_governor()rewrite = (await asyncio.to_thread(@@ -323,16 +324,26 @@ class DeltaWriter:duration_ms=round(duration_s * 1000),governor_mode=adm.mode,governor_predicted_peak_mb=adm.predicted_peak_mb,- governor_observed_delta_mb=adm.observed_delta_mb,+ governor_predicted_inuse_mb=adm.estimate.inuse_mb if adm.estimate else None,+ governor_reader_mb=adm.estimate.reader_mb if adm.estimate else None,+ governor_writer_mb=adm.estimate.writer_mb if adm.estimate else None,governor_budget_mb=adm.budget_mb,governor_capacity_exceeded=adm.capacity_exceeded,governor_mpp=adm.planned_mpp,- governor_rewrite_mb=adm.rewrite_mb,+ governor_mpf=adm.planned_mpf,+ governor_max_row_group_mb=adm.max_row_group_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,+ # Process-wide RSS while this upsert ran; filter on max_concurrent_upserts == 1 for+ # a clean per-upsert signal.+ governor_peak_rss_mb=adm.rss.peak_mb if adm.rss else None,+ governor_rss_delta_mb=adm.rss.delta_mb if adm.rss else None,+ governor_rss_samples=adm.rss.samples if adm.rss else None,+ governor_concurrent_upserts=adm.concurrent_upserts,+ governor_max_concurrent_upserts=adm.rss.max_concurrent if adm.rss else None,**_deltalite_write_stats(stats),)DELTALITE_WRITE_TOTAL.labels(outcome="written").inc()