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.

fix(data-warehouse): detect repartition need pre-extraction so OOMing tables self-heal (#67665)

Tom Owersa8723ef6ebf7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
index 0e51e491bda8..b70a856ef915 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
@@ -179,11 +179,49 @@ class TestRepartitionActivity:
ActivityEnvironment().run(maybe_repartition_table_activity, inputs)
return capture
- def test_noop_when_nothing_pending(self, team):
- inputs = self._inputs(team, _make_schema(team, {}))
+ def test_noop_when_within_budget_measurement_recorded(self, team):
+ # The healthy common path: a within-budget `max_partition_bytes` from a prior post-load run
+ # short-circuits the cheap gate, so nothing pending means no delta read, no detection, no
+ # rewrite. Guards the gate that keeps every healthy sync free of the extra pre-extraction work.
+ schema = _make_schema(team, {"max_partition_bytes": 5})
mocked = AsyncMock()
- self._run(inputs, mocked)
+ with (
+ patch.object(repartition_table, "HeartbeaterSync"),
+ patch.object(repartition_table, "repartition_table_in_place", new=mocked),
+ patch.object(repartition_table, "capture_repartition_event"),
+ patch.object(repartition_table, "target_partition_bytes", return_value=10**12),
+ patch.object(repartition_table, "maybe_flag_for_repartition") as flag,
+ ):
+ ActivityEnvironment().run(maybe_repartition_table_activity, self._inputs(team, schema))
mocked.assert_not_called()
+ flag.assert_not_called()
+
+ def test_pre_extraction_flags_over_budget_table_and_repartitions(self, team):
+ # No target was queued, but the on-disk partition is over budget: the activity must detect and
+ # rewrite it here, pre-extraction. This is the path that rescues a table whose merge OOMs every
+ # run and so never reaches post-load detection to flag itself — without it the activity is a noop.
+ schema = _make_schema(
+ team,
+ {"partitioning_enabled": True, "partition_mode": "md5", "partition_count": 2, "partitioning_keys": ["id"]},
+ )
+ mocked = AsyncMock(return_value={"outcome": "completed", "row_count": 4, "partition_mode_after": "md5"})
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_partitioned_delta(f"{d}/t", ["0", "0", "1", "1"])
+ with (
+ patch.object(repartition_table, "HeartbeaterSync"),
+ patch.object(repartition_table, "repartition_table_in_place", new=mocked),
+ patch.object(repartition_table, "capture_repartition_event") as capture,
+ patch.object(repartition_table.DeltaTableHelper, "get_delta_table", new=AsyncMock(return_value=delta)),
+ patch.object(ctrl, "target_partition_bytes", return_value=1),
+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),
+ patch.object(ctrl, "capture_repartition_event"),
+ ):
+ ActivityEnvironment().run(maybe_repartition_table_activity, self._inputs(team, schema))
+
+ mocked.assert_awaited_once()
+ emitted = [c.args[0] for c in capture.call_args_list]
+ assert "warehouse_repartition_started" in emitted
+ assert "warehouse_repartition_completed" in emitted
def test_success_emits_completed(self, team):
schema = _make_schema(team, {})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
index 171211bbf00b..eebc644626a1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
@@ -16,6 +16,7 @@ from django.db import close_old_connections
import structlog
from asgiref.sync import async_to_sync
from structlog.contextvars import bind_contextvars
+from structlog.types import FilteringBoundLogger
from temporalio import activity
from posthog.exceptions_capture import capture_exception
@@ -35,6 +36,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
MAX_REPARTITION_ATTEMPTS,
base_event_props,
capture_repartition_event,
+ maybe_flag_for_repartition,
+ target_partition_bytes,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
DELTA_REPARTITION_DURATION_SECONDS,
@@ -64,6 +67,50 @@ def _target_from_schema(schema: ExternalDataSchema) -> RepartitionTarget:
)
+def _needs_pre_extraction_detection(schema: ExternalDataSchema) -> bool:
+ """Whether to measure the on-disk table for a repartition need, using only in-memory schema state.
+
+ Keeps the healthy no-op path free of any I/O (no job fetch, no delta-log read): we only fall through
+ to the on-disk measurement for a non-CDC table (CDC is excluded from the controller, matching the
+ post-load call site in load.py) whose last post-load measurement is over budget or was never
+ recorded. The never-recorded case covers a table whose merge OOMs every run, so post-load detection
+ never ran to record one — the chicken-and-egg this whole path exists to break.
+ """
+ if schema.sync_type == ExternalDataSchema.SyncType.CDC:
+ return False
+ last_measured = schema.max_partition_bytes
+ return last_measured is None or last_measured > target_partition_bytes()
+
+
+def _maybe_flag_pre_extraction(
+ schema: ExternalDataSchema,
+ job: ExternalDataJob,
+ helper: DeltaTableHelper,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any] | None:
+ """Measure the on-disk table before extraction and flag a repartition if it's over budget.
+
+ The post-load detector (`maybe_flag_for_repartition`) only runs after a merge completes, so a table
+ whose merge OOMs every run can never flag itself for repair — the classic chicken-and-egg. Running
+ the same detection (same feature-flag, budget, and cooldown gating) here, pre-extraction, closes
+ that gap: the on-disk table already reflects the over-budget layout, so we can flag and — in this
+ same run — rewrite it before the merge that would OOM. Returns the pending target set by detection,
+ or None if nothing was flagged (or the table couldn't be measured). Never raises.
+ """
+ try:
+ delta_table = async_to_sync(helper.get_delta_table)()
+ if delta_table is None:
+ logger.debug("repartition: no delta table on disk, cannot measure for repartition")
+ return None
+ async_to_sync(maybe_flag_for_repartition)(schema, schema.source, job, delta_table, logger)
+ except Exception as e:
+ # Detection is best-effort; a failure here must not block the sync.
+ logger.warning("repartition: pre-extraction detection failed", exc_info=True)
+ capture_exception(e)
+ return None
+ return schema.repartition_pending
+
+
@activity.defn
def maybe_repartition_table_activity(inputs: RepartitionActivityInputs) -> None:
# Sync activity (runs in the worker's thread pool) so its ORM access is safe off the event loop;
@@ -75,23 +122,38 @@ def maybe_repartition_table_activity(inputs: RepartitionActivityInputs) -> None:
try:
schema = ExternalDataSchema.objects.select_related("source").get(id=inputs.schema_id)
except ExternalDataSchema.DoesNotExist:
+ logger.warning("repartition: schema not found, skipping activity", schema_id=inputs.schema_id)
return
pending = schema.repartition_pending
swap = schema.repartition_swap
- if pending is None and swap is None:
- return # Nothing queued — cheap common path.
+
+ # Fast no-op path: nothing queued and the in-memory gate says no on-disk measurement is needed.
+ # Return here — before fetching the job — so the common healthy invocation stays a single DB query.
+ if pending is None and swap is None and not _needs_pre_extraction_detection(schema):
+ logger.debug("repartition: nothing queued and no detection needed, nothing to do")
+ return
try:
job = ExternalDataJob.objects.get(id=inputs.job_id)
except ExternalDataJob.DoesNotExist:
+ logger.warning("repartition: job not found, skipping activity", job_id=inputs.job_id)
return
+ helper = DeltaTableHelper(resource_name=schema.name, job=job, logger=logger)
+
+ if pending is None and swap is None:
+ # Nothing was queued by a prior run's post-load detection, but the gate flagged the table for an
+ # on-disk measurement. Measure now and self-flag if it's over budget — the only path that can
+ # rescue a table which OOMs its merge every run (and so never reaches post-load detection).
+ pending = _maybe_flag_pre_extraction(schema, job, helper, logger)
+ if pending is None:
+ logger.debug("repartition: pre-extraction measurement found no repartition needed")
+ return
+
target = RepartitionTarget.from_dict(pending) if pending is not None else _target_from_schema(schema)
trigger_reason = (pending or {}).get("trigger_reason", "resume")
- helper = DeltaTableHelper(resource_name=schema.name, job=job, logger=logger)
-
started_props = base_event_props(schema, schema.source, inputs.job_id)
started_props["trigger_reason"] = trigger_reason
capture_repartition_event("warehouse_repartition_started", started_props)