:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add a command to stage coarser repartitions (#110071)
Daniel RCa37f9b4bb137
diff --git a/products/warehouse_sources/backend/management/commands/stage_warehouse_repartition.py b/products/warehouse_sources/backend/management/commands/stage_warehouse_repartition.pynew file mode 100644index 000000000000..6b722cb28040--- /dev/null+++ b/products/warehouse_sources/backend/management/commands/stage_warehouse_repartition.py@@ -0,0 +1,155 @@+"""Stage in-place rewrites of datetime-partitioned warehouse tables into a coarser tier.++This is for tables that were split finer than their data needs. The automatic coarsening path only+merges a table when every resulting partition fits half the repartition budget, which keeps the+controller from splitting and merging the same table in turns. A table that was split from just over+the budget can never meet that, so `stage_warehouse_coarsening` refuses it. Here the operator names+the tier, and the only limit is the budget itself.++What it does NOT do is rewrite anything. It stages the same `repartition_pending` target as the admin+page, and each table's next scheduled sync runs the rewrite before it extracts. The rewrite holds that+sync until it finishes, which takes hours for the largest tables, so stage big tables off-peak. A+scheduled full refresh skips the repartition step, so the target then waits for the sync after it.++Unlike the admin page, it measures the live table first and refuses a target whose largest partition+would be over the budget. A partition over the budget is what makes a merge run out of memory, and the+rewrite has no size check of its own for an operator's target.++Dry run by default; pass --execute to stage.+"""++from typing import Any+from uuid import UUID++from django.core.management.base import BaseCommand, CommandError++import deltalake++from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import (+ build_delta_table_uri,+ delta_storage_options,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (+ DATETIME_FORMAT_TIERS,+ measure_partition_bytes,+ simulate_datetime_coarsening,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (+ target_partition_bytes,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionFormat+++class Command(BaseCommand):+ help = "Stage in-place rewrites of datetime-partitioned schemas into a coarser tier (dry run by default)."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("--execute", action="store_true", help="Stage the rewrites (default is a dry run).")+ parser.add_argument(+ "--schema-id", type=UUID, action="append", default=None, help="Schema to rewrite. Repeatable."+ )+ parser.add_argument(+ "--format",+ choices=DATETIME_FORMAT_TIERS,+ required=True,+ help="Tier to rewrite every named schema into. It must be coarser than the schema's current tier.",+ )++ def _measure(self, schema: ExternalDataSchema) -> dict[str | None, int] | None:+ uri = build_delta_table_uri(schema.folder_path(), schema.resolved_s3_folder_name or schema.name)+ storage_options = delta_storage_options()+ if not deltalake.DeltaTable.is_deltatable(uri, storage_options=storage_options):+ return None+ return measure_partition_bytes(deltalake.DeltaTable(uri, storage_options=storage_options))++ def _refusal_before_measuring(self, schema: ExternalDataSchema, target_format: PartitionFormat) -> str | None:+ if not schema.should_sync:+ return "not_syncing: no sync will run the rewrite"+ if schema.sync_type == ExternalDataSchema.SyncType.CDC:+ return "cdc: repartitioning excludes CDC schemas"+ if (+ schema.repartition_pending is not None+ or schema.repartition_swap is not None+ or schema.delta_revive_required is not None+ ):+ return "busy: a rewrite or a corruption revive is already queued"+ if schema.partition_mode != "datetime":+ return f"not_datetime: partition mode is {schema.partition_mode}"+ current_format = schema.partition_format or "month"+ if DATETIME_FORMAT_TIERS.index(target_format) >= DATETIME_FORMAT_TIERS.index(current_format):+ return f"not_coarser: the table is at {current_format}"+ if not schema.partitioning_keys:+ return "no_partition_key: the schema records no partitioning key to rebuild from"+ return None++ def _plan(+ self, schema: ExternalDataSchema, target_format: PartitionFormat, budget: int+ ) -> tuple[str, dict[str, Any] | None]:+ """The report text for one schema, and the target to stage when the rewrite is safe."""+ refusal = self._refusal_before_measuring(schema, target_format)+ if refusal is not None:+ return f"REFUSED {refusal}", None++ try:+ partition_bytes = self._measure(schema)+ except Exception as e:+ # A bucket or credential error on one table must not end the batch with no report for the rest.+ return f"REFUSED read_failed: {type(e).__name__}: {e}", None+ if not partition_bytes:+ return "REFUSED no_delta_table: nothing on disk to rewrite", None+ simulated = simulate_datetime_coarsening(partition_bytes, schema.partition_format or "month", target_format)+ if simulated is None:+ return "REFUSED unparseable_partition_keys: a partition key is not a date in the current tier", None++ layout = (+ f"{len(partition_bytes):,} -> {len(simulated):,} partitions, "+ f"largest {max(partition_bytes.values()):,} -> {max(simulated.values()):,} bytes"+ )+ if max(simulated.values()) > budget:+ return f"REFUSED over_budget: {layout}", None+ return f"OK {layout}", {+ "partition_mode": "datetime",+ "partition_format": target_format,+ "partition_count": None,+ "partition_size": None,+ "partition_keys": schema.partitioning_keys,+ "trigger_reason": "admin",+ "attempts": 0,+ }++ def handle(self, *args: Any, **options: Any) -> None:+ schema_ids = [str(schema_id) for schema_id in options["schema_id"] or []]+ if not schema_ids:+ raise CommandError("Name at least one schema with --schema-id")+ target_format: PartitionFormat = options["format"]+ budget = target_partition_bytes()++ schemas = {+ str(schema.id): schema+ for schema in ExternalDataSchema.objects.filter(id__in=schema_ids, deleted=False).select_related("source")+ }+ self.stdout.write(f"Target tier: {target_format}. Budget per partition: {budget:,} bytes\n")+ # Every table is planned before anything is written, so a crash part way through stages nothing.+ targets: dict[str, dict[str, Any]] = {}+ for schema_id in schema_ids:+ schema = schemas.get(schema_id)+ if schema is None:+ self.stdout.write(f"{schema_id} REFUSED not_found: no such schema")+ continue+ verdict, target = self._plan(schema, target_format, budget)+ self.stdout.write(f"{schema_id} team={schema.team_id} {schema.name} {verdict}")+ if target is not None:+ targets[schema_id] = target++ if not options["execute"]:+ self.stdout.write(self.style.WARNING(f"\nDry run. Re-run with --execute to stage {len(targets)}."))+ return++ for schema_id, target in targets.items():+ schemas[schema_id].set_repartition_pending(target)+ self.stdout.write(+ self.style.SUCCESS(+ f"\nStaged {len(targets)}. Each rewrites on its next sync that is not a full refresh, and holds that sync until done."+ )+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex c1b77c1f87d1..eec6d7c0be3d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -54,6 +54,7 @@ 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. Coarsening has its own flag, `data-warehouse-auto-coarsen`, released the same way.- **Repairing the existing backlog.** The automatic coarsening path will not reach a table that keeps recording OOM occurrences, and the tables most in need of coarsening are exactly the ones the unreliable OOM signal keeps firing on. `./manage.py stage_warehouse_coarsening` is the way in: it nominates tables by setting a `coarsen_requested` marker, and the next sync evaluates them. A nomination skips the policy gates (rollout flag, OOM history, layout age, minimum partition count) because an operator has made that call, but never the safety check: the controller still measures the live layout and refuses any target that would not fit the budget, so a nomination can only ever be a no-op. Nominated rewrites report `trigger_reason=coarsening_requested`. Dry run by default, `--limit` defaults low, and it is worth keeping low: a rewrite blocks that table's sync for as long as it runs, which is seconds for small tables and hours for the largest.+- **Putting back a table that was split too fine.** A table split from just over the budget cannot pass the coarsening safety check, because its coarser partitions are larger than half the budget. `./manage.py stage_warehouse_repartition --schema-id <id> --format <tier>` covers that case for datetime tables. The operator names the coarser tier, and the command measures the live table and refuses a target whose largest partition would be over the full budget. It then stages the same `repartition_pending` target as the admin page (`trigger_reason=admin`), and the next scheduled sync runs the rewrite. A scheduled full refresh skips the repartition step, so the target then waits for the sync after it. `--schema-id` repeats, and it is a dry run by default.- The budget is tunable via the `DATA_WAREHOUSE_TARGET_PARTITION_BYTES` setting (default ~0.5 GB at-rest → ~10 GB worst-case merge). Worker pods are multi-tenant, so the budget leaves headroom for concurrent merges under the 29 GB pod limit rather than sizing to a single merge.- The OOM-history override is tunable via `DATA_WAREHOUSE_REPARTITION_OOM_THRESHOLD` (default 3) and `DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS` (default 7). An OOM-triggered rewrite of an under-budget table steps one tier finer per cooldown cycle, converging as the (still-recorded) OOMs continue.- The split floor and the coarsening trigger are both derived from the budget rather than tuned separately (`COARSEN_TRIGGER_DIVISOR`), so the two directions stay consistent by construction.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.pyindex 6e9368aec32a..3d4630d9da5d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py@@ -678,7 +678,7 @@ _DATETIME_KEY_FORMATS: dict[PartitionFormat, str] = {# Coarser tiers each partition can merge into, coarsest first. Every tier here contains the finer one# whole, so a row's new bucket follows from its old key, except week into month: ISO weeks straddle# month boundaries, and how a week's bytes divide between two months is not recoverable from the key.-# That one is sized by upper bound instead (see `_simulate_datetime_coarsening`) rather than left+# That one is sized by upper bound instead (see `simulate_datetime_coarsening`) rather than left# unreachable, because the finer path's first step is month into week, so without it a table this# controller wrongly split could never be merged back._COARSER_DATETIME_TIERS: dict[PartitionFormat, tuple[PartitionFormat, ...]] = {@@ -718,7 +718,7 @@ def _merged_keys(parsed: datetime, current_format: PartitionFormat, new_format:return [parsed.strftime(_DATETIME_KEY_FORMATS[new_format])]-def _simulate_datetime_coarsening(+def simulate_datetime_coarsening(partition_bytes: dict[str | None, int],current_format: PartitionFormat,new_format: PartitionFormat,@@ -822,7 +822,7 @@ def select_coarsen_target(return None, "datetime_at_coarsest_tier"# Coarsest tier first: fewer, larger partitions is the goal, and the size ceiling is what stops it.for new_format in candidate_formats:- if acceptable(_simulate_datetime_coarsening(partition_bytes, current_format, new_format)):+ if acceptable(simulate_datetime_coarsening(partition_bytes, current_format, new_format)):return RepartitionTarget(partition_keys=keys,trigger_reason="",diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.pyindex bdd11652a03c..167d25875c24 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py@@ -492,7 +492,7 @@ class TestSelectCoarsenTarget:current = bucket_sizes(current_format)expected = bucket_sizes(new_format)- simulated = repartition_module._simulate_datetime_coarsening(current, current_format, new_format)+ simulated = repartition_module.simulate_datetime_coarsening(current, current_format, new_format)assert simulated == expected@@ -517,7 +517,7 @@ class TestSelectCoarsenTarget:return sizesreal = bucket_sizes("month")- simulated = repartition_module._simulate_datetime_coarsening(bucket_sizes("week"), "week", "month")+ simulated = repartition_module.simulate_datetime_coarsening(bucket_sizes("week"), "week", "month")assert simulated is not None# Every month the rewrite produces is accounted for, and never under-stated.diff --git a/products/warehouse_sources/backend/tests/management/test_stage_warehouse_repartition.py b/products/warehouse_sources/backend/tests/management/test_stage_warehouse_repartition.pynew file mode 100644index 000000000000..afb6e242bffd--- /dev/null+++ b/products/warehouse_sources/backend/tests/management/test_stage_warehouse_repartition.py@@ -0,0 +1,153 @@+import uuid+import tempfile+from io import StringIO+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command++import pyarrow as pa+import deltalake+from parameterized import parameterized++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.core.consts import PARTITION_KEY++_COMMAND_MODULE = "products.warehouse_sources.backend.management.commands.stage_warehouse_repartition"+_FITS = 10**12+_QUEUED = {"partition_mode": "datetime", "partition_format": "week", "partition_keys": ["created_at"]}+++class TestStageWarehouseRepartition(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ # Three hour partitions over two days, standing in for a table split from day to hour.+ self.table_uri = f"{self.enterContext(tempfile.TemporaryDirectory())}/swaps"+ hours = ["2026-09-28T10", "2026-09-28T11", "2026-09-29T10"]+ deltalake.write_deltalake(+ self.table_uri,+ pa.table({"id": list(range(len(hours))), PARTITION_KEY: hours}),+ partition_by=PARTITION_KEY,+ )+ self.enterContext(patch(f"{_COMMAND_MODULE}.build_delta_table_uri", return_value=self.table_uri))+ self.enterContext(patch(f"{_COMMAND_MODULE}.delta_storage_options", return_value={}))++ def _schema(self, config: dict[str, Any] | None = None, **fields: Any) -> ExternalDataSchema:+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ status="Completed",+ source_type="Postgres",+ )+ return ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source=source,+ name="swaps",+ **{"should_sync": True, "sync_type": ExternalDataSchema.SyncType.INCREMENTAL, **fields},+ sync_type_config={+ "partitioning_enabled": True,+ "partition_mode": "datetime",+ "partition_format": "hour",+ "partitioning_keys": ["created_at"],+ **(config or {}),+ },+ )++ def _run(self, schemas: list[ExternalDataSchema], *, budget: int = _FITS, **options: Any) -> str:+ out = StringIO()+ with patch(f"{_COMMAND_MODULE}.target_partition_bytes", return_value=budget):+ call_command(+ "stage_warehouse_repartition",+ stdout=out,+ schema_id=[str(schema.id) for schema in schemas],+ **{"format": "day", **options},+ )+ return out.getvalue()++ def test_dry_run_reports_the_layout_without_staging(self) -> None:+ # A staged rewrite holds the table's next sync for as long as it runs, so a preview must not+ # leave a target behind.+ schema = self._schema()++ output = self._run([schema])++ assert str(schema.id) in output+ assert "3 -> 2 partitions" in output+ schema.refresh_from_db()+ assert schema.repartition_pending is None++ def test_execute_stages_the_rewrite_the_next_sync_runs(self) -> None:+ # The refused schema rides along to show that one bad table does not stop the batch.+ schema = self._schema()+ hashed = self._schema({"partition_mode": "md5", "partition_count": 4})++ self._run([hashed, schema], execute=True)++ schema.refresh_from_db()+ hashed.refresh_from_db()+ assert schema.repartition_pending == {+ "partition_mode": "datetime",+ "partition_format": "day",+ "partition_count": None,+ "partition_size": None,+ "partition_keys": ["created_at"],+ "trigger_reason": "admin",+ "attempts": 0,+ }+ assert hashed.repartition_pending is None++ @parameterized.expand(+ [+ # A partition over the budget is what makes a merge run out of memory, and the rewrite+ # itself has no size check for an operator's target.+ ("over_budget", {}, {}, {"budget": 1}),+ # A second target would replace a rewrite that is queued or already in progress.+ ("busy", {"repartition_pending": _QUEUED}, {}, {}),+ ("busy", {"repartition_swap": {"state": "ready"}}, {}, {}),+ ("not_coarser", {"partition_format": "day"}, {}, {}),+ ("not_datetime", {"partition_mode": "md5", "partition_count": 4}, {}, {}),+ ("cdc", {}, {"sync_type": ExternalDataSchema.SyncType.CDC}, {}),+ # Only a sync runs the rewrite, so a target on a paused schema would wait forever.+ ("not_syncing", {}, {"should_sync": False}, {}),+ ("no_partition_key", {"partitioning_keys": []}, {}, {}),+ ]+ )+ def test_refuses_a_rewrite_it_cannot_stage_safely(+ self, reason: str, config: dict[str, Any], fields: dict[str, Any], run_options: dict[str, Any]+ ) -> None:+ schema = self._schema(config, **fields)+ pending_before = schema.repartition_pending++ output = self._run([schema], execute=True, **run_options)++ assert reason in output+ schema.refresh_from_db()+ assert schema.repartition_pending == pending_before++ def test_refuses_a_schema_with_no_table_on_disk(self) -> None:+ schema = self._schema()++ with patch(f"{_COMMAND_MODULE}.build_delta_table_uri", return_value=f"{self.table_uri}-missing"):+ output = self._run([schema], execute=True)++ assert "no_delta_table" in output+ schema.refresh_from_db()+ assert schema.repartition_pending is None++ def test_a_table_that_cannot_be_read_does_not_stop_the_batch(self) -> None:+ # One bucket error would otherwise end the run with a traceback and no report for the rest.+ unreadable = self._schema()+ readable = self._schema()++ with patch(f"{_COMMAND_MODULE}.delta_storage_options", side_effect=[OSError("access denied"), {}]):+ output = self._run([unreadable, readable], execute=True)++ assert "read_failed" in output+ unreadable.refresh_from_db()+ readable.refresh_from_db()+ assert unreadable.repartition_pending is None+ assert readable.repartition_pending is not None