: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
feat(warehouse): governor loader concurrency + advisory calibration (#77898)
Tom Owersb83ddaaba4e3
diff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.pyindex 894dcb4108d3..af2e83da5e42 100644--- a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py+++ b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py@@ -7,6 +7,9 @@ import structlogfrom posthog.settings import WAREHOUSE_SOURCES_DATABASE_URLfrom posthog.temporal.common.logger import configure_logger+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import (+ configure_process_concurrency,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.health import (HealthState,start_health_server,@@ -217,6 +220,11 @@ class Command(BaseCommand):config = build_consumer_config(options)+ # Size deltalite's per-upsert memory slices against this loader's real concurrency (its own+ # max_concurrency), since it is a Kafka consumer, not a Temporal worker, so the governor's+ # MAX_CONCURRENT_ACTIVITIES source of truth is unset here.+ configure_process_concurrency(config.max_concurrency)+if options.get("claim_path") == "legacy":logger.warning("claim_path_legacy_removed", note="--claim-path is ignored; the legacy claim path no longer exists"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 70efc9693381..c879443deed7 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@@ -52,11 +52,16 @@ MB = 1024 * 1024Mode = 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.+#: Fallback concurrency when nothing else declares it. 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+#: A process's real max concurrent upserts, declared at startup via ``configure_process_concurrency``+#: (e.g. the v3 loader passes its BatchConsumer ``max_concurrency``). Set here rather than read from+#: 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@@ -261,16 +266,20 @@ class GovernorConfig: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.+ Resolution order:+ 1. ``DELTALITE_GOVERNOR_MAX_CONCURRENT`` env override (ops escape hatch).+ 2. A value declared by the process at startup via ``configure_process_concurrency`` — the+ v3 Kafka loader passes its ``BatchConsumer.max_concurrency`` here, since it is not a+ Temporal worker and ``MAX_CONCURRENT_ACTIVITIES`` does not describe it.+ 3. ``settings.MAX_CONCURRENT_ACTIVITIES`` — what the Temporal worker is configured with.+ 4. ``_DEFAULT_MAX_CONCURRENT`` with a warning, so it is visible when the slice is sized+ against a guess rather than the real concurrency."""explicit = os.environ.get("DELTALITE_GOVERNOR_MAX_CONCURRENT")if explicit:return max(1, _env_int("DELTALITE_GOVERNOR_MAX_CONCURRENT", _DEFAULT_MAX_CONCURRENT))+ if _PROCESS_MAX_CONCURRENT is not None:+ return _PROCESS_MAX_CONCURRENTconfigured = getattr(settings, "MAX_CONCURRENT_ACTIVITIES", None)if configured:return max(1, int(configured))@@ -299,6 +308,9 @@ 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.+ 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.capacity_exceeded: bool = False@@ -365,20 +377,23 @@ class MemoryGovernor:budget_mb = self._per_upsert_budget_mb(limit_mb)plan = size_upsert(budget_mb, source_mb, n_partitions)+ # Read live usage now, in every mode, so the observed cgroup delta over the upsert can be+ # logged against the prediction — the calibration advisory mode exists for. Only enforce+ # reserves against the budget; advisory is a pure no-op on the accounting.+ current_at_admit = self.pod.current_mb()admitted = False- current_at_admit: float | None = None- with self._lock:- if self.config.mode == "enforce":+ if self.config.mode == "enforce":+ with self._lock:self._reserved_mb += plan.predicted_peak_mbself._inflight += 1admitted = 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),+ planned_mpp=plan.max_parallel_partitions,capacity_exceeded=not plan.fits,)self._emit_decision(adm, source_mb)@@ -389,11 +404,11 @@ class MemoryGovernor:with self._lock:self._reserved_mb -= plan.predicted_peak_mbself._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)+ # 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 -----------------------------------------------------------------------@@ -429,6 +444,20 @@ class MemoryGovernor:_GOVERNOR: MemoryGovernor | None = None+def configure_process_concurrency(max_concurrent: int) -> None:+ """Declare this process's real max concurrent upserts, from its own source of truth.++ The v3 loader calls this with its ``BatchConsumer.max_concurrency`` at startup, before the first+ upsert, so the governor sizes each memory slice against the loader's actual concurrency instead+ of the Temporal-only ``MAX_CONCURRENT_ACTIVITIES`` (unset there) or a conservative default. Takes+ precedence over the setting; the ``DELTALITE_GOVERNOR_MAX_CONCURRENT`` env override still wins.+ Resets the singleton so the next ``get_governor()`` rebuilds with the declared value.+ """+ global _PROCESS_MAX_CONCURRENT, _GOVERNOR+ _PROCESS_MAX_CONCURRENT = max(1, int(max_concurrent))+ _GOVERNOR = None++def get_governor() -> MemoryGovernor:"""The process-wide governor singleton, built lazily from the environment on first use."""global _GOVERNORdiff --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 a3058cb6bd69..509c8e6ad0d0 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@@ -7,16 +7,27 @@ from django.test import override_settingsfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta import memory_governor as _mgfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.memory_governor import (MB,GovernorConfig,MemoryGovernor,PodMemory,_predict_marginal_mb,+ configure_process_concurrency,size_upsert,)[email protected](autouse=True)+def _reset_process_concurrency():+ # configure_process_concurrency sets a module global; isolate it so tests don't leak into each other.+ saved = _mg._PROCESS_MAX_CONCURRENT+ _mg._PROCESS_MAX_CONCURRENT = None+ yield+ _mg._PROCESS_MAX_CONCURRENT = saved++class _FakePod(PodMemory):"""A PodMemory stand-in. `current_mb` may be a value or a zero-arg callable (to model change)."""@@ -108,13 +119,24 @@ class TestGovernorModes:assert gov._inflight == 0 # off never reservesasync def test_advisory_computes_but_uses_defaults(self):- gov = _governor("advisory")+ gov = _governor("advisory") # 30000 / 15 = 2000 slice -> would pick mpp4async with gov.admit(source_bytes=50 * MB) as adm:- # Advisory plans (predicted peak + budget set) but must not change the write or reserve.+ # 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.assert adm.upsert_kwargs == {}assert adm.predicted_peak_mb is not None and adm.budget_mb is not None+ assert adm.planned_mpp == 4assert gov._inflight == 0 and gov._reserved_mb == 0.0+ async def test_advisory_records_observed_delta_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+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)@@ -227,6 +249,26 @@ class TestConfigFromEnv:with patch.dict("os.environ", {}, clear=True), override_settings(MAX_CONCURRENT_ACTIVITIES=None):assert GovernorConfig.from_env().max_concurrent == 100++class TestProcessConcurrency:+ """configure_process_concurrency lets a non-Temporal worker (the v3 loader) declare its own+ concurrency, instead of relying on MAX_CONCURRENT_ACTIVITIES or an env var."""++ def test_declared_concurrency_used_when_setting_unset(self):+ configure_process_concurrency(16)+ with patch.dict("os.environ", {}, clear=True), override_settings(MAX_CONCURRENT_ACTIVITIES=None):+ assert GovernorConfig.from_env().max_concurrent == 16++ def test_declared_concurrency_beats_setting(self):+ configure_process_concurrency(16)+ with patch.dict("os.environ", {}, clear=True), override_settings(MAX_CONCURRENT_ACTIVITIES=50):+ assert GovernorConfig.from_env().max_concurrent == 16++ def test_env_override_beats_declared_concurrency(self):+ configure_process_concurrency(16)+ with patch.dict("os.environ", {"DELTALITE_GOVERNOR_MAX_CONCURRENT": "8"}, clear=True):+ assert GovernorConfig.from_env().max_concurrent == 8+def test_reads_numeric_overrides(self):env = {"DELTALITE_GOVERNOR_MODE": "enforce",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 080459eb71c1..91c72641a91d 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@@ -257,7 +257,7 @@ class DeltaWriter: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"),+ governor_mpp=adm.planned_mpp,**_deltalite_write_stats(stats),)DELTALITE_WRITE_TOTAL.labels(outcome="written").inc()