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.

refactor(warehouse): recalibrate governor to the threaded memory model (#78152)

Tom Owersf24112a04a08
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py
index c879443deed7..7f81166ad5ae 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
@@ -62,24 +62,29 @@ _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 (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
+# --- Memory model coefficients (threaded process model; REPORT.md §5.6, deltalite_planner's
+# ProcessCalibration) ---------------------------------------------------------------------------
+#
+# 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
#: Beyond 4 partition workers the measured wall-clock gains vanish while memory keeps climbing.
_MAX_PARALLEL_PARTITIONS = 4
+#: Per-call knobs the governor no longer tunes (mpp is the memory dial): deltalite's defaults, kept
+#: explicit so the write is deterministic.
+_MAX_PARALLEL_FILES = 4
+_DEFAULT_BUFFERED_BYTES = 64 * MB
@dataclass(frozen=True)
@@ -89,9 +94,9 @@ class UpsertPlan:
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 marginal peak RSS this upsert adds while running concurrently with others, in MB.
predicted_peak_mb: float
- #: False when even the most conservative single-worker config exceeds the available budget.
+ #: False when even a single worker exceeds the available slice.
fits: bool
def as_upsert_kwargs(self) -> dict[str, int]:
@@ -102,35 +107,31 @@ class UpsertPlan:
}
-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 _predict_marginal_mb(source_mb: float, mpp: int) -> float:
+ """Marginal peak RSS one upsert adds while running concurrently (threaded model, REPORT §5.6)."""
+ return _MARGINAL_BASE_MB + _MARGINAL_PER_WORKER_MB * mpp + _MARGINAL_PER_SOURCE_MB * source_mb
def 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``.
+ ``available_mb`` is the per-upsert memory slice, not the whole pod. Start at the cap and step
+ down. If even a single worker exceeds the slice, return ``mpp=1`` with ``fits=False``. The caller
+ does not fall back on ``fits=False`` — it runs deltalite at ``mpp=1`` anyway (still the memory
+ floor, far below the MERGE) and flags ``capacity_exceeded``. mpp is the memory dial; the other
+ knobs stay at deltalite's defaults.
"""
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)
+ for mpp in range(partition_cap, 0, -1):
+ predicted = _predict_marginal_mb(source_mb, mpp)
+ if predicted <= available_mb:
+ return UpsertPlan(mpp, _MAX_PARALLEL_FILES, _DEFAULT_BUFFERED_BYTES, round(predicted, 1), fits=True)
- # 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)
+ minimal = _predict_marginal_mb(source_mb, 1)
+ return UpsertPlan(1, _MAX_PARALLEL_FILES, _DEFAULT_BUFFERED_BYTES, round(minimal, 1), fits=False)
# --- Reading the pod's real memory (cgroup v2, with v1 and psutil fallbacks) -----------------
@@ -244,8 +245,6 @@ class GovernorConfig:
reserve_mb: float = 2048.0
#: Used only when the cgroup limit is unreadable (local dev). None + unreadable ⇒ deltalite defaults.
limit_override_mb: float | None = None
- #: Shared process floor for the projected-peak / pressure estimate.
- baseline_mb: float = _PROCESS_BASELINE_MB
@staticmethod
def from_env() -> GovernorConfig:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_memory_governor.py
index 509c8e6ad0d0..d12b46b94be3 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
@@ -44,24 +44,21 @@ class _FakePod(PodMemory):
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
- )
+ # Clean arithmetic defaults: no safety derate, no reserve, so the per-upsert slice is exactly
+ # limit / max_concurrent.
+ config = GovernorConfig(mode=mode, safety=1.0, reserve_mb=0.0, max_concurrent=max_concurrent, **cfg)
return MemoryGovernor(config, _FakePod(limit_mb, current_mb))
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
+ # threaded model: marginal(source, mpp) = 220 + 133*mpp + 0.73*source. For source_mb=50 (36.5):
+ # mpp1=389.5 mpp2=522.5 mpp3=655.5 mpp4=788.5
@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
+ ("steps_down_to_two", 600.0, 50.0, None, 2, True), # mpp2=522.5<=600, mpp3=655.5>600
+ ("steps_down_to_one", 450.0, 50.0, None, 1, True), # mpp1=389.5<=450, mpp2=522.5>450
+ ("does_not_fit", 300.0, 50.0, None, 1, False), # mpp1=389.5>300
("partition_cap_limits_mpp", 5_000.0, 50.0, 2, 2, True), # budget allows 4, only 2 partitions
]
)
@@ -76,8 +73,8 @@ class TestSizeUpsert:
}
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)
+ assert _predict_marginal_mb(50, 1) < _predict_marginal_mb(50, 4)
+ assert _predict_marginal_mb(50, 2) < _predict_marginal_mb(500, 2)
class TestPodMemory:
@@ -155,23 +152,24 @@ class TestGovernorModes:
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)
+ # 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):
- # 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:
+ # 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.
+ gov = _governor("enforce", limit_mb=30_000.0, max_concurrent=15)
+ async with gov.admit(source_bytes=2300 * 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:
+ gov = _governor("advisory", limit_mb=30_000.0, max_concurrent=15)
+ async with gov.admit(source_bytes=2300 * MB) as adm:
assert adm.capacity_exceeded is True
assert adm.upsert_kwargs == {} # advisory never changes the write
assert gov._inflight == 0