: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
fix(data-warehouse): base repartition detection on live partition size (#68186)
Tom Owers805c82a43a76
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.pyindex 6b3694cc33b4..57c854981636 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py@@ -290,7 +290,7 @@ async def repartition_table_in_place(storage_options=storage_options,logger=logger,)- await logger.ainfo("repartition: no delta table, skipping", schema_id=str(schema.id))+ await logger.ainfo(f"repartition: no delta table, skipping schema_id={schema.id}", schema_id=str(schema.id))return {"outcome": "skipped", "reason": "no_delta_table"}partition_bytes = await asyncio.to_thread(measure_partition_bytes, old_delta)@@ -308,7 +308,7 @@ async def repartition_table_in_place(if resuming:resolved = targetrows_written = old_row_count- await logger.ainfo("repartition: resuming from swap marker", schema_id=str(schema.id))+ await logger.ainfo(f"repartition: resuming from swap marker schema_id={schema.id}", schema_id=str(schema.id))else:# Fresh build: clear any stale temp folder, then stream the live table into it.async with aget_s3_client() as s3:@@ -364,7 +364,11 @@ async def repartition_table_in_place(helper.get_delta_table.cache_clear()await logger.ainfo(- "repartition: completed",+ f"repartition: completed schema_id={schema.id} rows={rows_written} "+ f"mode={before['partition_mode']}->{resolved.partition_mode} "+ f"format={before['partition_format']}->{resolved.partition_format} "+ f"count={before['partition_count']}->{resolved.partition_count} "+ f"size={before['partition_size']}->{resolved.partition_size}",schema_id=str(schema.id),rows=rows_written,mode=f"{before['partition_mode']}->{resolved.partition_mode}",@@ -411,10 +415,14 @@ async def _resume_swap_with_missing_live(if not temp_present:await asyncio.to_thread(schema.clear_repartition_swap)await asyncio.to_thread(schema.clear_repartition_pending)- await logger.ainfo("repartition: live and temp both missing, skipping", schema_id=str(schema.id))+ await logger.ainfo(+ f"repartition: live and temp both missing, skipping schema_id={schema.id}", schema_id=str(schema.id)+ )return {"outcome": "skipped", "reason": "no_delta_table"}- await logger.ainfo("repartition: live missing mid-swap, resuming from temp", schema_id=str(schema.id))+ await logger.ainfo(+ f"repartition: live missing mid-swap, resuming from temp schema_id={schema.id}", schema_id=str(schema.id)+ )temp_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=temp_uri, storage_options=storage_options)expected_rows = await asyncio.to_thread(_table_row_count, temp_delta)@@ -438,7 +446,11 @@ async def _resume_swap_with_missing_live(await asyncio.to_thread(schema.stamp_last_repartition_at)helper.get_delta_table.cache_clear()- await logger.ainfo("repartition: recovered from interrupted swap", schema_id=str(schema.id), rows=expected_rows)+ await logger.ainfo(+ f"repartition: recovered from interrupted swap schema_id={schema.id} rows={expected_rows}",+ schema_id=str(schema.id),+ rows=expected_rows,+ )return {"outcome": "completed", "row_count": expected_rows, "recovered": True}diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.pyindex eb60ef2476df..d61eef1c745a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.py@@ -141,7 +141,8 @@ async def maybe_flag_for_repartition(partition_bytes = await asyncio.to_thread(measure_partition_bytes, delta_table)if not partition_bytes:await logger.adebug(- "repartition: skipped, no partition measurements in the delta log", schema_id=str(schema.id)+ f"repartition: skipped, no partition measurements in the delta log schema_id={schema.id}",+ schema_id=str(schema.id),)return@@ -151,7 +152,8 @@ async def maybe_flag_for_repartition(budget = target_partition_bytes()if max_bytes <= budget:await logger.adebug(- "repartition: not needed, largest partition within budget",+ f"repartition: not needed, largest partition within budget schema_id={schema.id} "+ f"max_partition_bytes={max_bytes} budget_bytes={budget} partition_count={len(partition_bytes)}",schema_id=str(schema.id),max_partition_bytes=max_bytes,budget_bytes=budget,@@ -163,7 +165,8 @@ async def maybe_flag_for_repartition(enabled = await asyncio.to_thread(is_auto_repartition_enabled, schema)if not enabled:await logger.adebug(- "repartition: over budget but skipped, controller disabled by feature flag",+ f"repartition: over budget but skipped, controller disabled by feature flag "+ f"schema_id={schema.id} max_partition_bytes={max_bytes} budget_bytes={budget}",schema_id=str(schema.id),max_partition_bytes=max_bytes,budget_bytes=budget,@@ -172,7 +175,8 @@ async def maybe_flag_for_repartition(if schema.repartition_pending is not None:await logger.adebug(- "repartition: over budget but already queued for the next run",+ f"repartition: over budget but already queued for the next run schema_id={schema.id} "+ f"max_partition_bytes={max_bytes} budget_bytes={budget} repartition_pending={schema.repartition_pending}",schema_id=str(schema.id),max_partition_bytes=max_bytes,budget_bytes=budget,@@ -183,7 +187,9 @@ async def maybe_flag_for_repartition(cooldown_remaining = _cooldown_seconds_remaining(schema)if cooldown_remaining > 0:await logger.adebug(- "repartition: over budget but skipped, in post-repartition cooldown",+ f"repartition: over budget but skipped, in post-repartition cooldown schema_id={schema.id} "+ f"max_partition_bytes={max_bytes} budget_bytes={budget} last_repartition_at={schema.last_repartition_at} "+ f"cooldown_seconds_remaining={int(cooldown_remaining)}",schema_id=str(schema.id),max_partition_bytes=max_bytes,budget_bytes=budget,@@ -201,7 +207,10 @@ async def maybe_flag_for_repartition(props.update({"max_partition_bytes_before": max_bytes, "reason": reason})await asyncio.to_thread(capture_repartition_event, "warehouse_repartition_skipped", props)await logger.adebug(- "repartition: over budget but skipped, no finer partitioning target available",+ f"repartition: over budget but skipped, no finer partitioning target available "+ f"schema_id={schema.id} reason={reason} max_partition_bytes={max_bytes} budget_bytes={budget} "+ f"partition_mode={schema.partition_mode} partition_format={schema.partition_format} "+ f"partition_count={len(partition_bytes)}",schema_id=str(schema.id),reason=reason,max_partition_bytes=max_bytes,@@ -229,7 +238,9 @@ async def maybe_flag_for_repartition()await asyncio.to_thread(capture_repartition_event, "warehouse_repartition_flagged", props)await logger.adebug(- "repartition: flagged for next run",+ f"repartition: flagged for next run schema_id={schema.id} max_partition_bytes={max_bytes} "+ f"budget_bytes={budget} target_mode={target.partition_mode} target_format={target.partition_format} "+ f"target_count={target.partition_count} target_size={target.partition_size}",schema_id=str(schema.id),max_partition_bytes=max_bytes,budget_bytes=budget,@@ -240,5 +251,5 @@ async def maybe_flag_for_repartition()except Exception as e:# Detection is best-effort; never fail post-load over it.- await logger.aexception("repartition: detection failed", schema_id=str(schema.id))+ await logger.aexception(f"repartition: detection failed schema_id={schema.id}", schema_id=str(schema.id))capture_exception(e)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.pyindex 63cda2422e5e..ae51869194d1 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,31 +179,38 @@ class TestRepartitionActivity:ActivityEnvironment().run(maybe_repartition_table_activity, inputs)return capture- 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.+ def test_noop_when_flag_disabled(self, team):+ # Healthy no-op: the rollout flag being off short-circuits the gate before any on-disk I/O — no+ # job fetch, no delta read, no detection, no rewrite — regardless of any recorded size. Guards+ # the gate that keeps unflagged syncs free of the extra pre-extraction work.schema = _make_schema(team, {"max_partition_bytes": 5})mocked = AsyncMock()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, "is_auto_repartition_enabled", return_value=False),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"]},- )+ @pytest.mark.parametrize("recorded_max_partition_bytes", [None, 5])+ def test_pre_extraction_flags_over_budget_live_table(self, team, recorded_max_partition_bytes):+ # Nothing queued, flag on: the activity reads the LIVE on-disk size and repartitions when it's+ # over budget. The `recorded_max_partition_bytes=5` case is the fix's core regression: a stale,+ # within-budget recorded value (from a merge that OOMed before it could refresh) must NOT+ # short-circuit detection — the gate now trusts the live size, not the recorded one.+ config: dict = {+ "partitioning_enabled": True,+ "partition_mode": "md5",+ "partition_count": 2,+ "partitioning_keys": ["id"],+ }+ if recorded_max_partition_bytes is not None:+ config["max_partition_bytes"] = recorded_max_partition_bytes+ schema = _make_schema(team, config)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"])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.pyindex c2b6d1812592..801a3c3c3d29 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@@ -69,19 +69,23 @@ 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.+def _needs_pre_extraction_detection(schema: ExternalDataSchema, enabled: bool) -> bool:+ """Whether to read the live on-disk partition sizes to decide if a repartition is needed.++ We deliberately do NOT gate on the recorded `max_partition_bytes`. That value is only refreshed by+ post-load detection, so for a table whose merge OOMs before post-load it goes stale and can sit far+ below the true partition size — precisely the tables this path exists to rescue (e.g. a partition+ that has since grown to many GB while the recorded value still reads a few hundred MB). Instead,+ whenever the rollout flag is on (a targeted set of schemas) and the table isn't CDC-excluded, we+ read the live partition sizes from the Delta log each run and let `maybe_flag_for_repartition` judge+ against the real, current size. The cost is one metadata-only Delta-log read per sync, bounded to+ flagged schemas; a disabled flag still short-circuits to a zero-I/O no-op."""+ if not enabled:+ return Falseif 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()+ return Truedef _maybe_flag_pre_extraction(@@ -128,7 +132,11 @@ def maybe_repartition_table_activity(inputs: RepartitionActivityInputs) -> None:# Always bracket the run with start/finish INFO lines so the Syncs UI shows the activity ran even# on the healthy no-op path (which otherwise only logs at DEBUG). The finally guarantees the finish# line regardless of which branch returns, including swallowed failures.- logger.info("repartition: activity started", job_id=inputs.job_id, source_id=inputs.source_id)+ logger.info(+ f"repartition: activity started job_id={inputs.job_id} source_id={inputs.source_id}",+ job_id=inputs.job_id,+ source_id=inputs.source_id,+ )try:_maybe_repartition_table(inputs, logger)finally:@@ -139,36 +147,46 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterintry: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)+ logger.warning(+ f"repartition: schema not found, skipping activity schema_id={inputs.schema_id}",+ schema_id=inputs.schema_id,+ )return- # Log the rollout-flag verdict (and the sizes that gate detection) so it's clear from the Syncs UI- # why a table does or doesn't repartition — a disabled flag is the most common reason for a no-op.- # Evaluate once here and thread the result into the pre-extraction detection path so the flag- # (a Team DB query plus a PostHog API call) isn't re-evaluated inside maybe_flag_for_repartition.+ # Log the rollout-flag verdict (and the recorded/budget sizes) so it's clear from the Syncs UI why a+ # table does or doesn't repartition — a disabled flag is the most common reason for a no-op. Note+ # `max_partition_bytes` here is the last *recorded* value (can be stale); the gate no longer trusts+ # it, the live size is read below. Evaluate the flag once and thread the result into the+ # pre-extraction detection path so it isn't re-evaluated inside maybe_flag_for_repartition.enabled = is_auto_repartition_enabled(schema)+ recorded_max_partition_bytes = schema.max_partition_bytes+ budget = target_partition_bytes()logger.info(- "repartition: feature flag evaluated",+ f"repartition: feature flag evaluated flag={WAREHOUSE_AUTO_REPARTITION_FLAG} enabled={enabled} "+ f"max_partition_bytes={recorded_max_partition_bytes} target_partition_bytes={budget}",flag=WAREHOUSE_AUTO_REPARTITION_FLAG,enabled=enabled,- max_partition_bytes=schema.max_partition_bytes,- target_partition_bytes=target_partition_bytes(),+ max_partition_bytes=recorded_max_partition_bytes,+ target_partition_bytes=budget,)pending = schema.repartition_pendingswap = schema.repartition_swap- # Fast no-op path: nothing queued and the in-memory gate says no on-disk measurement is needed.- # Return here — before fetching the job and reading the delta log — so the common healthy- # invocation avoids all on-disk I/O.- if pending is None and swap is None and not _needs_pre_extraction_detection(schema):+ # Fast no-op path: nothing queued and the gate says no on-disk measurement is needed (flag off, or+ # CDC). Return here — before fetching the job and reading the delta log — so the common healthy+ # invocation avoids all on-disk I/O. Flagged tables fall through and measure the live size below.+ if pending is None and swap is None and not _needs_pre_extraction_detection(schema, enabled):logger.info("repartition: nothing queued and no detection needed, nothing to do")returntry:job = ExternalDataJob.objects.get(id=inputs.job_id)except ExternalDataJob.DoesNotExist:- logger.warning("repartition: job not found, skipping activity", job_id=inputs.job_id)+ logger.warning(+ f"repartition: job not found, skipping activity job_id={inputs.job_id}",+ job_id=inputs.job_id,+ )returnhelper = DeltaTableHelper(resource_name=schema.name, job=job, logger=logger)@@ -188,7 +206,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinstarted_props = base_event_props(schema, schema.source, inputs.job_id)started_props["trigger_reason"] = trigger_reasoncapture_repartition_event("warehouse_repartition_started", started_props)- logger.info("repartition: starting", trigger_reason=trigger_reason)+ logger.info(f"repartition: starting trigger_reason={trigger_reason}", trigger_reason=trigger_reason)start = time.monotonic()try:@@ -230,7 +248,12 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin"warehouse_repartition_completed" if result.get("outcome") == "completed" else "warehouse_repartition_skipped")capture_repartition_event(event, props)- logger.info("repartition: finished", outcome=result.get("outcome"), duration_seconds=duration)+ outcome = result.get("outcome")+ logger.info(+ f"repartition: finished outcome={outcome} duration_seconds={duration}",+ outcome=outcome,+ duration_seconds=duration,+ )def _handle_failure(