:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(data-warehouse): fit the deltalite memory governor to 0.1.10 (#112476)
Tom Owersda6bcf288007
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 e6a214596aa4..ec1a5aeb3e71 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,19 +26,22 @@ Two layers, by design:governor predicted. The governor aims never to reach it; the backstop guarantees safety when aprediction is wrong.-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.+The memory model follows the shape of the files a merge rewrites, not their total size. An upsert+in deltalite 0.1.10 holds three things at its peak:++* **Readers.** Each reader fetches one whole compressed row group before it decodes it. A reader+ reserves its row group from the per-call fetch budget (``max_fetch_bytes``) first, so all readers+ of one upsert together hold at most the budget, or one row group when a row group is larger.+* **Writers.** Each partition worker streams its open file into fixed-size chunks, so it holds about+ one ``target_file_size`` file, and less when the partition writes less. Each column also keeps+ page and dictionary buffers, so wide tables cost more per worker than narrow ones.* **Decode.** Decoded survivor batches in flight, capped per call by ``max_buffered_bytes``.+ Compressible files decode to many times their stored size, so the decoded volume comes from the+ candidate rows, not the stored 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.+or the total bytes a merge rewrites — only with these terms. The terms are named constants, so a+deltalite release that changes one of them changes one number."""from __future__ import annotations@@ -87,33 +90,39 @@ _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-# --- File-shape memory model (deltalite 0.1.9) -------------------------------------------------+# --- File-shape memory model (deltalite 0.1.10) ------------------------------------------------#-# 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.+# Fitted on a Linux harness that runs the loader's exact upsert (glibc, MALLOC_MMAP_THRESHOLD_ at+# 128 KiB, a warm process): 6-, 30- and 200-column tables; small files over 10 to 1,000 partitions;+# single-row-group files of 27 to 93 MB; 150 MB files of three row groups; compressible files of+# 2 to 10 stored bytes per row; target_file_size 32, 100 and 256 MiB; plans from 1x1 to 4x4; and+# insert-only writes of 5 to 250 MB. 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: the whole compressed row+#: group, held until it is decoded._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+#: deltalite's per-call ``max_fetch_bytes``, passed explicitly. All readers of one upsert hold at+#: most this much fetched row-group data, or one row group when a row group is larger.+_FETCH_BUDGET_BYTES = 128 * MB+#: Resident bytes per byte of the file one partition worker writes, up to ``target_file_size``.+_WRITER_BYTES_PER_TARGET_BYTE = 1.8+#: Page and dictionary buffers per column of one open output file, once the file is large enough+#: to fill them.+_WRITER_MB_PER_COLUMN = 0.8+#: Bytes written before the per-column buffers are full; a smaller file fills them in proportion.+_WRITER_COLUMN_FILL_MB = 32.0#: 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+#: Columns assumed when the source is unknown: wider than most tables, so the guess errs high.+_UNKNOWN_COLUMNS = 64#: Per upsert, before any partition worker: channels, tasks, the commit.-_BASE_INUSE_MB = 6.0+_BASE_INUSE_MB = 8.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@@ -141,7 +150,7 @@ _MAX_PARALLEL_PARTITIONS = 4#: 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.+#: overlap from more; the reader term charges every extra reader its row group, up to the fetch budget._MAX_PARALLEL_FILES = 8#: Ceiling on ``max_parallel_partitions × max_parallel_files`` for one upsert, the process-wide#: reader limit deltalite enforces by default.@@ -195,15 +204,19 @@ class PartitionShape:stored_bytes: int#: Bytes of the source rows that land in this partition.source_bytes: int = 0+ #: Decoded bytes of all candidate files: their rows times the source's bytes per row. None+ #: when a file does not record its row count, which sizes the decode term at its budget.+ decoded_bytes: int | None = None@staticmethod- def of(file_bytes: Sequence[int], source_bytes: int = 0) -> PartitionShape:+ def of(file_bytes: Sequence[int], source_bytes: int = 0, decoded_bytes: int | None = None) -> 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,+ decoded_bytes=0 if not ordered else decoded_bytes,)@@ -217,6 +230,8 @@ class RewriteProfile: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+ #: Columns of the rows the merge writes. Each column of an open output file keeps buffers.+ columns: int = _UNKNOWN_COLUMNS@propertydef files(self) -> int:@@ -288,7 +303,12 @@ def rewrite_profile(has no candidate files."""if source.num_rows == 0:- return RewriteProfile(partitions=(), table_files=add_actions.num_rows, target_file_size=target_file_size)+ return RewriteProfile(+ partitions=(),+ table_files=add_actions.num_rows,+ target_file_size=target_file_size,+ columns=source.num_columns,+ )if partition_col is None:rows_per_partition: dict[str | None, int] = {None: source.num_rows}@@ -304,24 +324,39 @@ def rewrite_profile()sizes_by_partition: dict[str | None, list[int]] = {partition: [] for partition in rows_per_partition}+ rows_by_partition: dict[str | None, int | None] = dict.fromkeys(rows_per_partition, 0)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):+ file_rows = (+ add_actions["num_records"].to_pylist()+ if "num_records" in add_actions.column_names+ else [None] * add_actions.num_rows+ )+ for partition, size, rows, candidate in zip(+ file_partitions, add_actions["size_bytes"].to_pylist(), file_rows, can_match+ ):if candidate and partition in sizes_by_partition:sizes_by_partition[partition].append(size or 0)+ known = rows_by_partition[partition]+ rows_by_partition[partition] = None if known is None or rows is None else known + rows+ # The source has the table's columns, so its bytes per row also size the decoded candidates.bytes_per_row = source.nbytes / source.num_rows- partitions = [- PartitionShape.of(- sizes,- source_bytes=round(bytes_per_row * rows_per_partition[partition]),+ partitions = []+ for partition, sizes in sizes_by_partition.items():+ candidate_rows = rows_by_partition[partition]+ partitions.append(+ PartitionShape.of(+ sizes,+ source_bytes=round(bytes_per_row * rows_per_partition[partition]),+ decoded_bytes=None if candidate_rows is None else round(bytes_per_row * candidate_rows),+ ))- 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,+ columns=source.num_columns,)@@ -364,9 +399,17 @@ class MemoryEstimate:class WorkerTerms:"""Memory terms for one partition worker."""- reader_mb: float- writer_mb: float+ #: Fetched row groups of its readers, before the per-call fetch budget caps them.held_mb: float+ #: Decompressed pages next to those row groups.+ pages_mb: float+ #: The largest row group one of its readers fetches.+ largest_row_group_mb: float+ writer_mb: float++ @property+ def reader_mb(self) -> float:+ return _READER_BYTES_PER_ROW_GROUP_BYTE * self.held_mb + self.pages_mb@frozen@@ -374,18 +417,24 @@ class WorkerBounds:"""Independent upper bounds for worker memory terms."""terms: tuple[WorkerTerms, ...]- held_mb: tuple[float, ...]+ #: Decoded bytes of the largest partitions, largest first. None is unknown.+ decoded_mb: tuple[float | None, ...]++def _writer_mb(written_mb: float, target_mb: float, columns: int) -> float:+ file_mb = min(target_mb, written_mb)+ column_fill = min(1.0, file_mb / _WRITER_COLUMN_FILL_MB)+ return _WRITER_BYTES_PER_TARGET_BYTE * file_mb + _WRITER_MB_PER_COLUMN * columns * column_fill-def _worker_terms(shape: PartitionShape, files_per_worker: int, target_mb: float) -> WorkerTerms:++def _worker_terms(shape: PartitionShape, files_per_worker: int, target_mb: float, columns: int) -> 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) / MBreturn 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,+ held_mb=sum(row_groups_mb),+ pages_mb=sum(min(_READER_PAGE_BUFFER_MB, _READER_PAGE_BUFFER_SHARE * rg) for rg in row_groups_mb),+ largest_row_group_mb=max(row_groups_mb, default=0.0),+ writer_mb=_writer_mb(written, target_mb, columns),)@@ -404,7 +453,8 @@ def _unknown_shapes(n_partitions: int | None, source_mb: float, target_mb: floatdef _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]+ terms = [_worker_terms(shape, files_per_worker, target_mb, profile.columns) for shape in profile.partitions]+ decoded = [None if p.decoded_bytes is None else p.decoded_bytes / MB for p in profile.partitions]return WorkerBounds(terms=tuple(heapq.nlargest(@@ -413,10 +463,28 @@ def _costliest_workers(profile: RewriteProfile, files_per_worker: int) -> Workerkey=lambda worker: worker.reader_mb + worker.writer_mb,)),- held_mb=tuple(heapq.nlargest(_MAX_PARALLEL_PARTITIONS, (worker.held_mb for worker in terms))),+ # Unknown sorts first: it is sized as a full decode budget.+ decoded_mb=tuple(+ heapq.nlargest(_MAX_PARALLEL_PARTITIONS, decoded, key=lambda mb: float("inf") if mb is None else mb)+ ),)+def _readers_in_flight_mb(workers: Sequence[WorkerTerms]) -> float:+ """Reader memory of ``workers``, capped by the per-call fetch budget.++ A reader takes fetch budget for its row group before it fetches it, so the readers of one+ upsert hold at most the budget at once. A row group larger than the budget takes all of it+ and runs alone. Fewer readers in flight also hold fewer pages, in the same proportion.+ """+ held = sum(w.held_mb for w in workers)+ if held <= 0:+ return sum(w.pages_mb for w in workers)+ budget_mb = max(_FETCH_BUDGET_BYTES / MB, max(w.largest_row_group_mb for w in workers))+ share = min(1.0, budget_mb / held)+ return share * sum(w.reader_mb for w in workers)++def predict_upsert_memory(profile: RewriteProfile,source_mb: float,@@ -435,10 +503,12 @@ def predict_upsert_memory(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)+ reader_mb = _readers_in_flight_mb(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)+ decoded = costliest.decoded_mb[:mpp]+ budget_mb = buffered_bytes / MB+ decoded_mb = budget_mb if None in decoded else sum(mb for mb in decoded if mb is not None)+ decode_mb = _DECODE_BUDGET_FILL * min(budget_mb, decoded_mb)fixed_mb = (_BASE_INUSE_MB+ _SOURCE_INUSE_PER_MB * source_mb@@ -468,12 +538,15 @@ class UpsertPlan:fits: boolestimate: MemoryEstimateprobe_concurrency: int = _PROBE_CONCURRENCY+ #: The reader term assumes this budget, so it goes out explicitly rather than as deltalite's default.+ max_fetch_bytes: int = _FETCH_BUDGET_BYTESdef as_upsert_kwargs(self) -> dict[str, int]:return {"max_parallel_partitions": self.max_parallel_partitions,"max_parallel_files": self.max_parallel_files,"max_buffered_bytes": self.max_buffered_bytes,+ "max_fetch_bytes": self.max_fetch_bytes,"probe_concurrency": self.probe_concurrency,}@@ -495,8 +568,8 @@ def size_upsert(``available_mb`` is the per-upsert memory slice, not the whole pod. Partition workers comefirst: 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+ worker before fewer. A worker's readers cost its largest row groups up to the fetch budget, so a+ partition of big single-row-group files steps its readers down before the plan loses a worker. When no planfits, 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.@@ -504,13 +577,16 @@ def size_upsert(profile = rewriteif profile is None:target_mb = _DEFAULT_TARGET_FILE_SIZE / MB- profile = RewriteProfile(partitions=_unknown_shapes(n_partitions, source_mb, target_mb))+ profile = RewriteProfile(+ partitions=_unknown_shapes(n_partitions, source_mb, target_mb), columns=_UNKNOWN_COLUMNS+ )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,+ columns=profile.columns,)partition_cap = min(_MAX_PARALLEL_PARTITIONS, max(1, len(profile.partitions)))@@ -726,6 +802,8 @@ class Admission:#: Stored MB of all candidate files the merge can rewrite, over every touched partition.rewrite_total_mb: float | None = Nonerewrite_files: int | None = None+ #: Columns of the rows the merge writes. None when the shape is unknown.+ columns: int | None = None#: 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``.@@ -903,6 +981,7 @@ class MemoryGovernor: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,+ columns=rewrite.columns if rewrite is not None else None,concurrent_upserts=concurrent,reserved_slots=round(reserve_mb / budget_mb, 2) if budget_mb else None,wait_ms=round(waited_s * 1000),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 63e6b8a35aa1..618f70e0d5a0 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@@ -71,12 +71,27 @@ def _governor(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:+def _profile(+ *partitions: list[float],+ target_mb: float = 100.0,+ table_files: int = 0,+ columns: int = 64,+ decoded_mb: float | None = None,+ source_mb_per_partition: float = 0.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),+ partitions=tuple(+ PartitionShape.of(+ [round(size * MB) for size in sizes],+ source_bytes=round(source_mb_per_partition * MB),+ decoded_bytes=None if decoded_mb is None else round(decoded_mb * MB),+ )+ for sizes in partitions+ ),table_files=table_files,target_file_size=round(target_mb * MB),+ columns=columns,)@@ -92,28 +107,37 @@ _SMALL = _profile(*([[0.5] * 6] * 10))_WIDE = _profile([57.0] * 24)#: The production slice: (29 GiB x 0.8 - 2048) / 16._SLOT = 1356.8+#: The same slice at a 14 GiB limit: (14 GiB x 0.8 - 2048) / 16.+_SLOT_14GI = 588.8class 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.+ # Readers: row group + min(22, 0.4 x row group) each, scaled down so all readers of the upsert+ # hold at most max(128 MB, largest row group). Per worker: 1.8 x min(target, written) ++ # 0.8 x columns x min(1, file / 32). Decode: 0.875 x min(64, decoded candidates), 64 when unknown.+ # Fixed: 8 + 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.+ # 4 x 4 x (0.5 + 0.2) = 11.2; 4 x (1.8 x 3 + 0.8 x 64 x 3 / 32) = 40.8; 8 + 60 x 2.6 / 1024.+ ("small_files", _SMALL, 0.0, 4, 4, (11.2, 40.8, 56.0, 8.2)),+ # Four 100 MB row groups want 400 MB; the 128 MB fetch budget holds 0.32 of 4 x 122.+ ("fetch_budget_caps_readers", _profile([100.0] * 10), 0.0, 1, 4, (156.2, 231.2, 56.0, 8.0)),+ ("one_reader", _profile([100.0] * 10), 0.0, 1, 1, (122.0, 231.2, 56.0, 8.0)),+ # A row group above the budget takes all of it and runs alone: 200 + 22.+ ("row_group_above_the_budget_runs_alone", _profile([200.0] * 4), 0.0, 1, 4, (222.0, 231.2, 56.0, 8.0)),+ # 1.8 x 32 + 0.8 x 64 = 108.8.+ ("small_target_file_size", _profile([100.0] * 10, target_mb=32.0), 0.0, 1, 4, (156.2, 108.8, 56.0, 8.0)),+ # Per-column buffers: 1.8 x 100 + 0.8 x 200 = 340 against 1.8 x 100 + 0.8 x 7 = 185.6.+ ("wide_table_writer", _profile([100.0], columns=200), 0.0, 1, 1, (122.0, 340.0, 56.0, 8.0)),+ ("narrow_table_writer", _profile([100.0], columns=7), 0.0, 1, 1, (122.0, 185.6, 56.0, 8.0)),+ # (100 + 22) + (10 + 4) + (1 + 0.4) + 4 x 0.7 = 140.2 stays under the budget.("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),+ (140.2, 241.4, 56.0, 8.0),),("one_worker_takes_the_costliest",@@ -121,26 +145,36 @@ class TestPredictUpsertMemory:0.0,1,4,- (137.4, 230.0, 56.0, 6.0),+ (137.4, 231.2, 56.0, 8.0),+ ),+ ("more_workers_than_partitions", _profile([100.0]), 0.0, 4, 4, (122.0, 231.2, 56.0, 8.0)),+ # A 4 MB file of compressible rows decodes to 500 MB: the decode budget fills.+ (+ "compressible_file_fills_the_decode_budget",+ _profile([4.0], decoded_mb=500.0),+ 0.0,+ 1,+ 1,+ (5.6, 13.6, 56.0, 8.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.+ ("small_decoded_volume", _profile([4.0], decoded_mb=8.0), 0.0, 1, 1, (5.6, 13.6, 7.0, 8.0)),+ # Nothing to read: 1.8 x 10 + 0.8 x 64 x 10 / 32 = 34; 8 + 0.73 x 10 = 15.3.("insert_only_partition",RewriteProfile(partitions=(PartitionShape.of([], source_bytes=10 * MB),)),10.0,1,4,- (0.0, 23.0, 0.0, 13.3),+ (0.0, 34.0, 0.0, 15.3),),- # 6 + (2.2 x 10000 + 2.6 x 60) / 1024 = 27.6.+ # 8 + (2.2 x 10000 + 2.6 x 60) / 1024 = 29.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),+ (11.2, 40.8, 56.0, 29.6),),])@@ -164,6 +198,13 @@ class TestPredictUpsertMemory: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_readers_never_hold_more_than_the_fetch_budget(self):+ # Eight readers of 57 MB row groups ask for 456 MB, but the upsert holds 128 MB of it.+ one = predict_upsert_memory(_WIDE, 0.0, 1, 1)+ eight = predict_upsert_memory(_WIDE, 0.0, 1, 8)+ assert eight.reader_mb == pytest.approx(128.0 / 456.0 * 8 * (57.0 + 22.0), abs=0.1)+ assert eight.reader_mb < 3 * one.reader_mb+def test_decode_uses_an_independent_costliest_worker_bound(self):profile = RewriteProfile(partitions=(@@ -172,8 +213,9 @@ class TestPredictUpsertMemory:))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)+ # The insert-only partition writes the most, the other one decodes: both count.+ assert estimate.writer_mb == pytest.approx(1.8 * 50 + 0.8 * 64)+ assert estimate.decode_mb == pytest.approx(56.0)def test_retention_scales_only_the_rss(self):low = predict_upsert_memory(_WIDE, 0.0, 1, 4, retention=1.4)@@ -182,48 +224,116 @@ class TestPredictUpsertMemory: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)+ # Peak RSS measured for these synthetic shapes on deltalite 0.1.10 (Linux, glibc,+ # MALLOC_MMAP_THRESHOLD_=131072, a warm process).+ @parameterized.expand(+ [+ # 1.9M rows in one 8 MB file per partition, 43 columns: decodes to ~100x its stored size.+ (+ "compressible_files",+ _profile(*([[8.1]] * 2), columns=43, decoded_mb=815.0, source_mb_per_partition=1.3),+ 2.4,+ 1,+ 1,+ 141.6,+ ),+ (+ "compressible_files_two_workers",+ _profile(*([[8.1]] * 2), columns=43, decoded_mb=815.0, source_mb_per_partition=1.3),+ 2.4,+ 2,+ 8,+ 159.3,+ ),+ (+ "wide_table",+ _profile(*([[46.6] * 4] * 4), columns=202, decoded_mb=249.2, source_mb_per_partition=2.7),+ 10.8,+ 1,+ 1,+ 621.5,+ ),+ (+ "small_target_file_size",+ _profile(+ *([[27.3] * 6] * 4), target_mb=32.0, columns=31, decoded_mb=214.3, source_mb_per_partition=0.4+ ),+ 1.6,+ 1,+ 1,+ 254.0,+ ),+ (+ "wide_table_four_workers",+ _profile(*([[46.6] * 4] * 4), columns=202, decoded_mb=249.2, source_mb_per_partition=2.7),+ 10.8,+ 4,+ 1,+ 1365.4,+ ),+ (+ "narrow_table_large_row_groups",+ _profile(*([[75.4] * 4] * 4), columns=7, decoded_mb=400.6, source_mb_per_partition=0.1),+ 0.3,+ 1,+ 1,+ 426.4,+ ),+ (+ "large_insert_of_narrow_rows",+ RewriteProfile(partitions=(PartitionShape.of([], source_bytes=round(332.2 * MB)),), columns=7),+ 332.2,+ 1,+ 1,+ 492.9,+ ),+ ]+ )+ def test_prediction_covers_the_measured_peak(self, _name, profile, source_mb, mpp, mpf, measured_rss_mb):+ assert predict_upsert_memory(profile, source_mb, mpp, mpf, retention=1.4).rss_mb >= measured_rss_mb+class TestSizeUpsert:@parameterized.expand([- ("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),+ ("small_files_take_the_widest_plan", _SMALL, None, 2.0, _SLOT, 4, 4, True),+ # The fetch budget bounds the readers, so large row groups keep every reader.+ ("fetch_budget_keeps_readers_on_large_row_groups", _WIDE, None, 1.4, _SLOT, 1, 8, True),+ # (1, 2) = 1.4 x 460.6 does not fit 588.8; (1, 1) = 1.4 x 381.6 does.+ ("small_slot_steps_readers_down", _WIDE, None, 1.4, _SLOT_14GI, 1, 1, True),+ ("workers_before_readers", _profile(*([[57.0] * 6] * 4)), None, 1.4, _SLOT, 3, 5, True),+ ("partition_cap_fills_readers", _SMALL, 2, 2.0, _SLOT, 2, 8, True),+ ("single_small_partition_gets_the_widest_worker", _profile([0.5] * 6), None, 2.0, _SLOT, 1, 8, True),+ ("three_partitions_share_the_reader_ceiling", _profile(*([[0.5] * 6] * 3)), None, 2.0, _SLOT, 3, 5, True),+ # One 1 GB row group: even (1, 1) is 2 x (1024 + 22 + 231.2 + 56 + 15.3) > slot.+ ("huge_row_group_does_not_fit", _profile([1024.0] * 3), None, 2.0, _SLOT, 1, 1, False),+ # Unknown shapes assume target-sized files of 64 columns in every worker.+ ("unknown_shape_is_conservative", None, 4, 1.4, _SLOT, 3, 5, True),+ ("unknown_shape_does_not_fit_a_small_slot", None, 4, 1.4, _SLOT_14GI, 1, 1, False),])- 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)+ def test_sizing(self, _name, profile, n_partitions, retention, slot, 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 <= 16assert plan.predicted_peak_mb == plan.estimate.rss_mbif exp_fits:- assert plan.predicted_peak_mb <= _SLOT- kwargs = plan.as_upsert_kwargs()- assert set(kwargs) == {- "max_parallel_partitions",- "max_parallel_files",- "max_buffered_bytes",- "probe_concurrency",- }+ assert plan.predicted_peak_mb <= slot# Probes are budgeted against max_buffered_bytes, so the raised concurrency goes out in- # every plan; leaving it out would silently hand deltalite its default of 8.- assert kwargs["probe_concurrency"] == 32+ # every plan; leaving it out would silently hand deltalite its default of 8. The reader+ # term assumes the fetch budget, so it goes out too.+ assert plan.as_upsert_kwargs() == {+ "max_parallel_partitions": plan.max_parallel_partitions,+ "max_parallel_files": plan.max_parallel_files,+ "max_buffered_bytes": 64 * MB,+ "max_fetch_bytes": 128 * MB,+ "probe_concurrency": 32,+ }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+ plan = size_upsert(_SLOT_14GI, 10.0, None, _WIDE, 1.4)+ wider = predict_upsert_memory(_WIDE, 10.0, 1, 2, retention=1.4)+ assert wider.rss_mb > _SLOT_14GI >= plan.predicted_peak_mbdef test_empty_source_sizes_one_idle_worker(self):plan = size_upsert(_SLOT, 0.0, None, RewriteProfile(partitions=(), table_files=10))@@ -380,8 +490,7 @@ class TestGovernorSizing: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+ assert (adm.max_row_group_mb, adm.rewrite_files, adm.rewrite_total_mb, adm.columns) == (57.0, 24, 1368.0, 64)async def test_reservation_released_on_exception(self):sampler = _fake_sampler(1_000.0, 1_000.0)@@ -505,12 +614,14 @@ _FILES = []-def _add_actions(files=_FILES, *, with_stats=True) -> pa.Table:+def _add_actions(files=_FILES, *, with_stats=True, num_records=None) -> 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 num_records is not None:+ columns["num_records"] = pa.array(num_records, pa.int64())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())@@ -567,6 +678,23 @@ class TestRewriteProfile: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)]+ @parameterized.expand(+ [+ # a's two candidates hold 40 + 60 rows.+ ("rows_size_the_decoded_volume", [10, 40, 60, 5, 7], True),+ # A file without a row count leaves the volume unknown, which sizes it at the budget.+ ("missing_row_count_is_unknown", [10, 40, None, 5, 7], False),+ ("no_row_counts_is_unknown", None, False),+ ]+ )+ def test_decoded_volume_and_columns(self, _name, num_records, known):+ source = _source([("a", 150), ("a", 250)])+ profile = rewrite_profile(_add_actions(num_records=num_records), source, _PART, ["id"])+ shape = profile.partitions[0]+ assert shape.stored_bytes == 80+ assert shape.decoded_bytes == (round(100 * source.nbytes / source.num_rows) if known else None)+ assert profile.columns == 2+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"])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 ba2c1d1567d7..22566b0f5f2c 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@@ -1214,7 +1214,7 @@ class TestDeltaliteWritePath:reset_governor_for_tests(None)assert wrote is Truelog_kwargs = logger.ainfo.call_args.kwargs- assert log_kwargs["governor_rewrite_files"] == 1+ assert (log_kwargs["governor_rewrite_files"], log_kwargs["governor_columns"]) == (1, 3)assert log_kwargs["governor_rewrite_total_mb"] == round(partition_a_bytes / (1024 * 1024), 1)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 None@@ -1225,6 +1225,7 @@ class TestDeltaliteWritePath:assert "governor_observed_delta_mb" not in log_kwargsupsert_kwargs = fake_table.upsert.call_args.kwargsassert (upsert_kwargs["max_parallel_partitions"], upsert_kwargs["max_parallel_files"]) == (1, 8)+ assert upsert_kwargs["max_fetch_bytes"] == 128 * 1024 * 1024@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 ef90d533aa15..c52c917b29d0 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@@ -334,6 +334,7 @@ class DeltaWriter: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_columns=adm.columns,governor_reserved_slots=adm.reserved_slots,governor_wait_ms=adm.wait_ms,governor_wait_timed_out=adm.wait_timed_out,