Skip to content

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

feat(warehouse): deltalite memory capacity governor (#77216)

Tom Owers3dfb3d76bc46
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py
new file mode 100644
index 000000000000..70efc9693381
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py
@@ -0,0 +1,443 @@
+"""Runtime memory capacity planning for concurrent deltalite upserts on one pod.
+
+deltalite runs as Temporal activity threads inside a single worker process: every
+concurrent upsert — plus every delta-rs MERGE fallback and full-sync ``write_deltalake`` —
+shares one address space and one cgroup memory limit. This governor decides, per upsert and
+how large an upsert to run: it picks the per-call knobs
+(``max_parallel_partitions`` / ``max_parallel_files`` / ``max_buffered_bytes``) sized to a fixed
+per-upsert slice of pod memory. The slice is ``(pod limit × safety − reserve) / max_concurrent``,
+so however many upserts run at once (up to the pod's ``MAX_CONCURRENT_ACTIVITIES``) their peaks sum
+to less than the pod. deltalite therefore **always writes** — it never falls back to the delta-rs
+MERGE 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.
+
+Two layers, by design:
+
+* This governor (Python) is the **planner**. It divides the usable pod memory into equal
+ per-upsert slices (one per concurrent activity) and sizes each upsert's knobs to its slice, so
+ the concurrent upserts always fit. Memory for *non-deltalite* writers (full syncs, the rare
+ genuine-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.
+* ``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 the
+ governor predicted. The governor aims never to reach it; the backstop guarantees safety when a
+ prediction is wrong.
+
+The memory model (rust/deltalite ``REPORT.md`` §5.5–5.7): peak memory does **not** track the
+target table size. It tracks the resident source batch (the floor — linear in source rows, and
+no knob bounds it), the number of concurrent partition workers (``max_parallel_partitions``, the
+memory dial) and the write buffers. So the only inputs that matter for sizing are the source
+batch size and how many partition workers we permit. The coefficients below mirror
+``rust/deltalite/python/deltalite_planner.py`` and are conservative starting points — validate
+against real load and re-fit if needed (the process-global backstop holds either way).
+"""
+
+from __future__ import annotations
+
+import os
+import logging
+import threading
+import contextlib
+from collections.abc import AsyncIterator
+from dataclasses import dataclass, field
+from typing import Literal
+
+from django.conf import settings
+
+logger = logging.getLogger(__name__)
+
+MB = 1024 * 1024
+
+Mode = Literal["off", "advisory", "enforce"]
+
+#: Fallback concurrency when neither the env override nor settings.MAX_CONCURRENT_ACTIVITIES is set.
+#: The Temporal SDK's own default is 100 (posthog's worker wrapper uses 50); we pick the higher
+#: value so an unknown concurrency yields a smaller, safer per-upsert slice rather than over-commit.
+_DEFAULT_MAX_CONCURRENT = 100
+
+# --- Memory model coefficients (mirror deltalite_planner.py; see REPORT.md §5.5-5.7) --------
+
+#: One-off, shared process floor: interpreter, imports, tokio runtime, object-store pools. Paid
+#: once for the whole process, so it is a floor on the projected peak, not a per-upsert cost.
+_PROCESS_BASELINE_MB = 500.0
+#: Marginal cost of one in-flight upsert before any partition worker: snapshot/log state, plan,
+#: channels, PK set bookkeeping.
+_PER_UPSERT_FLOOR_MB = 300.0
+#: The resident source batch is held for the whole upsert; roughly doubled while an interleaved
+#: source is sliced per partition. Conservative (over-counting memory is the safe direction).
+_SOURCE_RESIDENT_MULTIPLIER = 2.0
+#: Cost of one concurrent partition worker on top of its write buffer (in-flight row groups, PK
+#: set, transient source slice).
+_PER_WORKER_OVERHEAD_MB = 150.0
+#: Default output file target; the write buffer per worker is bounded by this.
+_TARGET_FILE_SIZE_MB = 100.0
+#: Beyond 4 partition workers the measured wall-clock gains vanish while memory keeps climbing.
+_MAX_PARALLEL_PARTITIONS = 4
+
+
+@dataclass(frozen=True)
+class UpsertPlan:
+ """A sizing decision for one upsert: the knobs, and the memory it is predicted to add."""
+
+ max_parallel_partitions: int
+ max_parallel_files: int
+ max_buffered_bytes: int
+ #: Predicted marginal peak RSS this upsert adds on top of the shared baseline, in MB.
+ predicted_peak_mb: float
+ #: False when even the most conservative single-worker config exceeds the available budget.
+ fits: bool
+
+ def as_upsert_kwargs(self) -> dict[str, int]:
+ return {
+ "max_parallel_partitions": self.max_parallel_partitions,
+ "max_parallel_files": self.max_parallel_files,
+ "max_buffered_bytes": self.max_buffered_bytes,
+ }
+
+
+def _predict_marginal_mb(source_mb: float, mpp: int, buffered_mb: float) -> float:
+ """Marginal peak RSS one upsert adds: floor + resident source + workers + output buffer."""
+ worker_mb = _TARGET_FILE_SIZE_MB + _PER_WORKER_OVERHEAD_MB
+ return _PER_UPSERT_FLOOR_MB + _SOURCE_RESIDENT_MULTIPLIER * source_mb + mpp * worker_mb + buffered_mb
+
+
+def size_upsert(available_mb: float, source_mb: float, n_partitions: int | None = None) -> UpsertPlan:
+ """Pick the largest ``max_parallel_partitions`` whose marginal peak fits ``available_mb``.
+
+ ``available_mb`` is the per-upsert memory slice, not the whole pod. Strategy: start at the cap
+ and step down; if even one worker with a shrunk buffer does not fit, return the minimal config
+ with ``fits=False``. The caller does not fall back on ``fits=False`` — it runs deltalite at
+ ``mpp=1`` anyway (still the memory floor, far below the MERGE) and flags ``capacity_exceeded``.
+ """
+ partition_cap = _MAX_PARALLEL_PARTITIONS
+ if n_partitions is not None and n_partitions >= 1:
+ partition_cap = min(partition_cap, n_partitions)
+
+ # Try the roomy config first, then a tight one (halved buffer / fewer readers) if nothing fits.
+ for buffered_bytes, mpf in ((64 * MB, 4), (32 * MB, 2)):
+ buffered_mb = buffered_bytes / MB
+ for mpp in range(partition_cap, 0, -1):
+ predicted = _predict_marginal_mb(source_mb, mpp, buffered_mb)
+ if predicted <= available_mb:
+ return UpsertPlan(mpp, mpf, buffered_bytes, round(predicted, 1), fits=True)
+
+ # Nothing fits: report the smallest configuration (mpp=1, tight buffer) and its overshoot.
+ minimal = _predict_marginal_mb(source_mb, 1, 32.0)
+ return UpsertPlan(1, 2, 32 * MB, round(minimal, 1), fits=False)
+
+
+# --- Reading the pod's real memory (cgroup v2, with v1 and psutil fallbacks) -----------------
+
+
+class PodMemory:
+ """Reads the pod's memory limit and live usage from the cgroup the process runs in.
+
+ cgroup v2 (``memory.max`` / ``memory.current``) first, then v1
+ (``memory.limit_in_bytes`` / ``memory.usage_in_bytes``), then psutil for usage on hosts with
+ no 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.
+ """
+
+ _V2_MAX = "/sys/fs/cgroup/memory.max"
+ _V2_CURRENT = "/sys/fs/cgroup/memory.current"
+ _V1_MAX = "/sys/fs/cgroup/memory/memory.limit_in_bytes"
+ _V1_CURRENT = "/sys/fs/cgroup/memory/memory.usage_in_bytes"
+ # A v1 "unlimited" limit is a sentinel near the top of the address space, not a real cap.
+ _V1_UNLIMITED = 0x7FFFFFFFFFFFF000
+
+ def __init__(self, limit_override_mb: float | None = None) -> None:
+ self._limit_override_mb = limit_override_mb
+ self._limit_mb: float | None = None
+ self._limit_read = False
+
+ @staticmethod
+ def _read_int(path: str) -> int | None:
+ try:
+ with open(path) as f:
+ raw = f.read().strip()
+ except (OSError, ValueError):
+ return None
+ if raw == "max": # cgroup v2 unlimited
+ return None
+ try:
+ return int(raw)
+ except ValueError:
+ return None
+
+ def limit_mb(self) -> float | None:
+ """The pod's memory limit in MB, or None if it cannot be determined (unlimited/unreadable)."""
+ if self._limit_read:
+ return self._limit_mb
+ self._limit_read = True
+ if self._limit_override_mb is not None:
+ self._limit_mb = self._limit_override_mb
+ return self._limit_mb
+ for path in (self._V2_MAX, self._V1_MAX):
+ v = self._read_int(path)
+ if v is not None and 0 < v < self._V1_UNLIMITED:
+ self._limit_mb = v / MB
+ return self._limit_mb
+ self._limit_mb = None
+ return None
+
+ def current_mb(self) -> float | None:
+ """Live memory currently used by everything in this cgroup, in MB, or None if unreadable."""
+ for path in (self._V2_CURRENT, self._V1_CURRENT):
+ 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
+
+
+# --- Governor configuration ------------------------------------------------------------------
+
+
+def _env_float(name: str, default: float) -> float:
+ raw = os.environ.get(name)
+ if raw is None or raw.strip() == "":
+ return default
+ try:
+ return float(raw)
+ except ValueError:
+ logger.warning("invalid %s=%r; using default %s", name, raw, default)
+ return default
+
+
+def _env_int(name: str, default: int) -> int:
+ return int(_env_float(name, default))
+
+
+@dataclass(frozen=True)
+class GovernorConfig:
+ """Runtime configuration, read from the environment so it can be tuned without a deploy.
+
+ ``mode`` gates the rollout:
+ * ``off`` — do nothing; upserts use deltalite's own defaults (today's behaviour).
+ * ``advisory`` — compute and log/emit the decision, but still use deltalite defaults for the
+ actual write. Zero behaviour change; validates the model on prod.
+ * ``enforce`` — apply the sized knobs. deltalite still always writes; only the knobs change.
+ """
+
+ mode: Mode = "advisory"
+ #: Fraction of the pod limit deltalite planning may target; the rest is slack for allocator
+ #: retention, pyarrow buffers and anything unmodelled.
+ safety: float = 0.8
+ #: Max upserts that can run concurrently in this process. The usable pod budget is divided by
+ #: this so all ``max_concurrent`` upserts are guaranteed to fit at once — the guarantee that lets
+ #: deltalite always write instead of falling back to the memory-hungry MERGE. Resolved by
+ #: ``_resolve_max_concurrent`` (env override → settings.MAX_CONCURRENT_ACTIVITIES → default).
+ max_concurrent: int = _DEFAULT_MAX_CONCURRENT
+ #: Headroom held back from deltalite for everything else on the pod: full-refresh writes, the
+ #: rare genuine-error MERGE fallback (its RSS tracks table size), interpreter and allocator slack.
+ reserve_mb: float = 2048.0
+ #: Used only when the cgroup limit is unreadable (local dev). None + unreadable ⇒ deltalite defaults.
+ limit_override_mb: float | None = None
+ #: Shared process floor for the projected-peak / pressure estimate.
+ baseline_mb: float = _PROCESS_BASELINE_MB
+
+ @staticmethod
+ def from_env() -> GovernorConfig:
+ mode = os.environ.get("DELTALITE_GOVERNOR_MODE", "advisory").strip().lower()
+ if mode not in ("off", "advisory", "enforce"):
+ logger.warning("invalid DELTALITE_GOVERNOR_MODE=%r; defaulting to advisory", mode)
+ mode = "advisory"
+ override = os.environ.get("DELTALITE_GOVERNOR_LIMIT_MB")
+ return GovernorConfig(
+ mode=mode, # type: ignore[arg-type]
+ safety=_env_float("DELTALITE_GOVERNOR_SAFETY", 0.8),
+ max_concurrent=GovernorConfig._resolve_max_concurrent(),
+ reserve_mb=_env_float("DELTALITE_GOVERNOR_RESERVE_MB", 2048.0),
+ limit_override_mb=float(override) if override else None,
+ )
+
+ @staticmethod
+ def _resolve_max_concurrent() -> int:
+ """Max concurrent upserts on this process, from the same source of truth as the worker.
+
+ Prefers an explicit ``DELTALITE_GOVERNOR_MAX_CONCURRENT``, then
+ ``settings.MAX_CONCURRENT_ACTIVITIES`` (what the Temporal worker is configured with). Falls
+ back to ``_DEFAULT_MAX_CONCURRENT`` with a warning, so it is visible when the slice is sized
+ against a guess rather than the real concurrency. The v3 loader is a Kafka consumer, not a
+ Temporal worker, so ``MAX_CONCURRENT_ACTIVITIES`` does not describe it — set the explicit
+ override there to its consumer-thread count.
+ """
+ explicit = os.environ.get("DELTALITE_GOVERNOR_MAX_CONCURRENT")
+ if explicit:
+ return max(1, _env_int("DELTALITE_GOVERNOR_MAX_CONCURRENT", _DEFAULT_MAX_CONCURRENT))
+ configured = getattr(settings, "MAX_CONCURRENT_ACTIVITIES", None)
+ if configured:
+ return max(1, int(configured))
+ logger.warning(
+ "deltalite governor: neither DELTALITE_GOVERNOR_MAX_CONCURRENT nor "
+ "settings.MAX_CONCURRENT_ACTIVITIES is set; sizing the per-upsert memory slice against a "
+ "default of %d concurrent upserts. Set one to this worker's real concurrency.",
+ _DEFAULT_MAX_CONCURRENT,
+ )
+ return _DEFAULT_MAX_CONCURRENT
+
+
+@dataclass
+class Admission:
+ """The knobs to write one upsert with, plus diagnostics.
+
+ There is no "decline": deltalite ALWAYS writes. The governor only decides how many partition
+ workers 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.
+ """
+
+ upsert_kwargs: dict[str, int]
+ mode: Mode
+ predicted_peak_mb: float | None
+ #: The per-upsert memory slice this upsert was sized against, in MB.
+ budget_mb: float | 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.
+ 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 governor ----------------------------------------------------------------------------
+
+
+class MemoryGovernor:
+ """Process-wide admission control for deltalite upserts. Construct one per process.
+
+ State is guarded by a ``threading.Lock``, not an ``asyncio.Lock``, on purpose: the V3 loader
+ runs concurrent ``process_message`` calls in worker threads, each driving ``DeltaWriter.write``
+ through ``async_to_sync`` on its own short-lived event loop. An ``asyncio.Lock`` binds to the
+ first loop that touches it and is not thread-safe, so a governor singleton shared across those
+ per-thread loops would error or race. The critical sections here are tiny and fully synchronous
+ (a few arithmetic ops, no ``await`` inside, and the lock is never held across the ``yield``), so
+ a plain thread lock is both correct across loops and effectively uncontended.
+ """
+
+ def __init__(self, config: GovernorConfig | None = None, pod: PodMemory | None = None) -> None:
+ self.config = config or GovernorConfig.from_env()
+ self.pod = pod or PodMemory(limit_override_mb=self.config.limit_override_mb)
+ self._lock = threading.Lock()
+ self._reserved_mb = 0.0
+ self._inflight = 0
+
+ # -- accounting --------------------------------------------------------------------------
+
+ def _per_upsert_budget_mb(self, limit_mb: float) -> float:
+ """The fixed memory slice one upsert may size itself to.
+
+ ``(usable pod memory) / max_concurrent`` — so however many upserts run at once (up to
+ ``max_concurrent``), the sum of their sized peaks stays under the pod. This static division
+ is the capacity guarantee that lets deltalite always write without ever falling back to the
+ memory-hungry MERGE for capacity reasons.
+ """
+ usable = limit_mb * self.config.safety - self.config.reserve_mb
+ return max(0.0, usable) / self.config.max_concurrent
+
+ @contextlib.asynccontextmanager
+ async def admit(self, *, source_bytes: int, n_partitions: int | None = None) -> AsyncIterator[Admission]:
+ """Size one upsert to its memory slice and yield the knobs to run it with.
+
+ Use as ``async with governor.admit(...) as adm``. deltalite always writes — the reservation
+ (for observability + oversubscription accounting) is held for the whole ``with`` block and
+ released on exit, even on exception.
+ """
+ source_mb = source_bytes / MB
+
+ if self.config.mode == "off":
+ yield Admission({}, "off", None, None)
+ return
+
+ limit_mb = self.pod.limit_mb()
+ # 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)
+ plan = size_upsert(budget_mb, source_mb, n_partitions)
+
+ admitted = False
+ current_at_admit: float | None = None
+ with self._lock:
+ if self.config.mode == "enforce":
+ self._reserved_mb += plan.predicted_peak_mb
+ self._inflight += 1
+ admitted = True
+ current_at_admit = self.pod.current_mb()
+
+ adm = Admission(
+ upsert_kwargs=plan.as_upsert_kwargs() if admitted else {},
+ mode=self.config.mode,
+ predicted_peak_mb=plan.predicted_peak_mb,
+ budget_mb=round(budget_mb, 1),
+ capacity_exceeded=not plan.fits,
+ )
+ self._emit_decision(adm, source_mb)
+ try:
+ yield adm
+ finally:
+ if admitted:
+ with self._lock:
+ self._reserved_mb -= plan.predicted_peak_mb
+ self._inflight -= 1
+ # Best-effort predicted-vs-actual: how much did cgroup usage actually rise?
+ 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 -----------------------------------------------------------------------
+
+ def _emit_decision(self, adm: Admission, source_mb: float) -> None:
+ """Log the decision and emit metrics. Never raises into the write path."""
+ if adm.capacity_exceeded:
+ logger.warning(
+ "deltalite governor: source %.0f MB exceeds its %.0f MB per-upsert slice "
+ "(max_concurrent=%d); running deltalite at mpp=1. Chunk the source, raise the pod "
+ "memory limit, or lower max_concurrent.",
+ source_mb,
+ adm.budget_mb or 0.0,
+ self.config.max_concurrent,
+ )
+ try:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
+ DELTALITE_GOVERNOR_DECISION_TOTAL,
+ DELTALITE_GOVERNOR_INFLIGHT,
+ DELTALITE_GOVERNOR_PREDICTED_PEAK_MB,
+ DELTALITE_GOVERNOR_RESERVED_MB,
+ )
+
+ outcome = "capacity_exceeded" if adm.capacity_exceeded else "admitted"
+ DELTALITE_GOVERNOR_DECISION_TOTAL.labels(mode=adm.mode, outcome=outcome).inc()
+ DELTALITE_GOVERNOR_INFLIGHT.set(self._inflight)
+ DELTALITE_GOVERNOR_RESERVED_MB.set(self._reserved_mb)
+ if adm.predicted_peak_mb is not None:
+ DELTALITE_GOVERNOR_PREDICTED_PEAK_MB.observe(adm.predicted_peak_mb)
+ except Exception: # noqa: BLE001 - metrics are best-effort; never fail a write over them
+ pass
+
+
+_GOVERNOR: MemoryGovernor | None = None
+
+
+def get_governor() -> MemoryGovernor:
+ """The process-wide governor singleton, built lazily from the environment on first use."""
+ global _GOVERNOR
+ if _GOVERNOR is None:
+ _GOVERNOR = MemoryGovernor()
+ return _GOVERNOR
+
+
+def reset_governor_for_tests(governor: MemoryGovernor | None = None) -> None:
+ """Swap the process singleton — tests only."""
+ global _GOVERNOR
+ _GOVERNOR = governor
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py
new file mode 100644
index 000000000000..a3058cb6bd69
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py
@@ -0,0 +1,238 @@
+import asyncio
+
+import pytest
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import (
+ MB,
+ GovernorConfig,
+ MemoryGovernor,
+ PodMemory,
+ _predict_marginal_mb,
+ size_upsert,
+)
+
+
+class _FakePod(PodMemory):
+ """A PodMemory stand-in. `current_mb` may be a value or a zero-arg callable (to model change)."""
+
+ def __init__(self, limit_mb: float | None, current_mb):
+ super().__init__()
+ self._fake_limit = limit_mb
+ self._fake_current = current_mb
+
+ def limit_mb(self) -> float | None:
+ return self._fake_limit
+
+ def current_mb(self) -> float | None:
+ return self._fake_current() if callable(self._fake_current) else self._fake_current
+
+
+def _governor(mode="enforce", *, limit_mb=30_000.0, current_mb=1_000.0, max_concurrent=15, **cfg) -> MemoryGovernor:
+ # Clean arithmetic defaults: no safety derate, no reserve, no baseline, so the per-upsert
+ # slice is exactly limit / max_concurrent.
+ config = GovernorConfig(
+ mode=mode, safety=1.0, reserve_mb=0.0, baseline_mb=0.0, max_concurrent=max_concurrent, **cfg
+ )
+ return MemoryGovernor(config, _FakePod(limit_mb, current_mb))
+
+
+class TestSizeUpsert:
+ # source_mb=50 -> floor 300 + 2*50 = 400; worker 250; buffer 64.
+ # mpp4 = 400 + 1000 + 64 = 1464 ; mpp1 = 400 + 250 + 64 = 714 ; tight mpp1 = 400+250+32 = 682
+ @parameterized.expand(
+ [
+ ("roomy_takes_max_mpp", 5_000.0, 50.0, None, 4, True),
+ ("steps_down_to_two", 1_000.0, 50.0, None, 2, True), # mpp2=964<=1000, mpp3=1214>1000
+ ("steps_down_to_one", 800.0, 50.0, None, 1, True), # mpp1=714<=800, mpp2=964>800
+ ("tight_shrinks_buffer", 700.0, 50.0, None, 1, True), # only tight mpp1=682 fits
+ ("does_not_fit", 600.0, 50.0, None, 1, False), # even 682 overshoots
+ ("partition_cap_limits_mpp", 5_000.0, 50.0, 2, 2, True), # budget allows 4, only 2 partitions
+ ]
+ )
+ def test_sizing(self, _name, available_mb, source_mb, n_partitions, exp_mpp, exp_fits):
+ plan = size_upsert(available_mb, source_mb, n_partitions)
+ assert plan.max_parallel_partitions == exp_mpp
+ assert plan.fits is exp_fits
+ assert set(plan.as_upsert_kwargs()) == {
+ "max_parallel_partitions",
+ "max_parallel_files",
+ "max_buffered_bytes",
+ }
+
+ def test_predicted_peak_monotonic_in_mpp_and_source(self):
+ assert _predict_marginal_mb(50, 1, 64) < _predict_marginal_mb(50, 4, 64)
+ assert _predict_marginal_mb(50, 2, 64) < _predict_marginal_mb(500, 2, 64)
+
+
+class TestPodMemory:
+ @parameterized.expand(
+ [
+ ("cgroup_v2", {PodMemory._V2_MAX: 30_000 * MB}, 30_000.0),
+ ("v2_max_sentinel_falls_through", {PodMemory._V2_MAX: None, PodMemory._V1_MAX: 20_000 * MB}, 20_000.0),
+ ("unreadable_is_none", {}, None),
+ ("v1_unlimited_is_none", {PodMemory._V1_MAX: PodMemory._V1_UNLIMITED}, None),
+ ]
+ )
+ def test_limit_mb(self, _name, table, expected):
+ with patch.object(PodMemory, "_read_int", staticmethod(lambda p: table.get(p))):
+ assert PodMemory().limit_mb() == expected
+
+ def test_limit_override_wins(self):
+ assert PodMemory(limit_override_mb=12_345.0).limit_mb() == 12_345.0
+
+ def test_current_reads_cgroup(self):
+ with patch.object(PodMemory, "_read_int", staticmethod(lambda p: {PodMemory._V2_CURRENT: 4_096 * MB}.get(p))):
+ assert PodMemory().current_mb() == 4_096.0
+
+
+class TestPerUpsertBudget:
+ def test_divides_usable_pod_by_max_concurrent(self):
+ # usable = 29000 * 0.8 - 2048 = 21152 ; slice = 21152 / 15
+ gov = MemoryGovernor(
+ GovernorConfig(mode="enforce", safety=0.8, reserve_mb=2048.0, max_concurrent=15),
+ _FakePod(29_000.0, 1_000.0),
+ )
+ assert round(gov._per_upsert_budget_mb(29_000.0), 1) == 1410.1
+
+
+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:
+ assert adm.upsert_kwargs == {}
+ assert gov._inflight == 0 # off never reserves
+
+ async def test_advisory_computes_but_uses_defaults(self):
+ gov = _governor("advisory")
+ async with gov.admit(source_bytes=50 * MB) as adm:
+ # Advisory plans (predicted peak + budget set) but must not change the write or reserve.
+ assert adm.upsert_kwargs == {}
+ assert adm.predicted_peak_mb is not None and adm.budget_mb is not None
+ assert gov._inflight == 0 and gov._reserved_mb == 0.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
+ assert adm.capacity_exceeded is False
+ assert gov._inflight == 1 and gov._reserved_mb == adm.predicted_peak_mb
+ assert 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 with gov.admit(source_bytes=50 * MB) as adm:
+ assert adm.upsert_kwargs == {} # can't size a slice, so deltalite defaults
+ assert gov._inflight == 0
+
+
+class TestGovernorSizing:
+ async def test_tight_slice_sizes_mpp_down(self):
+ # 12000 / 15 = 800 slice -> mpp1 fits (714), mpp2 (964) does not.
+ gov = _governor("enforce", limit_mb=12_000.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):
+ # 9000 / 15 = 600 slice -> even tight mpp1 (682) overshoots. Never falls back: runs mpp1.
+ gov = _governor("enforce", limit_mb=9_000.0, max_concurrent=15)
+ async with gov.admit(source_bytes=50 * MB) as adm:
+ assert adm.capacity_exceeded is True
+ assert adm.upsert_kwargs["max_parallel_partitions"] == 1 # still deltalite, minimal
+ assert gov._inflight == 1 # still admitted and reserved
+
+ async def test_advisory_source_too_big_flags_but_no_reserve(self):
+ gov = _governor("advisory", limit_mb=9_000.0, max_concurrent=15)
+ async with gov.admit(source_bytes=50 * MB) as adm:
+ assert adm.capacity_exceeded is True
+ assert adm.upsert_kwargs == {} # advisory never changes the write
+ assert gov._inflight == 0
+
+ async def test_reservation_released_on_exception(self):
+ gov = _governor("enforce")
+ with pytest.raises(ValueError):
+ async with gov.admit(source_bytes=50 * MB) as adm:
+ assert gov._inflight == 1 and gov._reserved_mb == adm.predicted_peak_mb
+ raise ValueError("boom")
+ assert gov._inflight == 0 and gov._reserved_mb == 0.0
+
+ 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:
+ assert gov._inflight == 1
+ async with gov.admit(source_bytes=50 * MB) as second:
+ assert gov._inflight == 2
+ assert first.predicted_peak_mb is not None and second.predicted_peak_mb is not None
+ assert gov._reserved_mb == first.predicted_peak_mb + second.predicted_peak_mb
+ assert 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
+ # event loop" on the second loop; the threading.Lock the governor uses does not. Two
+ # asyncio.run() calls reproduce two distinct loops.
+ gov = _governor("enforce")
+
+ async def _once() -> float | None:
+ async with gov.admit(source_bytes=50 * MB) as adm:
+ assert gov._inflight == 1
+ return adm.predicted_peak_mb
+
+ first = asyncio.run(_once())
+ second = asyncio.run(_once()) # different loop — would fail with an asyncio.Lock
+ assert first == second
+ assert gov._inflight == 0 and gov._reserved_mb == 0.0
+
+
+class TestConfigFromEnv:
+ def test_defaults_to_advisory(self):
+ with patch.dict("os.environ", {}, clear=True):
+ assert GovernorConfig.from_env().mode == "advisory"
+
+ def test_invalid_mode_falls_back_to_advisory(self):
+ with patch.dict("os.environ", {"DELTALITE_GOVERNOR_MODE": "nonsense"}, clear=True):
+ assert GovernorConfig.from_env().mode == "advisory"
+
+ @parameterized.expand([("off", "off"), ("enforce", "enforce"), ("ADVISORY", "advisory")])
+ def test_reads_mode(self, value, expected):
+ with patch.dict("os.environ", {"DELTALITE_GOVERNOR_MODE": value}, clear=True):
+ assert GovernorConfig.from_env().mode == expected
+
+ def test_max_concurrent_defaults_to_activity_setting(self):
+ # from_env reads the same source of truth the worker does: settings.MAX_CONCURRENT_ACTIVITIES.
+ with patch.dict("os.environ", {}, clear=True), override_settings(MAX_CONCURRENT_ACTIVITIES=20):
+ assert GovernorConfig.from_env().max_concurrent == 20
+
+ def test_explicit_env_override_wins_over_setting(self):
+ with (
+ patch.dict("os.environ", {"DELTALITE_GOVERNOR_MAX_CONCURRENT": "8"}, clear=True),
+ override_settings(MAX_CONCURRENT_ACTIVITIES=20),
+ ):
+ assert GovernorConfig.from_env().max_concurrent == 8
+
+ def test_defaults_to_conservative_100_when_unset(self):
+ with patch.dict("os.environ", {}, clear=True), override_settings(MAX_CONCURRENT_ACTIVITIES=None):
+ assert GovernorConfig.from_env().max_concurrent == 100
+
+ def test_reads_numeric_overrides(self):
+ env = {
+ "DELTALITE_GOVERNOR_MODE": "enforce",
+ "DELTALITE_GOVERNOR_SAFETY": "0.7",
+ "DELTALITE_GOVERNOR_RESERVE_MB": "4096",
+ }
+ with patch.dict("os.environ", env, clear=True):
+ cfg = GovernorConfig.from_env()
+ assert (cfg.safety, cfg.reserve_mb) == (0.7, 4096.0)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
index 47c33abdf39d..080459eb71c1 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
@@ -190,6 +190,9 @@ class DeltaWriter:
try:
import deltalite
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import (
+ get_governor,
+ )
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
DELTALITE_WRITE_DURATION_SECONDS,
DELTALITE_WRITE_TOTAL,
@@ -198,19 +201,32 @@ class DeltaWriter:
uri = await self._table.get_table_uri()
storage_options = self._table.get_storage_options()
partition_key = PARTITION_KEY if use_partitioning else None
+ n_partitions = (
+ pc.count_distinct(data[PARTITION_KEY]).as_py()
+ if use_partitioning and PARTITION_KEY in data.column_names
+ else None
+ )
- def _upsert() -> Any:
- table = deltalite.DeltaLiteTable.open(uri, storage_options)
- return table.upsert(
- data,
- list(normalized_primary_keys),
- partition_key,
- commit_metadata=commit_metadata,
- )
+ # 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).
+ async with get_governor().admit(source_bytes=data.nbytes, n_partitions=n_partitions) as adm:
+
+ def _upsert(upsert_kwargs: dict[str, int] = adm.upsert_kwargs) -> Any:
+ table = deltalite.DeltaLiteTable.open(uri, storage_options)
+ return table.upsert(
+ data,
+ list(normalized_primary_keys),
+ partition_key,
+ commit_metadata=commit_metadata,
+ **upsert_kwargs,
+ )
- started = time.perf_counter()
- stats = await asyncio.to_thread(_upsert)
- duration_s = time.perf_counter() - started
+ started = time.perf_counter()
+ stats = await asyncio.to_thread(_upsert)
+ duration_s = time.perf_counter() - started
except Exception as e: # noqa: BLE001 - pre-commit failure: nothing committed, fall back to MERGE
await self._logger.awarning(
f"deltalite write failed; falling back to delta-rs MERGE (sync unaffected): {e}"
@@ -236,6 +252,12 @@ class DeltaWriter:
await self._logger.ainfo(
"deltalite write: committed",
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_budget_mb=adm.budget_mb,
+ governor_capacity_exceeded=adm.capacity_exceeded,
+ governor_mpp=adm.upsert_kwargs.get("max_parallel_partitions"),
**_deltalite_write_stats(stats),
)
DELTALITE_WRITE_TOTAL.labels(outcome="written").inc()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
index 823f82034474..6f0367fcb3c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
@@ -1,4 +1,4 @@
-from prometheus_client import Counter, Histogram
+from prometheus_client import Counter, Gauge, Histogram
DELTA_WRITE_DURATION_SECONDS = Histogram(
"warehouse_load_delta_write_duration_seconds",
@@ -60,3 +60,30 @@ DELTALITE_WRITE_DURATION_SECONDS = Histogram(
"warehouse_load_deltalite_write_duration_seconds",
"Wall-clock time of a deltalite real write (DeltaLiteTable.upsert)",
)
+
+# deltalite memory governor (capacity planning). Sizes each upsert's knobs to a fixed per-upsert
+# slice of pod memory ((limit * safety - reserve) / max_concurrent), so all concurrent upserts fit
+# and deltalite never falls back to the MERGE for capacity. deltalite always writes.
+# mode - off | advisory | enforce
+# outcome - admitted | capacity_exceeded (source too big for its slice; ran at mpp=1)
+DELTALITE_GOVERNOR_DECISION_TOTAL = Counter(
+ "warehouse_load_deltalite_governor_decision_total",
+ "deltalite governor sizing decisions, by mode and outcome",
+ labelnames=["mode", "outcome"],
+)
+
+DELTALITE_GOVERNOR_PREDICTED_PEAK_MB = Histogram(
+ "warehouse_load_deltalite_governor_predicted_peak_mb",
+ "Predicted marginal peak RSS (MB) the governor sized an upsert against",
+ buckets=(128, 256, 512, 1024, 2048, 4096, 8192, 16384),
+)
+
+DELTALITE_GOVERNOR_INFLIGHT = Gauge(
+ "warehouse_load_deltalite_governor_inflight",
+ "deltalite upserts currently admitted and in flight on this process",
+)
+
+DELTALITE_GOVERNOR_RESERVED_MB = Gauge(
+ "warehouse_load_deltalite_governor_reserved_mb",
+ "Total memory (MB) currently reserved by in-flight deltalite upserts on this process",
+)