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(data-warehouse): auto-repartition deltalake tables in place (#67038)

Tom Owersca876fe4a8fe
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.py
index e45024542f01..73b78d0a7a6c 100644
--- a/posthog/settings/data_warehouse.py
+++ b/posthog/settings/data_warehouse.py
@@ -19,6 +19,14 @@ USE_LOCAL_SETUP = TEST or (DEBUG and len(os.getenv("OBJECT_STORAGE_ENDPOINT", "h
PYARROW_DEBUG_LOGGING = get_from_env("PYARROW_DEBUG_LOGGING", False, type_cast=str_to_bool)
+# At-rest (compressed) byte budget per Delta partition. The auto-repartition controller rewrites a
+# table into a finer scheme once its largest partition exceeds this. delta-rs merges need ~20x the
+# partition's at-rest size in memory, so ~1 GB keeps worst-case merge memory (~20 GB) under the
+# 29 GB worker limit with headroom.
+DATA_WAREHOUSE_TARGET_PARTITION_BYTES = get_from_env(
+ "DATA_WAREHOUSE_TARGET_PARTITION_BYTES", 1_000_000_000, type_cast=int
+)
+
GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL")
GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY")
GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID")
diff --git a/posthog/temporal/tests/data_imports/test_end_to_end.py b/posthog/temporal/tests/data_imports/test_end_to_end.py
index d80c46468cea..f1b8f16389d3 100644
--- a/posthog/temporal/tests/data_imports/test_end_to_end.py
+++ b/posthog/temporal/tests/data_imports/test_end_to_end.py
@@ -2117,6 +2117,103 @@ async def test_partition_folders_with_uuid_id_and_created_at(team, postgres_conf
assert schema.partition_count is not None
[email protected]_db(transaction=True)
+async def test_in_place_repartition_to_finer_datetime_format(team, postgres_config, postgres_connection, minio_client):
+ # A datetime-partitioned table that has outgrown its scheme is repartitioned in place to a finer
+ # (daily) layout from the data already in S3 — no source re-pull — and the next incremental merge
+ # then runs against the new layout. Runs the whole pipeline (V2 + V3 via the pipeline_mode fixture).
+ await postgres_connection.execute(
+ "CREATE TABLE IF NOT EXISTS {schema}.test_repartition (id uuid PRIMARY KEY, created_at timestamp)".format(
+ schema=postgres_config["schema"]
+ )
+ )
+ for ts in ("2025-01-15", "2025-01-20", "2025-02-10", "2025-02-15"):
+ await postgres_connection.execute(
+ "INSERT INTO {schema}.test_repartition (id, created_at) VALUES ('{id}', '{ts}T12:00:00.000Z')".format(
+ schema=postgres_config["schema"], id=uuid.uuid4(), ts=ts
+ )
+ )
+ await postgres_connection.commit()
+
+ job_inputs = {
+ "host": postgres_config["host"],
+ "port": postgres_config["port"],
+ "database": postgres_config["database"],
+ "user": postgres_config["user"],
+ "password": postgres_config["password"],
+ "schema": postgres_config["schema"],
+ "ssh_tunnel_enabled": "False",
+ }
+
+ # First sync → datetime partitioning on created_at (week format is the default).
+ _workflow_id, inputs = await _run(
+ team=team,
+ schema_name="test_repartition",
+ table_name="postgres_test_repartition",
+ source_type="Postgres",
+ job_inputs=job_inputs,
+ mock_data_response=[],
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},
+ ignore_assertions=True,
+ )
+
+ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)
+ assert schema.partition_mode == "datetime"
+ assert schema.partition_format == "week"
+
+ count_before = await sync_to_async(execute_hogql_query)("SELECT count() FROM postgres_test_repartition", team)
+ assert count_before.results[0][0] == 4
+
+ # Queue an in-place repartition to a finer (daily) format, then add a new row and re-sync. The
+ # pre-extraction activity rewrites the four existing rows to daily partitions; the incremental
+ # merge then folds in the new March row on that new layout.
+ await sync_to_async(schema.set_repartition_pending)(
+ {
+ "partition_mode": "datetime",
+ "partition_format": "day",
+ "partition_keys": ["created_at"],
+ "partition_count": None,
+ "partition_size": None,
+ "trigger_reason": "test",
+ "attempts": 0,
+ }
+ )
+ await postgres_connection.execute(
+ "INSERT INTO {schema}.test_repartition (id, created_at) VALUES ('{id}', '2025-03-05T12:00:00.000Z')".format(
+ schema=postgres_config["schema"], id=uuid.uuid4()
+ )
+ )
+ await postgres_connection.commit()
+
+ await _execute_run(str(uuid.uuid4()), inputs, [])
+ await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)
+
+ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)
+ assert schema.partition_format == "day", "repartition should have switched the table to daily partitions"
+ assert schema.repartition_pending is None, "the activity should have consumed the pending repartition"
+
+ job = await sync_to_async(
+ lambda: (
+ ExternalDataJob.objects.filter(team_id=team.pk, pipeline_id=inputs.external_data_source_id)
+ .order_by("-created_at")
+ .first()
+ )
+ )()
+ assert job is not None
+ folder_path = await sync_to_async(job.folder_path)()
+ s3_objects = await minio_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=f"{folder_path}/test_repartition/")
+ keys = [obj["Key"] for obj in s3_objects["Contents"]]
+ # Live data is now in daily partition folders (%Y-%m-%d); the old weekly (%G-wWW) folders are gone.
+ assert any(f"{PARTITION_KEY}=2025-01-15" in k for k in keys), keys
+ assert not any(f"{PARTITION_KEY}=2025-w" in k for k in keys), keys
+
+ # No rows lost or duplicated by the rewrite + the subsequent merge.
+ count_after = await sync_to_async(execute_hogql_query)("SELECT count() FROM postgres_test_repartition", team)
+ assert count_after.results[0][0] == 5
+
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
@pytest.mark.parametrize(
diff --git a/products/warehouse_sources/backend/admin/external_data_schema_admin.py b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
index 11e55e01d578..73233d186a3b 100644
--- a/products/warehouse_sources/backend/admin/external_data_schema_admin.py
+++ b/products/warehouse_sources/backend/admin/external_data_schema_admin.py
@@ -256,16 +256,30 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
# new mode is ever added.
assert_never(new_mode)
- change_label = (
- ", ".join(label_bits) + " (pinned for this reset)" if label_bits else "repartition (pinned for this reset)"
- )
+ change_label = ", ".join(label_bits) if label_bits else "repartition"
+
+ # Translate the validated operator inputs into a `repartition_pending` target. The next run's
+ # pre-extraction activity rewrites the existing S3 data into this scheme in place — no source
+ # re-pull, no reset. `staged` is reused only as a validated carrier of the chosen knobs.
+ target = {
+ "partition_mode": new_mode,
+ "partition_format": staged.get("partition_format"),
+ "partition_count": staged.get("partition_count_override"),
+ "partition_size": staged.get("partition_size_override"),
+ "partition_keys": (
+ staged.get("partitioning_keys_override") or schema.partitioning_keys or schema.primary_key_columns or []
+ ),
+ "trigger_reason": "admin",
+ "attempts": 0,
+ }
return self._pause_save_and_resync(
request,
schema,
- staged_updates=staged,
+ staged_updates={"repartition_pending": target},
change_label=change_label,
workflow_kind="repartition",
+ reset_pipeline=False,
)
def _pause_save_and_resync(
@@ -276,10 +290,12 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
staged_updates: dict[str, Any],
change_label: str,
workflow_kind: str,
+ reset_pipeline: bool = True,
):
# Shared tail for the partition-tuning admin actions (repartition, change partition mode):
- # pause the schedule, stage the operator's sync_type_config updates alongside
- # reset_pipeline, and trigger a single non-billable reset resync.
+ # pause the schedule, stage the operator's sync_type_config updates, and trigger a single
+ # non-billable run. With reset_pipeline=True the run re-pulls from source; with False the run's
+ # pre-extraction activity repartitions in place from S3 (no source pull) before syncing.
#
# Pause first so the scheduled workflow doesn't race with the admin one (Temporal's
# "OnlyOne" overlap policy is per-schedule, not across schedule + ad-hoc workflow). If
@@ -308,7 +324,8 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
# re-read True and wipe Delta + cursor, restarting from row 0.
for key, value in staged_updates.items():
schema.sync_type_config[key] = value
- schema.sync_type_config["reset_pipeline"] = True
+ if reset_pipeline:
+ schema.sync_type_config["reset_pipeline"] = True
if admin_paused_now:
schema.sync_type_config["admin_unpause_schedule_after_run"] = True
schema.save(update_fields=["sync_type_config"])
@@ -337,7 +354,7 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
pass
messages.error(
request,
- f"Saved {change_label}, but failed to trigger reset resync: {e}. "
+ f"Saved {change_label}, but failed to trigger run: {e}. "
f"Trigger one manually before the next scheduled sync.",
)
return redirect(_change_url(schema.id))
@@ -347,9 +364,14 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):
if admin_paused_now
else " Schedule was already paused; leaving it paused."
)
+ run_note = (
+ "non-billable reset resync (re-pulls from source)"
+ if reset_pipeline
+ else "non-billable in-place repartition (no source pull)"
+ )
messages.success(
request,
- f"{change_label}. Triggered non-billable reset resync (workflow_id={workflow_id}).{pause_note}",
+ f"{change_label}. Triggered {run_note} (workflow_id={workflow_id}).{pause_note}",
)
return redirect(_change_url(schema.id))
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index a559d949e919..53bda9cafba6 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -6,6 +6,7 @@ from typing import Any, Literal, Optional
from django.conf import settings
from django.db import models, transaction
+from django.utils import timezone
from dateutil import parser
from django_deprecate_fields import deprecate_field
@@ -64,7 +65,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
status = models.CharField(max_length=400, null=True, blank=True)
last_synced_at = models.DateTimeField(null=True, blank=True)
sync_type = models.CharField(max_length=128, choices=SyncType, null=True, blank=True)
- # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int }
+ # { "incremental_field": string, "incremental_field_type": string, "incremental_field_last_value": any, "incremental_field_earliest_value": any, "incremental_field_lookback_seconds": int | None, "reset_pipeline": bool, "partitioning_enabled": bool, "partition_count": int, "partition_size": int, "partition_mode": str, "partitioning_keys": list[str], "chunk_size_override": int | None, "primary_key_columns": list[str] | None, "xmin_last_value": int, "xmin_ceiling": int, "xmin_num_wraparound": int, "max_partition_bytes": int, "last_repartition_at": iso8601 str, "repartition_pending": { "partition_mode": str, "partition_format": str | None, "partition_count": int | None, "partition_size": int | None, "partition_keys": list[str], "trigger_reason": str }, "repartition_swap": { "state": "ready", "temp_uri": str, "live_uri": str } }
sync_type_config = models.JSONField(
default=dict,
blank=True,
@@ -388,6 +389,69 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
self.sync_type_config.pop("partitioning_keys_override", None)
self.save()
+ # --- In-place repartition controller state ------------------------------------------------
+ # These keys drive the automated, no-source-pull repartition that bounds per-partition memory
+ # so incremental merges stop OOMing the worker. Detection records `max_partition_bytes` and (when
+ # over budget) a `repartition_pending` target; the next run's pre-extraction activity performs the
+ # in-place rewrite, using `repartition_swap` as a crash-safe marker, then stamps `last_repartition_at`.
+
+ @property
+ def max_partition_bytes(self) -> int | None:
+ if self.sync_type_config:
+ return self.sync_type_config.get("max_partition_bytes", None)
+ return None
+
+ @property
+ def last_repartition_at(self) -> str | None:
+ if self.sync_type_config:
+ return self.sync_type_config.get("last_repartition_at", None)
+ return None
+
+ @property
+ def repartition_pending(self) -> dict[str, Any] | None:
+ if self.sync_type_config:
+ pending = self.sync_type_config.get("repartition_pending", None)
+ if isinstance(pending, dict):
+ return pending
+ return None
+
+ @property
+ def repartition_swap(self) -> dict[str, Any] | None:
+ if self.sync_type_config:
+ swap = self.sync_type_config.get("repartition_swap", None)
+ if isinstance(swap, dict):
+ return swap
+ return None
+
+ def _save_sync_type_config(self) -> None:
+ # Internal bookkeeping write — skip the activity-log SELECT (see save()) since these run
+ # inside the sync/repartition activity where a dropped pooler connection would fail the run.
+ self.save(update_fields=["sync_type_config", "updated_at"], skip_activity_log=True)
+
+ def record_partition_measurement(self, max_partition_bytes: int) -> None:
+ self.sync_type_config["max_partition_bytes"] = max_partition_bytes
+ self._save_sync_type_config()
+
+ def set_repartition_pending(self, target: dict[str, Any]) -> None:
+ self.sync_type_config["repartition_pending"] = target
+ self._save_sync_type_config()
+
+ def clear_repartition_pending(self) -> None:
+ self.sync_type_config.pop("repartition_pending", None)
+ self._save_sync_type_config()
+
+ def set_repartition_swap(self, swap: dict[str, Any]) -> None:
+ self.sync_type_config["repartition_swap"] = swap
+ self._save_sync_type_config()
+
+ def clear_repartition_swap(self) -> None:
+ self.sync_type_config.pop("repartition_swap", None)
+ self._save_sync_type_config()
+
+ def stamp_last_repartition_at(self) -> None:
+ self.sync_type_config["last_repartition_at"] = timezone.now().isoformat()
+ self._save_sync_type_config()
+
def stage_incremental_field_value(self, run_uuid: str, last_value: Any, earliest_value: Any = None) -> None:
existing = self.sync_type_config.get("incremental_staged", {})
if existing.get("run_uuid") == run_uuid:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index 0b28c6458a3c..bcd9bf960834 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -32,6 +32,26 @@ If the `partition_mode` is either `md5` or `numerical`, then you'll want to do a
If the table has no partitions, but it could be partitioned, then again just resync the table following below.
+### Automated in-place repartitioning
+
+The manual flow above re-pulls every row from the source. We also have an automated path that repartitions the data **already in S3**, so it never re-extracts from the source and never materialises an oversized partition. It lives in `pipelines/pipeline/repartition.py` (the streaming rewrite + crash-safe swap), `pipelines/pipeline/repartition_controller.py` (size-aware detection + gating), and `workflow_activities/repartition_table.py` (the pre-extraction activity that runs it).
+
+How it works:
+
+- **Detection.** After each sync, the controller measures per-partition bytes from the Delta log (`get_add_actions` — no S3 LIST, no scan) and always records `max_partition_bytes` on the schema for observability. When the largest partition is over the budget it records a `repartition_pending` target on the schema: the next finer tier (md5 count grows, numerical size shrinks, datetime `month` → `week` → `day` → `hour`).
+- **Rewrite.** On the next run, a pre-extraction activity streams the live Delta table one record-batch at a time, recomputes `_ph_partition_key` under the finer scheme, and writes a sibling temp table. It then does a crash-safe swap: delete live → server-side copy temp → verify row count → delete temp. Memory is bounded by batch size, independent of partition size. Temp stays the source of truth until the swap is verified, so a worker death at any point loses wasted compute, never data.
+- **Safety.** The repartition is the sole writer (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), so it needs no new locking. A repartition failure never fails the sync — it's swallowed, retried on a later run, and capped at `MAX_REPARTITION_ATTEMPTS` (3) consecutive failures before it gives up and alerts.
+
+Tuning and gating:
+
+- Gated by the `data-warehouse-auto-repartition` feature flag plus a 24h per-table cooldown. The flag can be released to a single schema (`schema_id = <id>`) before rolling out by team/org/project.
+- The budget is tunable via the `DATA_WAREHOUSE_TARGET_PARTITION_BYTES` setting (default ~1 GB at-rest → ~20 GB worst-case merge, under the 29 GB pod limit with headroom).
+- CDC tables are excluded for now.
+
+Observability: `warehouse_repartition_flagged` / `started` / `completed` / `failed` / `skipped` PostHog events (with full team/schema/source/table context, before→after scheme, sizes, durations, and trigger reason) plus `DELTA_REPARTITION_*` Prometheus metrics.
+
+The existing admin repartition action now stages a `repartition_pending` target and triggers this cheap in-place path (no reset, no source re-pull) instead of a reset + resync.
+
## How to resync
When we resync a table, we do so from a k8s pod. We have the ability to disable billing for a sync via this method meaning that a user won't be charged for us repartitioning their data.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index ea933a6682cd..e8590bd2f6c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -72,6 +72,10 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
ImportDataActivityInputs,
import_data_activity_sync,
)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (
+ RepartitionActivityInputs,
+ maybe_repartition_table_activity,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
LOGGER = get_logger(__name__)
@@ -397,6 +401,29 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
update_inputs.status = ExternalDataJob.Status.BILLING_LIMIT_REACHED
return
+ # Pre-extraction, in-place repartition of any table flagged on a prior run. Runs here — sole
+ # writer, lock held, before the merge — so the subsequent merge uses the memory-safe layout.
+ # A no-op unless a repartition is pending; never fails the sync (errors are swallowed).
+ if job_id is not None:
+ try:
+ await workflow.execute_activity(
+ maybe_repartition_table_activity,
+ RepartitionActivityInputs(
+ team_id=inputs.team_id,
+ schema_id=str(inputs.external_data_schema_id),
+ job_id=str(job_id),
+ source_id=str(inputs.external_data_source_id),
+ ),
+ start_to_close_timeout=dt.timedelta(hours=6),
+ heartbeat_timeout=dt.timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ except Exception:
+ workflow.logger.warning(
+ "Repartition activity failed; continuing with sync on existing layout",
+ extra={"schema_id": str(inputs.external_data_schema_id)},
+ )
+
job_inputs = ImportDataActivityInputs(
team_id=inputs.team_id,
run_id=job_id,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 6fc95830fe0e..99c90c62aaef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
@@ -411,3 +411,15 @@ async def run_post_load_operations(
logger.debug("Syncing revenue analytics views if needed")
await database_sync_to_async_pool(sync_revenue_analytics_views)(schema, source)
+
+ # Measure partition sizes and flag the table for an in-place repartition if a partition has grown
+ # past the memory-safe budget. CDC tables are excluded for now (their companion-table semantics
+ # need separate validation). Detection never raises — it must not break post-load.
+ if not is_cdc_companion and schema.sync_type != ExternalDataSchema.SyncType.CDC:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition_controller import (
+ maybe_flag_for_repartition,
+ )
+
+ delta_table = await delta_table_helper.get_delta_table()
+ if delta_table is not None:
+ await maybe_flag_for_repartition(schema, source, job, delta_table, logger)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
index 67102c01e232..3e012b3abc91 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
@@ -195,6 +195,14 @@ class DeltaTableHelper:
folder_path = await database_sync_to_async_pool(self._job.folder_path)()
return f"{settings.BUCKET_URL}/{folder_path}/{normalized_resource_name}"
+ async def get_table_uri(self) -> str:
+ """Public accessor for the live Delta table S3 URI (used by the in-place repartitioner)."""
+ return await self._get_delta_table_uri()
+
+ def get_storage_options(self) -> dict[str, str]:
+ """Public accessor for the delta-rs storage options (used by the in-place repartitioner)."""
+ return self._get_credentials()
+
async def _evolve_delta_schema(self, schema: pa.Schema) -> deltalake.DeltaTable:
delta_table = await self.get_delta_table()
if delta_table is None:
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.py
new file mode 100644
index 000000000000..6b3694cc33b4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py
@@ -0,0 +1,484 @@
+"""In-place, streaming repartitioning of a DeltaLake table.
+
+Incremental syncs merge new rows into a Delta table partition-by-partition, but delta-rs reads the
+*whole* target partition into worker memory to do it. Once a single partition grows past ~1.5 GB
+at-rest it OOMs the worker. The historical fix was a reset + full resync that re-pulls every row from
+the source. This module instead repartitions the data **already in S3**, streaming one record-batch
+at a time, so it never re-extracts from the source and never materialises an oversized partition.
+
+The rewrite is a pure map (recompute `_ph_partition_key` per row under a finer scheme) into a sibling
+temp table, followed by a crash-safe swap. The live table is never mutated until a fully-built temp
+table exists, and temp stays the source of truth until the swap is verified — so a worker death at any
+point loses at most wasted compute, never data. See the "Repartitioning" section in
+`products/warehouse_sources/backend/temporal/data_imports/README.md`.
+"""
+
+from __future__ import annotations
+
+import math
+import asyncio
+import dataclasses
+from collections import defaultdict
+from typing import TYPE_CHECKING, Any
+
+import pyarrow as pa
+import deltalake as deltalake
+from structlog.types import FilteringBoundLogger
+
+from products.data_warehouse.backend.facade.api import aget_s3_client
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (
+ _realign_decimal_buffers,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ PartitionFormat,
+ PartitionMode,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (
+ append_partition_key_to_table,
+)
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (
+ DeltaTableHelper,
+ )
+
+# Coarse → fine. A datetime table that's OOMing steps one tier finer each repartition cycle.
+DATETIME_FORMAT_TIERS: list[PartitionFormat] = ["month", "week", "day", "hour"]
+
+# Rows per streamed record-batch. Bounds the repartition's peak memory independent of partition size.
+DEFAULT_REPARTITION_BATCH_SIZE = 50_000
+
+TEMP_URI_SUFFIX = "__repartitioned"
+
+
+class RepartitionUnpartitionableError(Exception):
+ """The table has no column suitable for partitioning — repartition is skipped, not retried."""
+
+
[email protected](frozen=True)
+class RepartitionTarget:
+ """The partition scheme to rewrite a table into. `partition_mode=None` means auto-detect."""
+
+ partition_keys: list[str]
+ trigger_reason: str
+ partition_mode: PartitionMode | None = None
+ partition_format: PartitionFormat | None = None
+ partition_count: int | None = None
+ partition_size: int | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return dataclasses.asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> RepartitionTarget:
+ fields = {f.name for f in dataclasses.fields(cls)}
+ return cls(**{k: v for k, v in data.items() if k in fields})
+
+
+def measure_partition_bytes(delta_table: deltalake.DeltaTable) -> dict[str | None, int]:
+ """At-rest bytes per partition, read from the Delta log (no S3 LIST, no data scan).
+
+ Unpartitioned tables collapse to a single `None` bucket. Keyed by the `_ph_partition_key` value.
+ """
+ actions = delta_table.get_add_actions(flatten=True)
+ columns = actions.schema.names
+ sizes = actions.column("size_bytes").to_pylist()
+
+ partition_column = f"partition.{PARTITION_KEY}"
+ keys: list[str | None]
+ if partition_column in columns:
+ keys = list(actions.column(partition_column).to_pylist())
+ else:
+ keys = [None] * len(sizes)
+
+ totals: dict[str | None, int] = defaultdict(int)
+ for key, size in zip(keys, sizes):
+ totals[key] += size or 0
+ return dict(totals)
+
+
+def _table_row_count(delta_table: deltalake.DeltaTable) -> int:
+ """Total rows from the Delta log's per-file `num_records` (metadata only, no scan)."""
+ actions = delta_table.get_add_actions(flatten=True)
+ if "num_records" not in actions.schema.names:
+ # Fall back to a metadata-only count if the stat is unavailable.
+ return delta_table.to_pyarrow_dataset().count_rows()
+ return sum(n or 0 for n in actions.column("num_records").to_pylist())
+
+
+def select_repartition_target(
+ schema: ExternalDataSchema,
+ partition_bytes: dict[str | None, int],
+ target_partition_bytes: int,
+) -> tuple[RepartitionTarget | None, str]:
+ """Pick the next finer partition scheme, returning (target, reason).
+
+ Computes the target directly from measured bytes so one repartition lands under budget rather
+ than stepping blindly: md5 grows the bucket count, numerical shrinks the row-size, datetime steps
+ one format tier finer. When no target is chosen the reason explains why (reported in metrics so a
+ skipped table is diagnosable): `within_budget`, `datetime_at_finest_tier`, `numerical_cannot_shrink`,
+ `numerical_no_size`, or `unpartitionable_no_keys`. A chosen target carries reason `selected`.
+ """
+ if not partition_bytes:
+ return None, "no_partitions"
+
+ max_bytes = max(partition_bytes.values())
+ if max_bytes <= target_partition_bytes:
+ return None, "within_budget"
+
+ total_bytes = sum(partition_bytes.values())
+ mode = schema.partition_mode
+ keys = schema.partitioning_keys or schema.primary_key_columns or []
+
+ if mode == "md5":
+ current = schema.partition_count or len(partition_bytes) or 1
+ new_count = max(current + 1, math.ceil(total_bytes / target_partition_bytes))
+ return RepartitionTarget(
+ partition_keys=keys, trigger_reason="", partition_mode="md5", partition_count=new_count
+ ), "selected"
+
+ if mode == "numerical":
+ current_size = schema.partition_size
+ if not current_size:
+ return None, "numerical_no_size"
+ new_size = max(1, math.floor(current_size * target_partition_bytes / max_bytes))
+ if new_size >= current_size:
+ return None, "numerical_cannot_shrink"
+ return RepartitionTarget(
+ partition_keys=keys, trigger_reason="", partition_mode="numerical", partition_size=new_size
+ ), "selected"
+
+ if mode == "datetime":
+ current_format: PartitionFormat = schema.partition_format or "month"
+ try:
+ next_index = DATETIME_FORMAT_TIERS.index(current_format) + 1
+ except ValueError:
+ next_index = 1
+ if next_index >= len(DATETIME_FORMAT_TIERS):
+ # Already at the finest tier (hour) — can't go finer. Caller alerts.
+ return None, "datetime_at_finest_tier"
+ return RepartitionTarget(
+ partition_keys=keys,
+ trigger_reason="",
+ partition_mode="datetime",
+ partition_format=DATETIME_FORMAT_TIERS[next_index],
+ ), "selected"
+
+ # Unpartitioned but over budget: attempt to enable partitioning via auto-detection. Needs keys.
+ if not keys:
+ return None, "unpartitionable_no_keys"
+ return RepartitionTarget(partition_keys=keys, trigger_reason="", partition_mode=None), "selected"
+
+
+def _read_next_batch(reader: pa.RecordBatchReader) -> pa.RecordBatch | None:
+ try:
+ return reader.read_next_batch()
+ except StopIteration:
+ return None
+
+
+async def _rewrite_into_temp(
+ *,
+ old_delta: deltalake.DeltaTable,
+ temp_uri: str,
+ storage_options: dict[str, str],
+ target: RepartitionTarget,
+ batch_size: int,
+ logger: FilteringBoundLogger,
+) -> tuple[int, RepartitionTarget]:
+ """Stream the live table into a fresh temp table under the new partition scheme.
+
+ Returns (rows_written, resolved_target). The first batch resolves any auto-detected mode/format/
+ keys so every subsequent batch is bucketed identically (a per-batch auto-detect could disagree).
+ """
+ dataset = await asyncio.to_thread(old_delta.to_pyarrow_dataset)
+ reader = await asyncio.to_thread(lambda: dataset.scanner(batch_size=batch_size).to_reader())
+
+ resolved: RepartitionTarget | None = None
+ rows_written = 0
+
+ while True:
+ batch = await asyncio.to_thread(_read_next_batch, reader)
+ if batch is None:
+ break
+
+ table = pa.Table.from_batches([batch])
+ if table.num_rows == 0:
+ continue
+ if PARTITION_KEY in table.column_names:
+ table = table.drop([PARTITION_KEY])
+
+ result = append_partition_key_to_table(
+ table=table,
+ partition_count=target.partition_count,
+ partition_size=target.partition_size,
+ partition_keys=target.partition_keys,
+ partition_mode=resolved.partition_mode if resolved else target.partition_mode,
+ partition_format=resolved.partition_format if resolved else target.partition_format,
+ logger=logger,
+ )
+ if result is None:
+ raise RepartitionUnpartitionableError(f"No supported partition mode for keys={target.partition_keys}")
+
+ partitioned_table, used_mode, used_format, used_keys = result
+ if resolved is None:
+ resolved = dataclasses.replace(
+ target,
+ partition_mode=used_mode,
+ partition_format=used_format,
+ partition_keys=used_keys,
+ )
+
+ partitioned_table = _realign_decimal_buffers(partitioned_table)
+
+ await asyncio.to_thread(
+ deltalake.write_deltalake,
+ temp_uri,
+ partitioned_table,
+ partition_by=PARTITION_KEY,
+ mode="append",
+ schema_mode="merge",
+ storage_options=storage_options,
+ )
+ rows_written += partitioned_table.num_rows
+
+ if resolved is None:
+ # Empty source table — nothing to rewrite.
+ resolved = target
+ return rows_written, resolved
+
+
+async def repartition_table_in_place(
+ helper: DeltaTableHelper,
+ schema: ExternalDataSchema,
+ target: RepartitionTarget,
+ logger: FilteringBoundLogger,
+ *,
+ batch_size: int = DEFAULT_REPARTITION_BATCH_SIZE,
+) -> dict[str, Any]:
+ """Rewrite the schema's Delta table under `target`'s finer partition scheme, in place, from S3.
+
+ Memory is bounded by `batch_size`; the source is never re-read. Crash-safe via the
+ `repartition_swap` marker (resume re-drives the swap from the intact temp table). On success,
+ persists the new partition settings and clears the controller markers. Returns a stats dict for
+ observability. Raises `RepartitionUnpartitionableError` (terminal) if no partition mode applies.
+ """
+ live_uri = await helper.get_table_uri()
+ temp_uri = f"{live_uri}{TEMP_URI_SUFFIX}"
+ storage_options = helper.get_storage_options()
+
+ # Resume path: a prior attempt already built + validated temp and recorded the swap marker.
+ swap = schema.repartition_swap
+ resuming = bool(swap and swap.get("state") == "ready")
+
+ old_delta = await helper.get_delta_table()
+ if old_delta is None:
+ # Live table missing. If a swap was already in progress (temp built + marker recorded), an
+ # interrupted prior run may have deleted live *after* recording the marker but before copying
+ # temp back. temp is the durable source of truth in that window, so resume the swap from it
+ # rather than skipping — a plain skip would strand the markers forever (every later run hits
+ # this same early return) and let the next sync bootstrap an empty table over the lost data.
+ if resuming:
+ return await _resume_swap_with_missing_live(
+ helper=helper,
+ schema=schema,
+ target=target,
+ temp_uri=temp_uri,
+ live_uri=live_uri,
+ storage_options=storage_options,
+ logger=logger,
+ )
+ await logger.ainfo("repartition: no delta table, skipping", schema_id=str(schema.id))
+ return {"outcome": "skipped", "reason": "no_delta_table"}
+
+ partition_bytes = await asyncio.to_thread(measure_partition_bytes, old_delta)
+ max_partition_bytes_before = max(partition_bytes.values()) if partition_bytes else 0
+ total_table_bytes = sum(partition_bytes.values())
+ old_row_count = await asyncio.to_thread(_table_row_count, old_delta)
+
+ before = {
+ "partition_mode": schema.partition_mode,
+ "partition_format": schema.partition_format,
+ "partition_count": schema.partition_count,
+ "partition_size": schema.partition_size,
+ }
+
+ if resuming:
+ resolved = target
+ rows_written = old_row_count
+ await logger.ainfo("repartition: resuming from swap marker", 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:
+ if await s3._exists(temp_uri):
+ await s3._rm(temp_uri, recursive=True)
+
+ rows_written, resolved = await _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=temp_uri,
+ storage_options=storage_options,
+ target=target,
+ batch_size=batch_size,
+ logger=logger,
+ )
+
+ # Validate before any destructive action — temp must hold every row.
+ new_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=temp_uri, storage_options=storage_options)
+ new_row_count = await asyncio.to_thread(_table_row_count, new_delta)
+ if new_row_count != old_row_count:
+ raise ValueError(
+ f"repartition row-count mismatch: temp={new_row_count} live={old_row_count} "
+ f"(schema_id={schema.id}) — refusing to swap"
+ )
+
+ # Marker makes the swap idempotent: temp stays the source of truth until it's confirmed live.
+ await asyncio.to_thread(
+ schema.set_repartition_swap, {"state": "ready", "temp_uri": temp_uri, "live_uri": live_uri}
+ )
+
+ # Swap (idempotent): replace live with a server-side copy of temp, verify, then drop temp. temp
+ # holds the full re-bucketed dataset, so deleting live is safe — temp is the new source of truth.
+ await _swap_temp_into_live(
+ temp_uri=temp_uri,
+ live_uri=live_uri,
+ storage_options=storage_options,
+ expected_rows=old_row_count,
+ )
+
+ # Persist the new scheme and clear controller state. set_partitioning_enabled saves + pops overrides.
+ await asyncio.to_thread(
+ schema.set_partitioning_enabled,
+ resolved.partition_keys,
+ resolved.partition_count,
+ resolved.partition_size,
+ resolved.partition_mode,
+ resolved.partition_format,
+ )
+ await asyncio.to_thread(schema.clear_repartition_swap)
+ await asyncio.to_thread(schema.clear_repartition_pending)
+ await asyncio.to_thread(schema.stamp_last_repartition_at)
+
+ # The cached delta-table object points at the pre-swap files; drop it so callers re-read live.
+ helper.get_delta_table.cache_clear()
+
+ await logger.ainfo(
+ "repartition: completed",
+ schema_id=str(schema.id),
+ rows=rows_written,
+ mode=f"{before['partition_mode']}->{resolved.partition_mode}",
+ format=f"{before['partition_format']}->{resolved.partition_format}",
+ count=f"{before['partition_count']}->{resolved.partition_count}",
+ size=f"{before['partition_size']}->{resolved.partition_size}",
+ )
+
+ return {
+ "outcome": "completed",
+ "row_count": rows_written,
+ "max_partition_bytes_before": max_partition_bytes_before,
+ "total_table_bytes": total_table_bytes,
+ "partition_mode_before": before["partition_mode"],
+ "partition_mode_after": resolved.partition_mode,
+ "partition_format_before": before["partition_format"],
+ "partition_format_after": resolved.partition_format,
+ "partition_count_before": before["partition_count"],
+ "partition_count_after": resolved.partition_count,
+ "partition_size_before": before["partition_size"],
+ "partition_size_after": resolved.partition_size,
+ }
+
+
+async def _resume_swap_with_missing_live(
+ *,
+ helper: DeltaTableHelper,
+ schema: ExternalDataSchema,
+ target: RepartitionTarget,
+ temp_uri: str,
+ live_uri: str,
+ storage_options: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ """Finish a swap whose live table was already deleted by an interrupted prior run.
+
+ Entered only when the swap marker is set but live is gone — i.e. a previous run crashed inside
+ `_swap_temp_into_live` after deleting live and before the copy completed. temp is the durable
+ source of truth, so its own row count is the swap's expectation. If temp is *also* gone there is
+ nothing left to recover (both folders lost): clear the markers and skip so the next sync rebuilds.
+ """
+ async with aget_s3_client() as s3:
+ temp_present = await s3._exists(temp_uri)
+ 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))
+ return {"outcome": "skipped", "reason": "no_delta_table"}
+
+ await logger.ainfo("repartition: live missing mid-swap, resuming from temp", 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)
+
+ await _swap_temp_into_live(
+ temp_uri=temp_uri,
+ live_uri=live_uri,
+ storage_options=storage_options,
+ expected_rows=expected_rows,
+ )
+
+ await asyncio.to_thread(
+ schema.set_partitioning_enabled,
+ target.partition_keys,
+ target.partition_count,
+ target.partition_size,
+ target.partition_mode,
+ target.partition_format,
+ )
+ await asyncio.to_thread(schema.clear_repartition_swap)
+ await asyncio.to_thread(schema.clear_repartition_pending)
+ 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)
+ return {"outcome": "completed", "row_count": expected_rows, "recovered": True}
+
+
+async def _swap_temp_into_live(
+ *,
+ temp_uri: str,
+ live_uri: str,
+ storage_options: dict[str, str],
+ expected_rows: int,
+) -> None:
+ """Atomically-enough replace `live_uri` with the contents of `temp_uri`.
+
+ Crash-safe ordering: delete live → server-side copy temp → live → verify → delete temp. Until
+ temp is deleted it remains the durable source of truth, so any retry simply re-runs this whole
+ function (Delta uses relative paths in `_delta_log`, so a copied folder is a valid table).
+
+ Files are copied one at a time preserving their path relative to temp — a single recursive
+ `copy(prefix, prefix)` trips over directory-marker objects on S3-compatible stores.
+ """
+ temp_prefix = temp_uri.replace("s3://", "").rstrip("/")
+ async with aget_s3_client() as s3:
+ if await s3._exists(temp_uri):
+ if await s3._exists(live_uri):
+ await s3._rm(live_uri, recursive=True)
+ files = await s3._find(temp_uri)
+ for f in files:
+ rel = f[len(temp_prefix) :]
+ await s3._copy(f"s3://{f.lstrip('/')}", f"{live_uri}{rel}")
+
+ # Verify the live copy is a valid Delta table with the expected row count before dropping temp.
+ live_delta = await asyncio.to_thread(deltalake.DeltaTable, table_uri=live_uri, storage_options=storage_options)
+ live_rows = await asyncio.to_thread(_table_row_count, live_delta)
+ if live_rows != expected_rows:
+ raise ValueError(f"repartition swap verification failed: live={live_rows} expected={expected_rows}")
+
+ async with aget_s3_client() as s3:
+ # Delete the temp files explicitly (a recursive prefix delete can leave directory-marker
+ # objects behind on some S3-compatible stores), then a best-effort recursive sweep.
+ temp_files = await s3._find(temp_uri)
+ if temp_files:
+ await s3._rm([f"s3://{f.lstrip('/')}" for f in temp_files])
+ if await s3._exists(temp_uri):
+ await s3._rm(temp_uri, recursive=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.py
new file mode 100644
index 000000000000..9b44d97183b9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.py
@@ -0,0 +1,191 @@
+"""Detection + gating for the automated in-place repartition controller.
+
+Measures per-partition size after a sync (cheap — read from the Delta log) and, when a table's
+largest partition outgrows the memory-safe budget, records a `repartition_pending` target on the
+schema. The next run's pre-extraction activity performs the rewrite (see `repartition.py` and
+`workflow_activities/repartition_table.py`). Everything is observable via PostHog events.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import TYPE_CHECKING, Any
+
+from django.conf import settings
+from django.utils import timezone
+
+import deltalake as deltalake
+import posthoganalytics
+from dateutil import parser
+from structlog.types import FilteringBoundLogger
+
+from posthog.exceptions_capture import capture_exception
+from posthog.utils import get_machine_id
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
+ measure_partition_bytes,
+ select_repartition_target,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
+ DELTA_REPARTITION_SKIP_TOTAL,
+)
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+WAREHOUSE_AUTO_REPARTITION_FLAG = "data-warehouse-auto-repartition"
+
+# Don't repartition the same table more than once a day — the budget has headroom, so a table that
+# trips repeatedly should converge over a few daily cycles, not thrash every sync.
+REPARTITION_COOLDOWN_SECONDS = 24 * 60 * 60
+
+# Give up (and alert) after this many consecutive failed attempts so a permanently-failing table
+# doesn't re-attempt the rewrite on every sync forever.
+MAX_REPARTITION_ATTEMPTS = 3
+
+
+def target_partition_bytes() -> int:
+ return int(getattr(settings, "DATA_WAREHOUSE_TARGET_PARTITION_BYTES", 1_000_000_000))
+
+
+def is_auto_repartition_enabled(schema: ExternalDataSchema) -> bool:
+ """Evaluate the rollout flag for this schema.
+
+ `schema_id`, `team_id`, and `source_type` are passed as person properties so the flag can be
+ released to a single table — set a release condition `schema_id = <id>` to dogfood the controller
+ on one schema before rolling out by team/org/project.
+ """
+ from posthog.models import Team
+
+ try:
+ team = Team.objects.only("uuid", "organization_id").get(id=schema.team_id)
+ except Team.DoesNotExist:
+ return False
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ WAREHOUSE_AUTO_REPARTITION_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ person_properties={
+ "schema_id": str(schema.id),
+ "team_id": str(schema.team_id),
+ "source_type": schema.source.source_type,
+ },
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+
+def base_event_props(schema: ExternalDataSchema, source: ExternalDataSource, job_id: str | None) -> dict[str, Any]:
+ return {
+ "team_id": schema.team_id,
+ "schema_id": str(schema.id),
+ "source_id": str(schema.source_id),
+ "source_type": source.source_type,
+ "resource_name": schema.name,
+ "job_id": str(job_id) if job_id else None,
+ "partition_mode": schema.partition_mode,
+ "partition_format": schema.partition_format,
+ "partition_count": schema.partition_count,
+ "partition_size": schema.partition_size,
+ }
+
+
+def capture_repartition_event(event: str, props: dict[str, Any]) -> None:
+ posthoganalytics.capture(distinct_id=get_machine_id(), event=event, properties=props)
+
+
+def _cooldown_active(schema: ExternalDataSchema) -> bool:
+ last = schema.last_repartition_at
+ if not last:
+ return False
+ try:
+ last_dt = parser.parse(last)
+ except (ValueError, TypeError):
+ return False
+ return (timezone.now() - last_dt).total_seconds() < REPARTITION_COOLDOWN_SECONDS
+
+
+async def maybe_flag_for_repartition(
+ schema: ExternalDataSchema,
+ source: ExternalDataSource,
+ job: ExternalDataJob,
+ delta_table: deltalake.DeltaTable,
+ logger: FilteringBoundLogger,
+) -> None:
+ """Measure partition sizes and, if over budget, record a `repartition_pending` target.
+
+ Always records `max_partition_bytes` for observability (even when the controller is disabled or in
+ cooldown). Setting the pending target is gated by the feature flag; the rewrite itself happens on
+ the next run. Never raises — detection must not break post-load.
+ """
+ try:
+ partition_bytes = await asyncio.to_thread(measure_partition_bytes, delta_table)
+ if not partition_bytes:
+ return
+
+ max_bytes = max(partition_bytes.values())
+ await asyncio.to_thread(schema.record_partition_measurement, max_bytes)
+
+ budget = target_partition_bytes()
+ if max_bytes <= budget:
+ return
+
+ if not await asyncio.to_thread(is_auto_repartition_enabled, schema):
+ await logger.adebug("repartition: over budget but controller disabled", schema_id=str(schema.id))
+ return
+
+ if schema.repartition_pending is not None:
+ return # Already queued for the next run.
+
+ if _cooldown_active(schema):
+ await logger.adebug("repartition: over budget but in cooldown", schema_id=str(schema.id))
+ return
+
+ target, reason = select_repartition_target(schema, partition_bytes, budget)
+ if target is None:
+ # Over budget but nothing finer to do (datetime at hour, numerical can't shrink, unpartitionable).
+ # `reason` is reported on the metric + event so a skipped table is diagnosable.
+ DELTA_REPARTITION_SKIP_TOTAL.labels(team_id=str(schema.team_id), reason=reason).inc()
+ props = base_event_props(schema, source, str(job.id))
+ props.update({"max_partition_bytes_before": max_bytes, "reason": reason})
+ await asyncio.to_thread(capture_repartition_event, "warehouse_repartition_skipped", props)
+ capture_exception(Exception(f"Repartition needed but skipped for schema {schema.id}: {reason}"))
+ return
+
+ pending = {**target.to_dict(), "trigger_reason": "proactive_threshold", "attempts": 0}
+ await asyncio.to_thread(schema.set_repartition_pending, pending)
+
+ props = base_event_props(schema, source, str(job.id))
+ props.update(
+ {
+ "max_partition_bytes_before": max_bytes,
+ "trigger_reason": "proactive_threshold",
+ "partition_mode_after": target.partition_mode,
+ "partition_format_after": target.partition_format,
+ "partition_count_after": target.partition_count,
+ "partition_size_after": target.partition_size,
+ }
+ )
+ await asyncio.to_thread(capture_repartition_event, "warehouse_repartition_flagged", props)
+ await logger.ainfo(
+ "repartition: flagged for next run",
+ schema_id=str(schema.id),
+ max_partition_bytes=max_bytes,
+ target_mode=target.partition_mode,
+ )
+ 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))
+ capture_exception(e)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py
new file mode 100644
index 000000000000..4b6ce2cd8f18
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py
@@ -0,0 +1,335 @@
+import asyncio
+import datetime
+from types import SimpleNamespace
+
+import pytest
+from unittest.mock import AsyncMock, Mock, patch
+
+import pyarrow as pa
+import deltalake as deltalake
+import structlog
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline import (
+ repartition as repartition_module,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
+ RepartitionTarget,
+ _rewrite_into_temp,
+ measure_partition_bytes,
+ repartition_table_in_place,
+ select_repartition_target,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (
+ append_partition_key_to_table,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+def _schema(**kwargs):
+ defaults = {
+ "partition_mode": None,
+ "partition_count": None,
+ "partition_size": None,
+ "partition_format": None,
+ "partitioning_keys": None,
+ "primary_key_columns": None,
+ }
+ defaults.update(kwargs)
+ return SimpleNamespace(**defaults)
+
+
+def _write_month_partitioned(path: str, rows: list[tuple[int, datetime.datetime]]) -> deltalake.DeltaTable:
+ table = pa.table(
+ {
+ "id": pa.array([r[0] for r in rows], type=pa.int64()),
+ "created_at": pa.array([r[1] for r in rows], type=pa.timestamp("us")),
+ }
+ )
+ result = append_partition_key_to_table(table, None, None, ["created_at"], "datetime", "month", logger)
+ assert result is not None
+ partitioned, *_ = result
+ deltalake.write_deltalake(path, partitioned, partition_by=PARTITION_KEY)
+ return deltalake.DeltaTable(path)
+
+
+class TestSelectRepartitionTarget:
+ @parameterized.expand(
+ [
+ # (name, schema_kwargs, partition_bytes, target_bytes, expect)
+ (
+ "md5_over_budget_grows_count",
+ {"partition_mode": "md5", "partition_count": 4, "partitioning_keys": ["id"]},
+ {"0": 5000, "1": 5000},
+ 1000,
+ {"partition_mode": "md5", "partition_count": 10},
+ ),
+ (
+ "md5_within_budget_noop",
+ {"partition_mode": "md5", "partition_count": 4},
+ {"0": 500, "1": 400},
+ 1000,
+ None,
+ ),
+ (
+ "numerical_over_budget_shrinks_size",
+ {"partition_mode": "numerical", "partition_size": 1000, "partitioning_keys": ["id"]},
+ {"0": 5000},
+ 1000,
+ {"partition_mode": "numerical", "partition_size": 200},
+ ),
+ (
+ "datetime_month_steps_to_week",
+ {"partition_mode": "datetime", "partition_format": "month", "partitioning_keys": ["created_at"]},
+ {"2024-01": 5000},
+ 1000,
+ {"partition_mode": "datetime", "partition_format": "week"},
+ ),
+ (
+ "datetime_day_steps_to_hour",
+ {"partition_mode": "datetime", "partition_format": "day", "partitioning_keys": ["created_at"]},
+ {"2024-01-01": 5000},
+ 1000,
+ {"partition_mode": "datetime", "partition_format": "hour"},
+ ),
+ (
+ "datetime_hour_cannot_go_finer",
+ {"partition_mode": "datetime", "partition_format": "hour", "partitioning_keys": ["created_at"]},
+ {"2024-01-01T00": 5000},
+ 1000,
+ None,
+ ),
+ (
+ "unpartitioned_with_keys_enables_partitioning",
+ {"partition_mode": None, "primary_key_columns": ["id"]},
+ {None: 5000},
+ 1000,
+ {"partition_mode": None, "partition_keys": ["id"]},
+ ),
+ (
+ "unpartitioned_without_keys_noop",
+ {"partition_mode": None},
+ {None: 5000},
+ 1000,
+ None,
+ ),
+ ]
+ )
+ def test_select(self, _name, schema_kwargs, partition_bytes, target_bytes, expect):
+ target, reason = select_repartition_target(_schema(**schema_kwargs), partition_bytes, target_bytes)
+ if expect is None:
+ assert target is None
+ # A None target must carry a diagnostic reason (reported in metrics), never "selected".
+ assert reason and reason != "selected"
+ return
+ assert target is not None
+ assert reason == "selected"
+ for key, value in expect.items():
+ assert getattr(target, key) == value
+
+ @parameterized.expand(
+ [
+ ("datetime_hour", {"partition_mode": "datetime", "partition_format": "hour"}, "datetime_at_finest_tier"),
+ ("unpartitionable", {"partition_mode": None}, "unpartitionable_no_keys"),
+ ]
+ )
+ def test_skip_reason_is_specific(self, _name, schema_kwargs, expected_reason):
+ # The skip reason is what an operator reads off the metric/event to know why a table over budget
+ # was left alone — it must be the specific cause, not a generic placeholder.
+ _target, reason = select_repartition_target(_schema(**schema_kwargs), {"a": 5000}, 1000)
+ assert reason == expected_reason
+
+ def test_md5_count_strictly_grows_even_when_formula_below_current(self):
+ # Largest partition is over budget but total/target rounds below the current count: the count
+ # must still grow, or the repartition would be a no-op that never relieves the pressure.
+ target, _reason = select_repartition_target(
+ _schema(partition_mode="md5", partition_count=8),
+ {"0": 5000, "1": 100},
+ 1000,
+ )
+ assert target is not None
+ assert target.partition_count == 9
+
+
+class TestMeasurePartitionBytes:
+ def test_partitioned_groups_by_partition_key(self, tmp_path):
+ delta = _write_month_partitioned(
+ str(tmp_path / "t"),
+ [
+ (1, datetime.datetime(2024, 1, 5)),
+ (2, datetime.datetime(2024, 1, 9)),
+ (3, datetime.datetime(2024, 2, 2)),
+ ],
+ )
+ sizes = measure_partition_bytes(delta)
+ assert set(sizes.keys()) == {"2024-01", "2024-02"}
+ assert all(v > 0 for v in sizes.values())
+
+ def test_unpartitioned_collapses_to_single_bucket(self, tmp_path):
+ table = pa.table({"id": pa.array([1, 2, 3], type=pa.int64())})
+ deltalake.write_deltalake(str(tmp_path / "u"), table)
+ sizes = measure_partition_bytes(deltalake.DeltaTable(str(tmp_path / "u")))
+ assert list(sizes.keys()) == [None]
+ assert sizes[None] > 0
+
+
+class TestRewriteIntoTemp:
+ def test_rebuckets_finer_preserving_all_rows(self, tmp_path):
+ rows = [
+ (1, datetime.datetime(2024, 1, 5)),
+ (2, datetime.datetime(2024, 1, 20)),
+ (3, datetime.datetime(2024, 1, 25)),
+ (4, datetime.datetime(2024, 2, 2)),
+ ]
+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)
+ temp_uri = str(tmp_path / "tmp")
+
+ rows_written, resolved = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="test",
+ partition_mode="datetime",
+ partition_format="day",
+ ),
+ batch_size=2, # force multiple streamed batches
+ logger=logger,
+ )
+ )
+
+ assert rows_written == len(rows)
+ assert resolved.partition_mode == "datetime"
+ assert resolved.partition_format == "day"
+
+ new_delta = deltalake.DeltaTable(temp_uri)
+ # Every row survives, none duplicated.
+ new_sizes = measure_partition_bytes(new_delta)
+ assert sum(1 for _ in new_sizes) >= 4 # one partition per distinct day, finer than 2 months
+
+ new_table = new_delta.to_pyarrow_table().sort_by("id")
+ assert new_table.column("id").to_pylist() == [1, 2, 3, 4]
+ # Partition keys recomputed under the new (day) scheme — values are %Y-%m-%d.
+ for key in new_sizes:
+ assert key is not None and len(key) == len("2024-01-05")
+
+ def test_resolved_mode_is_fixed_by_first_batch(self, tmp_path):
+ # Auto-detect (mode=None) must resolve once and apply to every batch, not re-detect per batch.
+ rows = [(i, datetime.datetime(2024, 1, (i % 27) + 1)) for i in range(10)]
+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)
+ temp_uri = str(tmp_path / "tmp")
+
+ rows_written, resolved = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=temp_uri,
+ storage_options={},
+ target=RepartitionTarget(partition_keys=["created_at"], trigger_reason="test", partition_mode=None),
+ batch_size=3,
+ logger=logger,
+ )
+ )
+ assert rows_written == len(rows)
+ # created_at is a timestamp column named like a datetime key → auto-detects datetime mode.
+ assert resolved.partition_mode == "datetime"
+
+
+class _FakeS3CM:
+ """Minimal async-context-manager stand-in for `aget_s3_client()`."""
+
+ def __init__(self, s3):
+ self._s3 = s3
+
+ async def __aenter__(self):
+ return self._s3
+
+ async def __aexit__(self, *exc):
+ return False
+
+
+class TestResumeSwapWithMissingLive:
+ """An interrupted swap can delete the live table before copying temp back. On resume the live
+ table is gone, so `get_delta_table()` returns None — but the swap marker is still set and temp is
+ intact. The repartition must finish the swap from temp, not take the `no_delta_table` early return
+ (which would strand the markers forever and let the next sync bootstrap an empty table)."""
+
+ def _helper(self):
+ return SimpleNamespace(
+ get_table_uri=AsyncMock(return_value="s3://bucket/live"),
+ get_storage_options=Mock(return_value={}),
+ get_delta_table=AsyncMock(return_value=None),
+ )
+
+ def test_routes_to_recovery_when_swap_marker_present(self):
+ helper = self._helper()
+ schema = _schema(
+ id="s1",
+ repartition_swap={
+ "state": "ready",
+ "temp_uri": "s3://bucket/live__repartitioned",
+ "live_uri": "s3://bucket/live",
+ },
+ )
+ target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="resume")
+
+ recovered = {"outcome": "completed", "recovered": True}
+ with patch.object(
+ repartition_module, "_resume_swap_with_missing_live", new=AsyncMock(return_value=recovered)
+ ) as recover:
+ result = asyncio.run(repartition_table_in_place(helper=helper, schema=schema, target=target, logger=logger))
+
+ recover.assert_awaited_once()
+ assert result == recovered
+
+ def test_skips_when_no_swap_marker(self):
+ helper = self._helper()
+ schema = _schema(id="s1", repartition_swap=None)
+ target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="resume")
+
+ with patch.object(repartition_module, "_resume_swap_with_missing_live", new=AsyncMock()) as recover:
+ result = asyncio.run(repartition_table_in_place(helper=helper, schema=schema, target=target, logger=logger))
+
+ recover.assert_not_awaited()
+ assert result == {"outcome": "skipped", "reason": "no_delta_table"}
+
+ def test_recovery_clears_markers_and_skips_when_temp_also_gone(self):
+ # Both live and temp lost: nothing left to recover, so clear the markers and skip rather than
+ # loop on a swap that can never complete.
+ helper = self._helper()
+ schema = _schema(id="s1", clear_repartition_swap=Mock(), clear_repartition_pending=Mock())
+ target = RepartitionTarget(partition_keys=["created_at"], trigger_reason="resume")
+ s3 = SimpleNamespace(_exists=AsyncMock(return_value=False))
+
+ with patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(s3)):
+ result = asyncio.run(
+ repartition_module._resume_swap_with_missing_live(
+ helper=helper,
+ schema=schema,
+ target=target,
+ temp_uri="s3://bucket/live__repartitioned",
+ live_uri="s3://bucket/live",
+ storage_options={},
+ logger=logger,
+ )
+ )
+
+ schema.clear_repartition_swap.assert_called_once()
+ schema.clear_repartition_pending.assert_called_once()
+ assert result == {"outcome": "skipped", "reason": "no_delta_table"}
+
+
+ "data",
+ [
+ {"partition_keys": ["a"], "trigger_reason": "admin", "partition_mode": "md5", "partition_count": 7},
+ {"partition_keys": ["a", "b"], "trigger_reason": "x", "partition_mode": None},
+ ],
+)
+def test_repartition_target_dict_roundtrip_ignores_extra_keys(data):
+ # from_dict must tolerate extra keys (attempts/trigger metadata) stored alongside the target.
+ restored = RepartitionTarget.from_dict({**data, "attempts": 3, "junk": "ignored"})
+ assert restored.to_dict() == {**RepartitionTarget(**data).to_dict()}
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
new file mode 100644
index 000000000000..0e51e491bda8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
@@ -0,0 +1,249 @@
+import uuid
+import datetime
+import tempfile
+
+import pytest
+from unittest.mock import AsyncMock, patch
+
+import pyarrow as pa
+import deltalake as deltalake
+import structlog
+from asgiref.sync import async_to_sync
+from temporalio.testing import ActivityEnvironment
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline import repartition_controller as ctrl
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
+ RepartitionUnpartitionableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import repartition_table
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (
+ RepartitionActivityInputs,
+ maybe_repartition_table_activity,
+)
+
+logger = structlog.get_logger(__name__)
+
+# transaction=True: the detection path and the (thread-pool) sync activity write to the DB from worker
+# threads with their own connections, which can't see an atomic TestCase's uncommitted rows.
+pytestmark = pytest.mark.django_db(transaction=True)
+
+
+def _write_partitioned_delta(path: str, buckets: list[str]) -> deltalake.DeltaTable:
+ table = pa.table(
+ {
+ "id": pa.array(list(range(len(buckets))), type=pa.int64()),
+ PARTITION_KEY: pa.array(buckets, type=pa.string()),
+ }
+ )
+ deltalake.write_deltalake(path, table, partition_by=PARTITION_KEY)
+ return deltalake.DeltaTable(path)
+
+
+def _write_unpartitioned_delta(path: str) -> deltalake.DeltaTable:
+ deltalake.write_deltalake(path, pa.table({"id": pa.array([1, 2, 3], type=pa.int64())}))
+ return deltalake.DeltaTable(path)
+
+
+def _make_schema(team, sync_type_config: dict) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=team, source_type="Stripe"
+ )
+ return ExternalDataSchema.objects.create(name="repart", team=team, source=source, sync_type_config=sync_type_config)
+
+
+def _make_job(team, schema: ExternalDataSchema) -> ExternalDataJob:
+ return ExternalDataJob.objects.create(
+ team=team, pipeline=schema.source, schema=schema, status=ExternalDataJob.Status.RUNNING, rows_synced=0
+ )
+
+
+class TestRepartitionDetection:
+ def _detect(self, team, schema: ExternalDataSchema, delta: deltalake.DeltaTable) -> None:
+ async_to_sync(ctrl.maybe_flag_for_repartition)(schema, schema.source, _make_job(team, schema), delta, logger)
+
+ def test_flags_over_budget_table_with_target(self, team):
+ # An md5 table whose largest partition exceeds the budget must be queued with a grown count, and
+ # the measured size recorded — this is the core trigger that stops OOMs before the next merge.
+ schema = _make_schema(
+ team,
+ {"partitioning_enabled": True, "partition_mode": "md5", "partition_count": 2, "partitioning_keys": ["id"]},
+ )
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_partitioned_delta(f"{d}/t", ["0", "0", "1", "1"])
+ with (
+ 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") as capture,
+ ):
+ self._detect(team, schema, delta)
+
+ schema.refresh_from_db()
+ assert schema.max_partition_bytes is not None and schema.max_partition_bytes > 0
+ pending = schema.repartition_pending
+ assert pending is not None
+ assert pending["partition_mode"] == "md5"
+ assert pending["partition_count"] > 2
+ assert pending["trigger_reason"] == "proactive_threshold"
+ assert capture.call_args.args[0] == "warehouse_repartition_flagged"
+
+ def test_within_budget_records_size_but_does_not_flag(self, team):
+ schema = _make_schema(team, {"partitioning_enabled": True, "partition_mode": "md5", "partition_count": 2})
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_partitioned_delta(f"{d}/t", ["0", "1"])
+ with (
+ patch.object(ctrl, "target_partition_bytes", return_value=10**12),
+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),
+ ):
+ self._detect(team, schema, delta)
+
+ schema.refresh_from_db()
+ assert schema.max_partition_bytes is not None
+ assert schema.repartition_pending is None
+
+ def test_disabled_flag_records_size_but_does_not_flag(self, team):
+ schema = _make_schema(team, {"partitioning_enabled": True, "partition_mode": "md5", "partition_count": 2})
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_partitioned_delta(f"{d}/t", ["0", "1"])
+ with (
+ patch.object(ctrl, "target_partition_bytes", return_value=1),
+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=False),
+ ):
+ self._detect(team, schema, delta)
+
+ schema.refresh_from_db()
+ assert schema.max_partition_bytes is not None
+ assert schema.repartition_pending is None
+
+ def test_cooldown_blocks_flagging(self, team):
+ recent = datetime.datetime.now(datetime.UTC).isoformat()
+ schema = _make_schema(
+ team,
+ {
+ "partitioning_enabled": True,
+ "partition_mode": "md5",
+ "partition_count": 2,
+ "partitioning_keys": ["id"],
+ "last_repartition_at": recent,
+ },
+ )
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_partitioned_delta(f"{d}/t", ["0", "1"])
+ with (
+ patch.object(ctrl, "target_partition_bytes", return_value=1),
+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),
+ ):
+ self._detect(team, schema, delta)
+
+ schema.refresh_from_db()
+ assert schema.repartition_pending is None
+
+ def test_unpartitionable_over_budget_skips_with_reason(self, team):
+ # An unpartitioned table with no usable key can't be repartitioned — we must surface the specific
+ # reason (so a human is alerted) rather than silently flag a target that would fail.
+ schema = _make_schema(team, {})
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_unpartitioned_delta(f"{d}/u")
+ with (
+ 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") as capture,
+ ):
+ self._detect(team, schema, delta)
+
+ schema.refresh_from_db()
+ assert schema.repartition_pending is None
+ assert capture.call_args.args[0] == "warehouse_repartition_skipped"
+ assert capture.call_args.args[1]["reason"] == "unpartitionable_no_keys"
+
+
+class TestRepartitionActivity:
+ def _inputs(self, team, schema: ExternalDataSchema) -> RepartitionActivityInputs:
+ job = _make_job(team, schema)
+ return RepartitionActivityInputs(
+ team_id=team.id, schema_id=str(schema.id), job_id=str(job.id), source_id=str(schema.source_id)
+ )
+
+ def _run(self, inputs: RepartitionActivityInputs, repartition_mock: AsyncMock):
+ # Mock HeartbeaterSync (no real heartbeat thread / activity context needed) and the primitive,
+ # so these exercise the activity's decision + bookkeeping, not the rewrite itself.
+ with (
+ patch.object(repartition_table, "HeartbeaterSync"),
+ patch.object(repartition_table, "repartition_table_in_place", new=repartition_mock),
+ patch.object(repartition_table, "capture_repartition_event") as capture,
+ ):
+ # ActivityEnvironment.run is synchronous for a sync activity — call it directly.
+ ActivityEnvironment().run(maybe_repartition_table_activity, inputs)
+ return capture
+
+ def test_noop_when_nothing_pending(self, team):
+ inputs = self._inputs(team, _make_schema(team, {}))
+ mocked = AsyncMock()
+ self._run(inputs, mocked)
+ mocked.assert_not_called()
+
+ def test_success_emits_completed(self, team):
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "test",
+ "attempts": 0,
+ }
+ )
+ mocked = AsyncMock(return_value={"outcome": "completed", "row_count": 6, "partition_mode_after": "md5"})
+ capture = self._run(self._inputs(team, schema), mocked)
+ 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_unpartitionable_clears_pending(self, team):
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {"partition_mode": None, "partition_keys": [], "trigger_reason": "test", "attempts": 0}
+ )
+ mocked = AsyncMock(side_effect=RepartitionUnpartitionableError("no keys"))
+ capture = self._run(self._inputs(team, schema), mocked)
+ schema.refresh_from_db()
+ assert schema.repartition_pending is None
+ assert "warehouse_repartition_skipped" in [c.args[0] for c in capture.call_args_list]
+
+ def test_failure_increments_attempts_without_clearing(self, team):
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "test",
+ "attempts": 0,
+ }
+ )
+ mocked = AsyncMock(side_effect=ValueError("boom"))
+ capture = self._run(self._inputs(team, schema), mocked)
+ schema.refresh_from_db()
+ assert schema.repartition_pending is not None
+ assert schema.repartition_pending["attempts"] == 1
+ assert "warehouse_repartition_failed" in [c.args[0] for c in capture.call_args_list]
+
+ def test_failure_gives_up_after_max_attempts(self, team):
+ schema = _make_schema(team, {})
+ # One short of the cap — this attempt pushes it over and the pending flag is cleared.
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "test",
+ "attempts": ctrl.MAX_REPARTITION_ATTEMPTS - 1,
+ }
+ )
+ self._run(self._inputs(team, schema), AsyncMock(side_effect=ValueError("boom")))
+ schema.refresh_from_db()
+ assert schema.repartition_pending is None
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 4b20a6550710..94488cf2408b 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
@@ -31,3 +31,25 @@ POST_LOAD_DURATION_SECONDS = Histogram(
labelnames=["operation"],
buckets=(0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),
)
+
+# TODO: the `team_id`/`schema_id` labels below are high cardinality — keep only for the gated rollout
+# so we can debug per-team behaviour, then drop them before fully rolling out (per-team diagnosability
+# is also covered by the `warehouse_repartition_*` capture events).
+DELTA_REPARTITION_DURATION_SECONDS = Histogram(
+ "warehouse_load_delta_repartition_duration_seconds",
+ "Duration of an in-place Delta table repartition",
+ labelnames=["team_id", "schema_id"],
+ buckets=(1.0, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0, 3600.0),
+)
+
+DELTA_REPARTITION_TOTAL = Counter(
+ "warehouse_load_delta_repartition_total",
+ "Total in-place Delta repartitions by outcome",
+ labelnames=["team_id", "outcome"],
+)
+
+DELTA_REPARTITION_SKIP_TOTAL = Counter(
+ "warehouse_load_delta_repartition_skip_total",
+ "Tables over the partition-size budget that the controller skipped, by reason",
+ labelnames=["team_id", "reason"],
+)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/settings.py b/products/warehouse_sources/backend/temporal/data_imports/settings.py
index e72f36398ae0..cd65898cccfb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/settings.py
@@ -27,6 +27,9 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
check_pipeline_version_activity,
release_v3_pipeline_lock_activity,
)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import (
+ maybe_repartition_table_activity,
+)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.sync_new_schemas import (
sync_new_schemas_activity,
)
@@ -57,4 +60,5 @@ ACTIVITIES = [
check_pipeline_version_activity,
acquire_v3_pipeline_lock_activity,
release_v3_pipeline_lock_activity,
+ maybe_repartition_table_activity,
]
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
new file mode 100644
index 000000000000..171211bbf00b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
@@ -0,0 +1,174 @@
+"""Pre-extraction Temporal activity that performs a pending in-place repartition.
+
+Runs inside `ExternalDataJobWorkflow` after the pipeline lock is held and before extraction, so it is
+the sole writer for the schema (the schedule's OnlyOne overlap policy + the v3 pipeline lock guarantee
+no concurrent sync). Acting on a pending target *before* the merge means the merge that follows in the
+same run uses the new, memory-safe layout. A repartition failure never fails the workflow — the sync
+just proceeds on the old layout (status quo) and the table is retried on a later run.
+"""
+
+import time
+import dataclasses
+from typing import Any
+
+from django.db import close_old_connections
+
+import structlog
+from asgiref.sync import async_to_sync
+from structlog.contextvars import bind_contextvars
+from temporalio import activity
+
+from posthog.exceptions_capture import capture_exception
+from posthog.temporal.common.heartbeat_sync import HeartbeaterSync
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (
+ DeltaTableHelper,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
+ RepartitionTarget,
+ RepartitionUnpartitionableError,
+ repartition_table_in_place,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition_controller import (
+ MAX_REPARTITION_ATTEMPTS,
+ base_event_props,
+ capture_repartition_event,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
+ DELTA_REPARTITION_DURATION_SECONDS,
+ DELTA_REPARTITION_TOTAL,
+)
+
+LOGGER = structlog.get_logger(__name__)
+
+
+class RepartitionActivityInputs:
+ team_id: int
+ schema_id: str
+ job_id: str
+ source_id: str
+
+
+def _target_from_schema(schema: ExternalDataSchema) -> RepartitionTarget:
+ """Fallback target reconstructed from the schema's current settings (resume-with-no-pending)."""
+ return RepartitionTarget(
+ partition_keys=schema.partitioning_keys or schema.primary_key_columns or [],
+ trigger_reason="resume",
+ partition_mode=schema.partition_mode,
+ partition_format=schema.partition_format,
+ partition_count=schema.partition_count,
+ partition_size=schema.partition_size,
+ )
+
+
+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;
+ # the async repartition primitive is driven via async_to_sync, like import_data_activity_sync.
+ bind_contextvars(team_id=inputs.team_id, schema_id=inputs.schema_id)
+ logger = LOGGER.bind()
+ close_old_connections()
+
+ try:
+ schema = ExternalDataSchema.objects.select_related("source").get(id=inputs.schema_id)
+ except ExternalDataSchema.DoesNotExist:
+ return
+
+ pending = schema.repartition_pending
+ swap = schema.repartition_swap
+ if pending is None and swap is None:
+ return # Nothing queued — cheap common path.
+
+ try:
+ job = ExternalDataJob.objects.get(id=inputs.job_id)
+ except ExternalDataJob.DoesNotExist:
+ 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)
+ logger.info("repartition: starting", trigger_reason=trigger_reason)
+
+ start = time.monotonic()
+ try:
+ # HeartbeaterSync heartbeats on a background thread while the (possibly long) rewrite streams,
+ # and on worker shutdown, so Temporal reschedules us instead of timing the activity out.
+ with HeartbeaterSync(logger=logger):
+ result = async_to_sync(repartition_table_in_place)(
+ helper=helper,
+ schema=schema,
+ target=target,
+ logger=logger,
+ )
+ except RepartitionUnpartitionableError as e:
+ # Terminal: the table can't be partitioned. Clear the flag so we don't retry every run.
+ schema.refresh_from_db(fields=["sync_type_config"])
+ schema.clear_repartition_pending()
+ props = base_event_props(schema, schema.source, inputs.job_id)
+ props.update({"trigger_reason": trigger_reason, "reason": str(e)})
+ capture_repartition_event("warehouse_repartition_skipped", props)
+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="skipped").inc()
+ capture_exception(e)
+ return
+ except Exception as e:
+ # Do NOT re-raise: a repartition failure must not block the sync — the table is retried on a
+ # later run, on the old layout in the meantime.
+ _handle_failure(inputs, schema, pending, trigger_reason, e)
+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()
+ return
+
+ duration = time.monotonic() - start
+ DELTA_REPARTITION_DURATION_SECONDS.labels(team_id=str(inputs.team_id), schema_id=inputs.schema_id).observe(duration)
+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome=result.get("outcome", "completed")).inc()
+
+ props = base_event_props(schema, schema.source, inputs.job_id)
+ props["trigger_reason"] = trigger_reason
+ props["duration_seconds"] = duration
+ props.update({k: v for k, v in result.items() if k != "outcome"})
+ event = (
+ "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)
+
+
+def _handle_failure(
+ inputs: RepartitionActivityInputs,
+ schema: ExternalDataSchema,
+ pending: dict[str, Any] | None,
+ trigger_reason: str,
+ error: Exception,
+) -> None:
+ """Record a failed attempt; give up (and clear the flag) after MAX_REPARTITION_ATTEMPTS."""
+ schema.refresh_from_db(fields=["sync_type_config"])
+ pending = schema.repartition_pending or pending or {}
+ attempts = int(pending.get("attempts", 0)) + 1
+
+ props = base_event_props(schema, schema.source, inputs.job_id)
+ props.update(
+ {
+ "trigger_reason": trigger_reason,
+ "attempts": attempts,
+ "error_type": type(error).__name__,
+ "error_message": str(error)[:1000],
+ }
+ )
+
+ if attempts >= MAX_REPARTITION_ATTEMPTS:
+ props["final"] = True
+ schema.clear_repartition_pending()
+ schema.clear_repartition_swap()
+ else:
+ updated = {**pending, "attempts": attempts}
+ schema.set_repartition_pending(updated)
+
+ capture_repartition_event("warehouse_repartition_failed", props)
+ capture_exception(error)
diff --git a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py
index 0982149f36d1..906ac983775b 100644
--- a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py
+++ b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py
@@ -89,31 +89,26 @@ class TestExternalDataSchemaAdmin(BaseTest):
"md5",
{"partition_mode": "md5", "partition_count": 72, "partitioning_enabled": True},
{"partition_count": "10"},
- "partition_count_override",
- 10,
- # The operator's count must land on *_override so it survives the bundled reset;
- # writing partition_count directly would be wiped and the source would re-derive its own value.
- {"partition_count": 72},
+ {"partition_mode": "md5", "partition_count": 10, "partition_size": None, "partition_format": None},
),
(
"numerical",
{"partition_mode": "numerical", "partition_size": 1_000_000, "partitioning_enabled": True},
{"partition_size": "5000000"},
- "partition_size_override",
- 5_000_000,
- {},
+ {"partition_mode": "numerical", "partition_size": 5_000_000, "partition_count": None},
),
]
)
- def test_repartition_writes_override_key(
+ def test_repartition_queues_pending_target_without_reset(
self,
_mode: str,
initial_config: dict,
post_data: dict,
- override_key: str,
- expected_value: int,
- extra_config_assertions: dict,
+ expected_pending: dict,
) -> None:
+ # In-place repartition writes a `repartition_pending` target consumed by the next run's
+ # pre-extraction activity — it must NOT set reset_pipeline (no source re-pull) or stage *_override
+ # keys (those drove the old reset-resync path).
schema = self._schema(sync_type_config=initial_config)
with (
@@ -125,11 +120,15 @@ class TestExternalDataSchemaAdmin(BaseTest):
assert response.status_code == 302
schema.refresh_from_db()
- assert schema.sync_type_config[override_key] == expected_value
- assert schema.sync_type_config["reset_pipeline"] is True
- for key, value in extra_config_assertions.items():
- assert schema.sync_type_config[key] == value
+ pending = schema.sync_type_config["repartition_pending"]
+ assert pending["trigger_reason"] == "admin"
+ assert pending["attempts"] == 0
+ for key, value in expected_pending.items():
+ assert pending[key] == value
+ assert "reset_pipeline" not in schema.sync_type_config
+ assert "partition_count_override" not in schema.sync_type_config
mock_start.assert_called_once()
+ assert mock_start.call_args.args[2].billable is False
@parameterized.expand(
[
@@ -138,8 +137,8 @@ class TestExternalDataSchemaAdmin(BaseTest):
{"partition_mode": "md5", "partition_count": 30, "partitioning_enabled": True},
{"partition_mode": "datetime", "partitioning_keys": "action_date", "partition_format": "month"},
{
- "partition_mode_override": "datetime",
- "partitioning_keys_override": ["action_date"],
+ "partition_mode": "datetime",
+ "partition_keys": ["action_date"],
"partition_format": "month",
},
),
@@ -148,9 +147,9 @@ class TestExternalDataSchemaAdmin(BaseTest):
{"partition_mode": "md5", "partition_count": 30, "partitioning_enabled": True},
{"partition_mode": "numerical", "partitioning_keys": "id", "partition_size": "1000000"},
{
- "partition_mode_override": "numerical",
- "partitioning_keys_override": ["id"],
- "partition_size_override": 1_000_000,
+ "partition_mode": "numerical",
+ "partition_keys": ["id"],
+ "partition_size": 1_000_000,
},
),
(
@@ -158,15 +157,14 @@ class TestExternalDataSchemaAdmin(BaseTest):
{"partition_mode": "datetime", "partition_format": "month", "partitioning_enabled": True},
{"partition_mode": "md5", "partition_count": "10", "partitioning_keys": "record_id,action_date"},
{
- "partition_mode_override": "md5",
- "partition_count_override": 10,
- "partitioning_keys_override": ["record_id", "action_date"],
+ "partition_mode": "md5",
+ "partition_count": 10,
+ "partition_keys": ["record_id", "action_date"],
},
),
(
- # md5 without keys must explicitly clear a stale partitioning_keys_override left by a
- # prior datetime attempt — otherwise it survives the reset and md5 hashes the wrong
- # column instead of falling back to the table's primary keys.
+ # md5 without keys must not carry a stale partitioning_keys_override from a prior datetime
+ # attempt — otherwise md5 would hash the wrong column instead of the table's primary keys.
"to_md5_clears_stale_keys",
{
"partition_mode": "datetime",
@@ -176,9 +174,9 @@ class TestExternalDataSchemaAdmin(BaseTest):
},
{"partition_mode": "md5", "partition_count": "10"},
{
- "partition_mode_override": "md5",
- "partition_count_override": 10,
- "partitioning_keys_override": None,
+ "partition_mode": "md5",
+ "partition_count": 10,
+ "partition_keys": [],
},
),
(
@@ -187,14 +185,13 @@ class TestExternalDataSchemaAdmin(BaseTest):
{"partition_mode": "datetime", "partition_format": "month", "partitioning_enabled": True},
{"partition_mode": "md5", "partition_count": "10", "partitioning_keys": ["record_id", "action_date"]},
{
- "partition_mode_override": "md5",
- "partition_count_override": 10,
- "partitioning_keys_override": ["record_id", "action_date"],
+ "partition_mode": "md5",
+ "partition_count": 10,
+ "partition_keys": ["record_id", "action_date"],
},
),
(
- # In-place format change with the mode unchanged — the merged "repartition" case
- # that used to be a separate action. No keys needed since the mode isn't changing.
+ # In-place format change with the mode unchanged — keys carry over from the existing scheme.
"datetime_in_place_format_change",
{
"partition_mode": "datetime",
@@ -204,18 +201,19 @@ class TestExternalDataSchemaAdmin(BaseTest):
},
{"partition_mode": "datetime", "partition_format": "day"},
{
- "partition_mode_override": "datetime",
+ "partition_mode": "datetime",
"partition_format": "day",
+ "partition_keys": ["action_date"],
},
),
]
)
- def test_change_partition_mode_writes_overrides(
+ def test_change_partition_mode_queues_pending_target(
self,
_name: str,
initial_config: dict,
post_data: dict,
- expected_config: dict,
+ expected_pending: dict,
) -> None:
schema = self._schema(sync_type_config=initial_config)
@@ -228,10 +226,12 @@ class TestExternalDataSchemaAdmin(BaseTest):
assert response.status_code == 302
schema.refresh_from_db()
- for key, value in expected_config.items():
- assert schema.sync_type_config[key] == value
- assert schema.sync_type_config["reset_pipeline"] is True
- # The resync must be non-billable — the operator's reset shouldn't charge the customer.
+ pending = schema.sync_type_config["repartition_pending"]
+ for key, value in expected_pending.items():
+ assert pending[key] == value
+ assert pending["trigger_reason"] == "admin"
+ # In-place: no source re-pull, and the run must be non-billable.
+ assert "reset_pipeline" not in schema.sync_type_config
mock_start.assert_called_once()
assert mock_start.call_args.args[2].billable is False
@@ -261,8 +261,8 @@ class TestExternalDataSchemaAdmin(BaseTest):
assert response.status_code == 302
schema.refresh_from_db()
- # Invalid input must not stage an override or kick off a resync.
- assert "partition_mode_override" not in schema.sync_type_config
+ # Invalid input must not queue a repartition or kick off a run.
+ assert "repartition_pending" not in schema.sync_type_config
assert "reset_pipeline" not in schema.sync_type_config
mock_start.assert_not_called()