:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): coarsen over-split tables, harden the OOM trigger (#76349)
Daniel RC81b70e077c5d
diff --git a/products/warehouse_sources/backend/management/commands/stage_warehouse_coarsening.py b/products/warehouse_sources/backend/management/commands/stage_warehouse_coarsening.pynew file mode 100644index 000000000000..ec05e9b2a5bb--- /dev/null+++ b/products/warehouse_sources/backend/management/commands/stage_warehouse_coarsening.py@@ -0,0 +1,126 @@+"""Nominate over-fragmented warehouse tables for the coarsening rewrite.++The automatic coarsening path only acts on tables that are clearly over-fragmented *and* clearly safe+to merge, and one of its conditions is no OOM history. That condition reads the same unreliable signal+that over-split most of these tables in the first place, so the backlog of already-damaged tables can+sit blocked indefinitely. This command is the operator's way in: it nominates tables, and the pipeline+still decides whether any coarser layout is actually safe.++What it does NOT do is rewrite anything. It sets a `coarsen_requested` marker on the schema; the next+sync's pre-extraction activity measures the live layout, picks a target that fits the memory budget (or+declines), and performs the rewrite under the pipeline lock with the existing crash-safe swap. A+nomination can therefore only ever be a no-op, never a rewrite into partitions too big to merge.++Rewrites are not free. Observed durations run from seconds for small tables to hours for the largest,+and the rewrite blocks that table's sync while it runs, so stage in small batches and prefer off-peak+for big tables. `--limit` caps the blast radius per invocation and defaults low on purpose.++Dry run by default; pass --execute to write the markers.+"""++from typing import Any++from django.core.management.base import BaseCommand, CommandError+from django.db.models import QuerySet+from django.utils import timezone++from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (+ min_splittable_partition_bytes,+)++# Datetime tiers fine enough to be worth reviewing. Coarser layouts are not over-fragmented by tier.+FINE_DATETIME_FORMATS = ("hour", "day", "week")+++class Command(BaseCommand):+ help = "Nominate over-fragmented external data schemas for the coarsening rewrite (dry run by default)."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("--execute", action="store_true", help="Write the markers (default is a dry run).")+ parser.add_argument(+ "--limit",+ type=int,+ default=25,+ help="Maximum schemas to nominate. Kept low because each rewrite blocks that table's sync.",+ )+ parser.add_argument(+ "--max-partition-bytes",+ type=int,+ default=None,+ help=(+ "Only consider schemas whose recorded largest partition is below this. "+ "Defaults to min_splittable_partition_bytes(), the same threshold the automatic path "+ "treats as over-fragmented, so the two cannot drift apart."+ ),+ )+ parser.add_argument("--team-id", type=int, default=None, help="Restrict to one team.")+ parser.add_argument("--source-type", type=str, default=None, help="Restrict to one source type.")+ parser.add_argument(+ "--schema-id",+ type=str,+ action="append",+ default=None,+ help="Nominate specific schemas by id. Repeatable, and skips the shape filters below.",+ )+ parser.add_argument(+ "--requested-by",+ type=str,+ default="stage_warehouse_coarsening",+ help="Recorded on the marker so a nomination can be traced back to whoever staged it.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ limit = options["limit"]+ if limit < 1:+ raise CommandError("--limit must be at least 1")+ threshold = options["max_partition_bytes"] or min_splittable_partition_bytes()++ candidates = list(self._candidates(options, threshold)[:limit])+ if not candidates:+ self.stdout.write("No candidates matched.")+ return++ self._report(candidates, threshold)++ if not options["execute"]:+ self.stdout.write(self.style.WARNING(f"\nDry run. Re-run with --execute to nominate {len(candidates)}."))+ return++ for schema in candidates:+ schema.set_coarsen_requested(+ {"requested_at": timezone.now().isoformat(), "requested_by": options["requested_by"]}+ )+ self.stdout.write(self.style.SUCCESS(f"\nNominated {len(candidates)}. Each is evaluated on its next sync."))++ def _candidates(self, options: dict[str, Any], threshold: int) -> QuerySet[ExternalDataSchema]:+ queryset = ExternalDataSchema.objects.filter(deleted=False, should_sync=True).exclude(+ sync_type=ExternalDataSchema.SyncType.CDC+ )+ if options["team_id"]:+ queryset = queryset.filter(team_id=options["team_id"])+ if options["source_type"]:+ queryset = queryset.filter(source__source_type=options["source_type"])++ if options["schema_id"]:+ # Explicit ids are the operator naming tables directly, so the shape filters don't apply.+ # The pipeline still refuses anything it can't coarsen safely.+ return queryset.filter(id__in=options["schema_id"])++ # Anything already queued for a rewrite, mid-swap, or waiting on a corruption revive is left+ # alone: nominating it would either be ignored or fight work that is already under way.+ queryset = queryset.filter(+ sync_type_config__max_partition_bytes__lt=threshold,+ sync_type_config__partition_format__in=FINE_DATETIME_FORMATS,+ ).exclude(sync_type_config__has_any_keys=["repartition_pending", "repartition_swap", "delta_revive_required"])+ # Worst first: the smaller the largest partition, the more the table was over-split.+ return queryset.select_related("source").order_by("sync_type_config__max_partition_bytes")++ def _report(self, candidates: list[ExternalDataSchema], threshold: int) -> None:+ self.stdout.write(f"Largest-partition threshold: {threshold:,} bytes\n")+ self.stdout.write(f"{'schema_id':38} {'team':>7} {'source':14} {'format':6} {'largest_bytes':>14} name")+ for schema in candidates:+ self.stdout.write(+ f"{str(schema.id):38} {schema.team_id:>7} {schema.source.source_type:14} "+ f"{str(schema.partition_format or '-'):6} {schema.max_partition_bytes or 0:>14,} {schema.name}"+ )diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 43182bd440ea..eb611e12acc9 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -554,6 +554,31 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldself.sync_type_config["delta_revive_required"] = infoself._save_sync_type_config()+ @property+ def coarsen_requested(self) -> dict[str, Any] | None:+ """Set by `stage_warehouse_coarsening` to nominate this table for the coarsening rewrite.++ Nominating overrides the *policy* gates the automatic path applies (rollout flag, OOM history,+ layout age, minimum partition count) because an operator has looked at the table. It never+ overrides the *safety* checks: the controller still measures the live layout and refuses any+ target that would not fit the memory budget, so a nomination can only ever be a no-op, never a+ rewrite into partitions too big to merge. Consumed on the next evaluation either way.+ Shape: {"requested_at": iso8601 str, "requested_by": str}.+ """+ if self.sync_type_config:+ marker = self.sync_type_config.get("coarsen_requested", None)+ if isinstance(marker, dict):+ return marker+ return None++ def set_coarsen_requested(self, info: dict[str, Any]) -> None:+ self.sync_type_config["coarsen_requested"] = info+ self._save_sync_type_config()++ def clear_coarsen_requested(self) -> None:+ self.sync_type_config.pop("coarsen_requested", 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()diff --git a/products/warehouse_sources/backend/models/oom_event.py b/products/warehouse_sources/backend/models/oom_event.pyindex e4be544495f8..398f4335a48a 100644--- a/products/warehouse_sources/backend/models/oom_event.py+++ b/products/warehouse_sources/backend/models/oom_event.py@@ -51,6 +51,11 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):def recent_count(cls, schema: "ExternalDataSchema", *, days: int) -> int:"""Number of OOM occurrences recorded for this schema within the last `days`.+ Every retry attempt that follows an OOM'd one counts, including repeats within a single job.+ Each is a separate attempt at the same merge, rescheduled onto whichever worker picks it up, so+ a job that OOMs on attempt after attempt is a table failing deterministically, which is the+ clearest evidence of a memory problem this log carries.+`days` is required (no default) so it stays sourced from `DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS`at the call site rather than duplicating that window here where the two could silently diverge.diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 02bff207be11..7fd0ab097d30 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -39,14 +39,21 @@ The manual flow above re-pulls every row from the source. We also have an automaHow 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. It records a `repartition_pending` target (the next finer tier — md5 count grows, numerical size shrinks, datetime `month` → `week` → `day` → `hour`) when **either** the largest partition is over the budget (`trigger_reason=proactive_threshold`) **or** the schema has repeatedly OOM'd recently (`trigger_reason=oom_history`). The OOM path catches tables whose compressed at-rest size looks safe but whose real merge working set is much larger (e.g. wide nested-JSON columns) — see `ExternalDataSchemaOOMEvent`, recorded per OOM occurrence at the heartbeat-timeout detection point.+- **What the OOM trigger requires.** The signal behind `ExternalDataSchemaOOMEvent` is "the previous attempt stopped heartbeating", which a deploy, an eviction, a node drain and a lost heartbeat all produce as readily as a real OOM, and repartitioning finer fixes none of those. The prerequisite that keeps it from acting where partition size cannot be the cause is `min_splittable_partition_bytes()`: a split has to land above the size the coarsening path treats as over-fragmented, because below it we would be splitting a table into a layout we immediately want to merge back. Since an OOM-triggered split targets half the current largest partition, the table's largest partition must be at least a quarter of the budget for the trigger to act at all. Note that every retry attempt counts, including repeats within one job: each is a separate attempt at the same merge on whichever worker picks it up, so a job that OOMs attempt after attempt is a table failing deterministically, which is the clearest evidence the log carries.+- **Coarsening.** The same detection pass also runs the reverse direction (`trigger_reason=coarsening`, `select_coarsen_target`): a table split far below what memory safety needs pays for every partition on each merge, and most tables in that state were put there by the finer path reacting to failures that were never about size. A table is coarsened only when it has at least 16 partitions, its largest is under an eighth of the budget, at least a 4x reduction is available, it has no OOM history in 14 days, and its current layout is at least 7 days old. Candidate layouts are computed from the measured partitions (re-formatting datetime keys, merging md5 buckets into a divisor of the current count, multiplying numerical bucket size) rather than estimated, and the coarsest one landing under **half** the budget wins. The gap between the two triggers is what stops the controller oscillating: a coarsened table must double before the finer path can claim it, and a split one must shrink eightfold before this path can.++Week into month is the one transition that cannot be computed exactly, because ISO weeks straddle month boundaries and the key does not say how a week's bytes divide between two months. It is sized by upper bound instead, charging each straddling week's full size to both months, so a layout that fits under the bound fits in reality. The transition is worth supporting rather than skipping: the finer path's first step is month into week, so without it a table this controller wrongly split could never be merged back. Note the bound also makes it the narrowest transition on offer, since a month holds only about 4.3 weeks against a 4x minimum reduction, so in practice it needs roughly a year of weekly partitions to qualify.+- **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. An interruption (OOM, worker restart) can leave the `__repartitioned` temp partial, so every step that could destroy live re-validates temp first: the swap opens temp and checks it holds the full row count before deleting live, and a resume re-validates the temp the `ready` marker points at — discarding it and rebuilding fresh from the intact live rather than copying a broken temp over live. A live table whose own log is unreadable is skipped (the import activity's revival handles it), not counted as a repartition failure.- **Safety.** Concurrent _syncs_ are excluded (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), but concurrent _repartition attempts_ are not: an attempt Temporal heartbeat-times-out keeps running as a zombie (heartbeat failures are swallowed) while its retry starts, and S3 has no locking. The schema row's `repartition_claim` is the fence — each attempt mints a claim token, temp tables are scoped to it (`__repartitioned_<token>`), and the claim is re-checked before every batch write and every destructive step (temp sweep, swap marker, live delete). A superseded attempt raises `RepartitionSupersededError` and stands down silently; orphaned temp variants from superseded or crashed attempts are swept by name prefix before each fresh rebuild. 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. Cancellations, superseded attempts, and transient infra errors (DB pooler drops, S3 rate limits) don't count against that cap.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.+- 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.- 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.- 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.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 64a1f96cae34..1f29c1c361b2 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@@ -22,7 +22,7 @@ import asyncioimport dataclassesfrom collections import defaultdictfrom collections.abc import Awaitable, Callable-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import TYPE_CHECKING, Anyimport pyarrow as pa@@ -43,6 +43,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import _purge_s3_prefixfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (+ NULL_NUMERICAL_PARTITION,append_partition_key_to_table,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import table_payload_bytes@@ -397,6 +398,222 @@ def select_repartition_target(return RepartitionTarget(partition_keys=keys, trigger_reason="", partition_mode=None), "selected"+# Coarsening (the reverse direction) rebuilds an over-fragmented table into fewer, larger partitions.+# It aims at half the budget, not the budget itself: landing at the budget would sit one growth spurt+# away from the finer trigger, and the gap between the two targets is what stops the controller+# oscillating. The minimum reduction keeps a rewrite from being spent on a marginal gain.+COARSEN_MIN_REDUCTION_FACTOR = 4++# Partition-key formats, by mode, for parsing a measured key back into the value that produced it.+_DATETIME_KEY_FORMATS: dict[PartitionFormat, str] = {+ "hour": "%Y-%m-%dT%H",+ "day": "%Y-%m-%d",+ "week": "%G-w%V",+ "month": "%Y-%m",+}++# 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+# 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, ...]] = {+ "hour": ("month", "week", "day"),+ "day": ("month", "week"),+ "week": ("month",),+ "month": (),+}+++def _parse_datetime_partition_key(key: str, partition_format: PartitionFormat) -> datetime | None:+ if partition_format == "week":+ # %G/%V need a weekday to resolve to a date, so anchor on the week's Monday.+ return _strptime_or_none(f"{key}-1", "%G-w%V-%u")+ return _strptime_or_none(key, _DATETIME_KEY_FORMATS[partition_format])+++def _strptime_or_none(value: str, fmt: str) -> datetime | None:+ try:+ return datetime.strptime(value, fmt)+ except ValueError:+ return None+++def _merged_keys(parsed: datetime, current_format: PartitionFormat, new_format: PartitionFormat) -> list[str]:+ """The coarser bucket(s) a partition's bytes can land in.++ One bucket for every containing tier. Week into month is the exception: the week starting `parsed`+ runs to the following Sunday, so it can fall in two months, and the key does not say how its bytes+ divide. Both months are returned and each is charged the week's full size, which over-states rather+ than under-states every bucket it touches. A layout that fits under that bound fits in reality.+ """+ if current_format == "week" and new_format == "month":+ monday_month = parsed.strftime(_DATETIME_KEY_FORMATS["month"])+ sunday_month = (parsed + timedelta(days=6)).strftime(_DATETIME_KEY_FORMATS["month"])+ return [monday_month] if monday_month == sunday_month else [monday_month, sunday_month]+ return [parsed.strftime(_DATETIME_KEY_FORMATS[new_format])]+++def _simulate_datetime_coarsening(+ partition_bytes: dict[str | None, int],+ current_format: PartitionFormat,+ new_format: PartitionFormat,+) -> dict[str | None, int] | None:+ """Bytes per partition after re-bucketing measured partitions into `new_format`.++ Computed from the keys rather than estimated: partition keys carry the date they were built from,+ so every transition is exact except week into month, which is an upper bound (see `_merged_keys`).+ Both are safe to size a rewrite against, since neither can under-state a resulting partition.++ None when any key doesn't parse, because a table carrying the unknown-date sentinel or non-date+ keys must not be coarsened on a guess.+ """+ merged: dict[str | None, int] = defaultdict(int)+ for key, size in partition_bytes.items():+ if key is None:+ return None+ parsed = _parse_datetime_partition_key(key, current_format)+ if parsed is None:+ return None+ for merged_key in _merged_keys(parsed, current_format, new_format):+ merged[merged_key] += size+ return dict(merged)+++def _simulate_modulo_coarsening(partition_bytes: dict[str | None, int], new_count: int) -> dict[str | None, int] | None:+ """Bytes per bucket after reducing an md5 scheme to `new_count` buckets.++ Exact only because `new_count` divides the current count: a row in bucket `h % N` lands in+ `(h % N) % M` when M divides N, so buckets merge cleanly instead of redistributing.+ """+ merged: dict[str | None, int] = defaultdict(int)+ for key, size in partition_bytes.items():+ if key is None or not key.isdigit():+ return None+ merged[str(int(key) % new_count)] += size+ return dict(merged)+++def _simulate_numerical_coarsening(+ partition_bytes: dict[str | None, int], multiplier: int+) -> dict[str | None, int] | None:+ """Bytes per bucket after growing a numerical partition size by `multiplier`.++ Buckets are `value // size`, so a size of `size * k` merges exactly `k` adjacent buckets. The null+ bucket holds rows with no usable key and stays as it is.+ """+ merged: dict[str | None, int] = defaultdict(int)+ for key, size in partition_bytes.items():+ if key is None:+ return None+ if key == NULL_NUMERICAL_PARTITION:+ merged[key] += size+ continue+ try:+ bucket = int(key)+ except ValueError:+ return None+ merged[str(bucket // multiplier)] += size+ return dict(merged)+++def select_coarsen_target(+ schema: ExternalDataSchema,+ partition_bytes: dict[str | None, int],+ target_partition_bytes: int,+) -> tuple[RepartitionTarget | None, str]:+ """Pick the coarsest partition scheme whose largest partition still fits `target_partition_bytes`.++ The mirror of `select_repartition_target`, for tables left over-fragmented, most of them by the+ finer path itself reacting to failures that were never about partition size. Fragmentation is not+ free: every partition is its own merge commit, so a table split into thousands of tiny pieces syncs+ slowly enough to cause the very timeouts that shrank it.++ Every candidate layout is simulated from the measured partitions rather than estimated, so a rewrite+ only happens when the result is known. Returns (target, reason); reasons mirror the finer path's.+ """+ if not partition_bytes:+ return None, "no_partitions"++ keys = schema.partitioning_keys or schema.primary_key_columns or []+ if not keys:+ # The rewrite recomputes every row's key, which needs a column to compute it from.+ return None, "unpartitionable_no_keys"+ mode = schema.partition_mode+ current_count = len(partition_bytes)++ def acceptable(simulated: dict[str | None, int] | None) -> bool:+ return (+ simulated is not None+ and max(simulated.values()) <= target_partition_bytes+ and len(simulated) * COARSEN_MIN_REDUCTION_FACTOR <= current_count+ )++ if mode == "datetime":+ current_format: PartitionFormat = schema.partition_format or "month"+ candidate_formats = _COARSER_DATETIME_TIERS.get(current_format)+ if candidate_formats is None:+ return None, "datetime_unknown_format"+ if not candidate_formats:+ 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)):+ return RepartitionTarget(+ partition_keys=keys,+ trigger_reason="",+ partition_mode="datetime",+ partition_format=new_format,+ ), "selected"+ return None, "no_coarser_layout_fits"++ if mode == "md5":+ count = schema.partition_count+ if not count:+ # The measured bucket count is no substitute: sparse data can leave buckets empty, and a+ # divisor of the measured count need not divide the true modulo, which is the whole basis+ # of the simulation's exactness ((h % N) % M == h % M only when M divides N).+ return None, "md5_no_count"+ # Every divisor of the current count is a candidate, because only a divisor merges buckets+ # cleanly (a row in bucket h % N lands in (h % N) % M exactly when M divides N), which is what+ # makes the simulation exact rather than an assumption about how md5 redistributes rows. The+ # finer path produces arbitrary counts, so halving alone would strand any non-power-of-two.+ divisors: set[int] = set()+ for low in range(1, math.isqrt(count) + 1):+ if count % low == 0:+ divisors.add(low)+ divisors.add(count // low)+ divisors.discard(count)+ for new_count in sorted(divisors): # ascending, so the coarsest layout that fits wins+ if acceptable(_simulate_modulo_coarsening(partition_bytes, new_count)):+ return RepartitionTarget(+ partition_keys=keys,+ trigger_reason="",+ partition_mode="md5",+ partition_count=new_count,+ ), "selected"+ return None, "no_coarser_layout_fits"++ if mode == "numerical":+ current_size = schema.partition_size+ if not current_size:+ return None, "numerical_no_size"+ multiplier = 2 ** math.floor(math.log2(max(current_count, 1))) if current_count > 1 else 1+ while multiplier >= 2:+ if acceptable(_simulate_numerical_coarsening(partition_bytes, multiplier)):+ return RepartitionTarget(+ partition_keys=keys,+ trigger_reason="",+ partition_mode="numerical",+ partition_size=current_size * multiplier,+ ), "selected"+ multiplier //= 2+ return None, "no_coarser_layout_fits"++ return None, "unsupported_mode"++def _read_next_batch(reader: pa.RecordBatchReader) -> pa.RecordBatch | None:try:return reader.read_next_batch()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.pyindex f36867bd8626..ce77a86e0f97 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.models.external_data_schema import Exterfrom products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEventfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (measure_partition_bytes,+ select_coarsen_target,select_repartition_target,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (@@ -38,6 +39,22 @@ if TYPE_CHECKING:from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourceWAREHOUSE_AUTO_REPARTITION_FLAG = "data-warehouse-auto-repartition"+WAREHOUSE_AUTO_COARSEN_FLAG = "data-warehouse-auto-coarsen"++# Coarsening gates. The two directions deliberately don't meet: a table is split finer above the budget+# and merged coarser only below an eighth of it, and a coarsen aims at half the budget. So a freshly+# coarsened table has to double before the finer path can claim it, and a freshly split one has to+# shrink eightfold before this path can. Without that gap the controller would hand tables back and+# forth every cooldown.+COARSEN_TRIGGER_DIVISOR = 8+COARSEN_TARGET_DIVISOR = 2+# Below this, fragmentation costs little and a rewrite isn't worth its own risk.+COARSEN_MIN_PARTITIONS = 16+# Let a layout prove itself over a few daily sync cycles before undoing it.+COARSEN_MIN_LAYOUT_AGE_SECONDS = 7 * 24 * 60 * 60+# Longer than the finer path's window: making partitions bigger is the one change that can cause the+# failure it's meant to prevent, so it takes a longer clean run to justify than a split does.+COARSEN_OOM_FREE_DAYS = 14# 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.@@ -47,18 +64,27 @@ REPARTITION_COOLDOWN_SECONDS = 24 * 60 * 60# doesn't re-attempt the rewrite on every sync forever.MAX_REPARTITION_ATTEMPTS = 3-# Worst-case assumed ratio between a partition's in-memory working set and its compressed at-rest-# size — the amplification that justifies the oom_history trigger at all. When even this generous-# multiple of the largest partition fits the budget, partition size can't be what's killing the-# worker (heartbeat timeouts also come from slow merges, deploys, and pod churn), so repartitioning-# finer can't help.-OOM_WORKING_SET_AMPLIFICATION = 100-def target_partition_bytes() -> int:return int(getattr(settings, "DATA_WAREHOUSE_TARGET_PARTITION_BYTES", 500_000_000))+def min_splittable_partition_bytes() -> int:+ """The smallest partition an OOM-triggered split is allowed to produce.++ Derived from the coarsening threshold rather than set independently, so the two directions cannot+ disagree about the same table: anything below this is a layout the coarsening path would want to+ merge back together, and splitting into it would be undoing our own work.++ This is what makes the OOM trigger safe to keep. The OOM signal cannot tell a real kill from a+ deploy or an eviction, so it fires on tables whose partitions were never the problem; requiring the+ result to stay above this floor means the trigger can only act where partition size is a plausible+ cause at all. Splitting below it also multiplies per-partition merge commits, which slows the sync+ that produced the timeouts in the first place.+ """+ return target_partition_bytes() // COARSEN_TRIGGER_DIVISOR++def repartition_oom_threshold() -> int:return int(getattr(settings, "DATA_WAREHOUSE_REPARTITION_OOM_THRESHOLD", 3))@@ -68,7 +94,15 @@ def repartition_oom_window_days() -> int:def is_auto_repartition_enabled(schema: ExternalDataSchema) -> bool:- """Evaluate the rollout flag for this schema.+ return _is_flag_enabled(schema, WAREHOUSE_AUTO_REPARTITION_FLAG)+++def is_auto_coarsen_enabled(schema: ExternalDataSchema) -> bool:+ return _is_flag_enabled(schema, WAREHOUSE_AUTO_COARSEN_FLAG)+++def _is_flag_enabled(schema: ExternalDataSchema, flag: str) -> bool:+ """Evaluate a rollout flag for this schema.`schema_id`, `team_id`, and `source_type` are passed as person properties so the flag can bereleased to a single table — set a release condition `schema_id = <id>` to dogfood the controller@@ -83,7 +117,7 @@ def is_auto_repartition_enabled(schema: ExternalDataSchema) -> bool:try:return bool(posthoganalytics.feature_enabled(- WAREHOUSE_AUTO_REPARTITION_FLAG,+ flag,str(team.uuid),groups={"organization": str(team.organization_id), "project": str(team.id)},person_properties={@@ -135,6 +169,154 @@ def _cooldown_seconds_remaining(schema: ExternalDataSchema) -> float:return max(0.0, REPARTITION_COOLDOWN_SECONDS - (timezone.now() - last_dt).total_seconds())+def _seconds_since_last_repartition(schema: ExternalDataSchema) -> float | None:+ """Age of the current layout, or None when this controller never rewrote the table."""+ last = schema.last_repartition_at+ if not last:+ return None+ try:+ last_dt = parser.parse(last)+ except (ValueError, TypeError):+ return None+ return (timezone.now() - last_dt).total_seconds()+++async def maybe_flag_for_coarsening(+ schema: ExternalDataSchema,+ source: ExternalDataSource,+ job: ExternalDataJob,+ partition_bytes: dict[str | None, int],+ recent_oom_count: int,+ logger: FilteringBoundLogger,+ *,+ budget: int,+ max_bytes: int,+) -> None:+ """Flag an over-fragmented table to be rebuilt into fewer, larger partitions.++ The counterpart to the finer path, for tables that ended up split far below what memory safety+ needs, most of them by that path reacting to failures partition size never caused. Thousands of+ tiny partitions mean thousands of per-partition merge commits, which is its own way to make a sync+ slow enough to look like the problem the split was meant to solve.++ The gates below split into two kinds, and only one kind is overridable. The *policy* gates decide+ whether a table is worth touching unprompted; an operator who has nominated a table through+ `stage_warehouse_coarsening` has already made that call, so a nomination skips them. The *safety*+ check is `select_coarsen_target`, which measures the live layout and refuses any target that would+ not fit the budget. Nothing overrides that, so a nomination can only ever be a no-op.++ Ordered cheapest first — in-memory shape gates, then the in-memory selector, then the database, and+ the feature flag (a Team fetch plus a PostHog API call) dead last. Post-load detection runs this+ for every within-budget table on every sync, so anything before the selector is fleet-wide cost,+ and most tables that pass the shape gates sit at the coarsest tier where the selector refuses.++ Called from `maybe_flag_for_repartition` on its healthy branch and on its floor-blocked branch+ (OOM history present but partitions too small to split — the over-split backlog's exact state, and+ the only route by which a nominated table there is evaluated). Never raises (the caller swallows).+ """+ measured_partitions = len(partition_bytes)+ # Never fight a rewrite that is already staged or mid-swap, however the evaluation was prompted.+ if schema.repartition_pending is not None or schema.repartition_swap is not None:+ return++ requested = schema.coarsen_requested+ if requested is None:+ if measured_partitions < COARSEN_MIN_PARTITIONS:+ return+ if max_bytes * COARSEN_TRIGGER_DIVISOR > budget:+ return+ # Any OOM history at all disqualifies coarsening unprompted: bigger partitions are the wrong+ # direction for a table that has shown memory trouble, and this is the one change that can+ # cause the failure it is meant to prevent.+ if recent_oom_count > 0:+ return+ layout_age = _seconds_since_last_repartition(schema)+ if layout_age is not None and layout_age < COARSEN_MIN_LAYOUT_AGE_SECONDS:+ return++ target, reason = await asyncio.to_thread(+ select_coarsen_target, schema, partition_bytes, budget // COARSEN_TARGET_DIVISOR+ )+ if requested is not None and target is None:+ # Consume a refused nomination now: leaving it set would re-evaluate the same table every sync,+ # and a table the selector refuses today will refuse again until its data changes. A *selected*+ # target keeps the nomination until the pending write lands (below), so a crash between the two+ # writes loses nothing; the leftover marker is then cleared by the next evaluation.+ await asyncio.to_thread(schema.clear_coarsen_requested)++ if target is None:+ # INFO only for an operator, who is waiting on the outcome of a nomination; the automatic path+ # lands here on every sync of every coarsest-tier table, which at INFO would flood the Syncs UI.+ log = logger.ainfo if requested is not None else logger.adebug+ await log(+ f"repartition: no coarser layout applies schema_id={schema.id} reason={reason} "+ f"operator_requested={requested is not None} max_partition_bytes={max_bytes} "+ f"partition_count={measured_partitions}",+ schema_id=str(schema.id),+ reason=reason,+ operator_requested=requested is not None,+ max_partition_bytes=max_bytes,+ partition_count=measured_partitions,+ )+ return++ if requested is None:+ # The 7-day window the caller already checked can miss an OOM that a repartition has since+ # reset, so re-ask over the longer window before making partitions bigger.+ long_window_oom_count = await asyncio.to_thread(+ ExternalDataSchemaOOMEvent.recent_count, schema, days=COARSEN_OOM_FREE_DAYS+ )+ if long_window_oom_count > 0:+ return++ if not await asyncio.to_thread(is_auto_coarsen_enabled, schema):+ await logger.adebug(+ f"repartition: table is over-fragmented but coarsening is disabled by feature flag "+ f"schema_id={schema.id} max_partition_bytes={max_bytes} partition_count={measured_partitions}",+ schema_id=str(schema.id),+ max_partition_bytes=max_bytes,+ partition_count=measured_partitions,+ )+ return++ # Distinct reason for a nominated rewrite, the same way an admin-staged one is distinguishable, so+ # the backlog pass can be tracked separately from what the controller does on its own.+ trigger_reason = "coarsening_requested" if requested is not None else "coarsening"+ pending = {**target.to_dict(), "trigger_reason": trigger_reason, "attempts": 0}+ await asyncio.to_thread(schema.set_repartition_pending, pending)+ if requested is not None:+ # Only after the pending write: consuming the nomination first would lose it to a crash between+ # the two writes, and nothing would ever restore it.+ await asyncio.to_thread(schema.clear_coarsen_requested)++ props = base_event_props(schema, source, str(job.id))+ props.update(+ {+ "max_partition_bytes_before": max_bytes,+ "trigger_reason": trigger_reason,+ "measured_partition_count_before": measured_partitions,+ "partition_mode_after": target.partition_mode or "auto",+ "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(+ f"repartition: flagged for coarsening on the next run schema_id={schema.id} "+ f"max_partition_bytes={max_bytes} partition_count={measured_partitions} "+ f"target_mode={target.partition_mode} target_format={target.partition_format} "+ f"target_count={target.partition_count} target_size={target.partition_size}",+ schema_id=str(schema.id),+ max_partition_bytes=max_bytes,+ partition_count=measured_partitions,+ target_mode=target.partition_mode,+ target_format=target.partition_format,+ target_count=target.partition_count,+ target_size=target.partition_size,+ )++async def maybe_flag_for_repartition(schema: ExternalDataSchema,source: ExternalDataSource,@@ -205,26 +387,55 @@ async def maybe_flag_for_repartition(recent_oom_count=oom_count,partition_count=len(partition_bytes),)+ await maybe_flag_for_coarsening(+ schema, source, job, partition_bytes, oom_count, logger, budget=budget, max_bytes=max_bytes+ )return- # A tiny largest partition can't be the OOM cause: without this guard, oom_history drives the- # scheme finer tier by tier until it bottoms out (e.g. datetime at hour) and then emits a- # skipped event + exception on every cooldown expiry forever — while the extra partitions- # multiply per-partition merge commits, slowing the sync that produced the timeouts.- if not over_budget and max_bytes * OOM_WORKING_SET_AMPLIFICATION < budget:+ # An OOM-triggered split targets roughly half the current largest partition (see `split_budget`+ # below). Refuse when that result would fall under the floor: partition size cannot be what is+ # killing a table whose partitions are already that small, and without this guard oom_history+ # drives the scheme finer tier by tier until it bottoms out (e.g. datetime at hour) and then+ # emits a skipped event plus an exception on every cooldown expiry forever.+ split_budget = budget if over_budget else max(1, max_bytes // 2)+ floor = min_splittable_partition_bytes()+ if not over_budget and split_budget < floor:await logger.adebug(- f"repartition: OOM history present but largest partition is far under budget, "- f"partitioning is not the cause — leaving layout alone schema_id={schema.id} "- f"max_partition_bytes={max_bytes} budget_bytes={budget} recent_oom_count={oom_count}",+ f"repartition: OOM history present but a split would produce partitions under the floor, "+ f"so partitioning is not the cause, leaving layout alone schema_id={schema.id} "+ f"max_partition_bytes={max_bytes} split_budget_bytes={split_budget} floor_bytes={floor} "+ f"budget_bytes={budget} recent_oom_count={oom_count}",schema_id=str(schema.id),max_partition_bytes=max_bytes,+ split_budget_bytes=split_budget,+ floor_bytes=floor,budget_bytes=budget,recent_oom_count=oom_count,)+ # A table blocked here has OOM history *and* partitions too small to split, which is the+ # exact state the over-split backlog is in. Evaluate coarsening rather than returning: the+ # automatic path still refuses it on the same OOM history, but an operator nomination gets+ # its chance, and this is the only route by which a nominated table reaches coarsening at+ # all once its OOM count crosses the split threshold.+ await maybe_flag_for_coarsening(+ schema, source, job, partition_bytes, oom_count, logger, budget=budget, max_bytes=max_bytes+ )returntrigger_reason = "proactive_threshold" if over_budget else "oom_history"+ if schema.coarsen_requested is not None:+ # The table needs the opposite direction, so the nomination is moot — and left set it would+ # force a Delta-log measurement on every sync forever, since nothing else consumes it here.+ await asyncio.to_thread(schema.clear_coarsen_requested)+ await logger.ainfo(+ f"repartition: coarsening nomination cleared, table needs a finer layout instead "+ f"schema_id={schema.id} trigger_reason={trigger_reason} max_partition_bytes={max_bytes}",+ schema_id=str(schema.id),+ trigger_reason=trigger_reason,+ max_partition_bytes=max_bytes,+ )+if enabled is None:enabled = await asyncio.to_thread(is_auto_repartition_enabled, schema)if not enabled:@@ -268,10 +479,10 @@ async def maybe_flag_for_repartition()return- # OOM-triggered but within the size budget: the compressed size under-counted the working set,- # so target roughly half the current largest partition to force a meaningfully finer scheme- # (md5 grows buckets, numerical halves the row-size, datetime steps one tier finer).- split_budget = budget if over_budget else max(1, max_bytes // 2)+ # `split_budget` was computed with the floor check above: an over-budget table targets the+ # budget, while an OOM-triggered one targets roughly half its current largest partition to force+ # a meaningfully finer scheme (md5 grows buckets, numerical halves the row-size, datetime steps+ # one tier finer).target, reason = select_repartition_target(schema, partition_bytes, split_budget)if target is None:# Needs repartition but nothing finer to do (datetime at hour, numerical can't shrink, unpartitionable).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 d87b735b12d1..d05fdb43c110 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@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep_rewrite_into_temp,measure_partition_bytes,repartition_table_in_place,+ select_coarsen_target,select_repartition_target,)@@ -256,6 +257,209 @@ class TestSelectRepartitionTarget:assert target.partition_count == 9+class TestSelectCoarsenTarget:+ @parameterized.expand(+ [+ # (name, schema_kwargs, partition_bytes, target_bytes, expect)+ # A week of hourly partitions: a day's worth fits the target, a week's doesn't, so the+ # coarsest tier that fits is day.+ (+ "hour_merges_into_day",+ {"partition_mode": "datetime", "partition_format": "hour", "partitioning_keys": ["created_at"]},+ {f"2024-01-{day:02d}T{hour:02d}": 10 for day in range(1, 8) for hour in range(24)},+ 500,+ {"partition_mode": "datetime", "partition_format": "day"},+ ),+ # A week-partitioned table can still reach month, sized by upper bound. This matters 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.+ (+ "week_merges_into_month",+ {"partition_mode": "datetime", "partition_format": "week", "partitioning_keys": ["created_at"]},+ {f"2024-w{week:02d}": 10 for week in range(1, 53)},+ 1000,+ {"partition_mode": "datetime", "partition_format": "month"},+ ),+ # Same layout, sized so the upper bound for a month exceeds the target. The bound is what+ # the decision has to use: under-stating a month here is what would rebuild the table into+ # partitions too big to merge.+ (+ "week_refused_when_the_bound_does_not_fit",+ {"partition_mode": "datetime", "partition_format": "week", "partitioning_keys": ["created_at"]},+ {f"2024-w{week:02d}": 200 for week in range(1, 53)},+ 1000,+ None,+ ),+ # Two months of daily partitions: month fits the target and is the coarsest that does, so a+ # single rewrite goes all the way rather than leaving the table to trip the trigger again.+ (+ "day_merges_to_coarsest_tier_that_fits",+ {"partition_mode": "datetime", "partition_format": "day", "partitioning_keys": ["created_at"]},+ {f"2024-{month:02d}-{day:02d}": 10 for month in (1, 2) for day in range(1, 29)},+ 1000,+ {"partition_mode": "datetime", "partition_format": "month"},+ ),+ # Same layout, but a month's worth of data would exceed the target: it must stop at the+ # finer tier that fits. Coarsening past the memory budget would cause the OOMs it prevents.+ (+ "stops_at_the_tier_that_fits_the_target",+ {"partition_mode": "datetime", "partition_format": "day", "partitioning_keys": ["created_at"]},+ {f"2024-{month:02d}-{day:02d}": 100 for month in (1, 2) for day in range(1, 29)},+ 1000,+ {"partition_mode": "datetime", "partition_format": "week"},+ ),+ # Three daily partitions merge into one month, a 3x reduction that falls under the 4x+ # minimum a full table rewrite has to earn.+ (+ "refuses_when_reduction_is_marginal",+ {"partition_mode": "datetime", "partition_format": "day", "partitioning_keys": ["created_at"]},+ {f"2024-01-0{day}": 10 for day in range(1, 4)},+ 1000,+ None,+ ),+ # The unknown-date sentinel `1970-01` doesn't parse as a day, so the merged layout can't be+ # computed. Coarsening on a guess could produce a partition far over budget.+ (+ "refuses_when_a_partition_key_does_not_parse",+ {"partition_mode": "datetime", "partition_format": "day", "partitioning_keys": ["created_at"]},+ {**{f"2024-01-{day:02d}": 10 for day in range(1, 29)}, "1970-01": 10},+ 1000,+ None,+ ),+ (+ "month_is_already_the_coarsest_tier",+ {"partition_mode": "datetime", "partition_format": "month", "partitioning_keys": ["created_at"]},+ {f"2024-{month:02d}": 10 for month in range(1, 13)},+ 1000,+ None,+ ),+ # md5 buckets merge cleanly only into a divisor of the current count: 16 -> 4 keeps every+ # row's bucket derivable from its current one.+ (+ "md5_merges_into_a_divisor_of_the_current_count",+ {"partition_mode": "md5", "partition_count": 16, "partitioning_keys": ["id"]},+ {str(bucket): 100 for bucket in range(16)},+ 500,+ {"partition_mode": "md5", "partition_count": 4},+ ),+ # The finer path produces arbitrary counts, not powers of two. For 18 buckets the only+ # halving candidate is 9, which fails the 4x minimum, so an enumeration that stops at the+ # first non-divisor would strand the table; the full divisor set finds 2 (a 9x reduction).+ (+ "md5_non_power_of_two_count_still_coarsens",+ {"partition_mode": "md5", "partition_count": 18, "partitioning_keys": ["id"]},+ {str(bucket): 50 for bucket in range(18)},+ 500,+ {"partition_mode": "md5", "partition_count": 2},+ ),+ # Without the configured modulo the measured bucket count is no substitute: sparse data+ # leaves buckets empty, and a divisor of the measured count need not divide the true N,+ # which would break the exactness the merge simulation is built on. Refuse, don't guess.+ (+ "md5_without_configured_count_refuses",+ {"partition_mode": "md5", "partitioning_keys": ["id"]},+ {str(bucket): 50 for bucket in range(18)},+ 500,+ None,+ ),+ # Numerical buckets are value // size, so a 4x size merges exactly 4 adjacent buckets.+ (+ "numerical_grows_the_bucket_size",+ {"partition_mode": "numerical", "partition_size": 1000, "partitioning_keys": ["id"]},+ {str(bucket): 100 for bucket in range(16)},+ 500,+ {"partition_mode": "numerical", "partition_size": 4000},+ ),+ (+ "refuses_without_a_key_to_recompute_from",+ {"partition_mode": "datetime", "partition_format": "hour"},+ {f"2024-01-01T{hour:02d}": 10 for hour in range(24)},+ 1000,+ None,+ ),+ ]+ )+ def test_select(self, _name, schema_kwargs, partition_bytes, target_bytes, expect):+ target, reason = select_coarsen_target(_schema(**schema_kwargs), partition_bytes, target_bytes)+ if expect is None:+ assert target is None+ 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(+ [+ ("hour", "day"),+ ("hour", "week"),+ ("hour", "month"),+ ("day", "week"),+ ("day", "month"),+ ]+ )+ def test_simulated_layout_matches_a_real_rewrite(self, current_format, new_format):+ # The selector picks a target purely from simulated sizes, so a simulation that disagrees with+ # how `append_partition_key_to_table` actually buckets rows would size the rewrite against a+ # layout that never materializes. Build both from the same timestamps and compare.+ timestamps = [+ datetime.datetime(2024, 1, 1, tzinfo=datetime.UTC) + datetime.timedelta(hours=6 * step)+ for step in range(200)+ ]+ table = pa.table({"created_at": pa.array(timestamps, type=pa.timestamp("us"))})++ def bucket_sizes(partition_format):+ result = append_partition_key_to_table(+ table, None, None, ["created_at"], "datetime", partition_format, logger+ )+ assert result is not None+ partitioned, *_ = result+ sizes: dict[str | None, int] = {}+ for key in partitioned.column(PARTITION_KEY).to_pylist():+ sizes[key] = sizes.get(key, 0) + 1+ return sizes++ current = bucket_sizes(current_format)+ expected = bucket_sizes(new_format)+ simulated = repartition_module._simulate_datetime_coarsening(current, current_format, new_format)++ assert simulated == expected++ def test_week_into_month_bounds_the_real_rewrite_from_above(self):+ # Weeks straddle month boundaries, so this transition is sized by upper bound rather than+ # exactly. The bound is only safe in one direction: it may over-state a month, but a month it+ # under-stated would let the table be rebuilt into partitions too big to merge.+ timestamps = [+ datetime.datetime(2024, 1, 1, tzinfo=datetime.UTC) + datetime.timedelta(hours=6 * step)+ for step in range(600)+ ]+ table = pa.table({"created_at": pa.array(timestamps, type=pa.timestamp("us"))})++ def bucket_sizes(partition_format):+ result = append_partition_key_to_table(+ table, None, None, ["created_at"], "datetime", partition_format, logger+ )+ assert result is not None+ partitioned, *_ = result+ sizes: dict[str | None, int] = {}+ for key in partitioned.column(PARTITION_KEY).to_pylist():+ sizes[key] = sizes.get(key, 0) + 1+ return sizes++ real = bucket_sizes("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.+ assert set(real) <= set(simulated)+ for month, real_size in real.items():+ assert simulated[month] >= real_size+ # A bound this loose would be useless: the timestamps span whole months, so only the weeks+ # crossing a boundary are double-counted.+ assert max(simulated.values()) <= max(real.values()) * 2++class TestMeasurePartitionBytes:def test_partitioned_groups_by_partition_key(self, tmp_path):delta = _write_month_partitioned(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.pyindex 07af609cc828..89e1edc2a85a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py@@ -268,10 +268,11 @@ class TestRepartitionOOMHistoryTrigger:with tempfile.TemporaryDirectory() as d:delta = _write_partitioned_delta(f"{d}/t", ["0", "1"])with (- # Within the size budget, but close enough that the amplified working set exceeds it —- # a bigger budget would (correctly) hit the tiny-partition guard instead.patch.object(ctrl, "target_partition_bytes", return_value=10_000),patch.object(ctrl, "repartition_oom_threshold", return_value=3),+ # The split floor is exercised by its own test below; neutralize it here so this one+ # fails only if the OOM trigger itself stops working.+ patch.object(ctrl, "min_splittable_partition_bytes", return_value=1),patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),patch.object(ctrl, "capture_repartition_event"),):@@ -318,10 +319,12 @@ class TestRepartitionOOMHistoryTrigger:assert schema.repartition_pending is Nonedef test_tiny_partitions_do_not_flag_on_oom_history(self, team):- # deals/contacts loop from prod: heartbeat timeouts recorded as OOMs on a table whose largest- # partition is KBs against a 500 MB budget. Without the amplification guard the trigger steps- # the scheme finer until it bottoms out at hour, then emits skipped + capture_exception daily- # forever. The guard must be a quiet no-op: nothing pending, no events at all.+ # The loop this guard exists for: timeouts recorded as OOMs on a table whose largest partition+ # is KBs against a 500 MB budget. Splitting it would produce partitions far under the size the+ # coarsening path treats as over-fragmented, so partitioning cannot be the cause. Without the+ # floor the trigger steps the scheme finer until it bottoms out at hour, then emits skipped+ # plus capture_exception daily forever. The guard must be a quiet no-op: nothing pending, no+ # events at all.schema = _make_schema(team,{"partitioning_enabled": True, "partition_mode": "md5", "partition_count": 2, "partitioning_keys": ["id"]},@@ -347,6 +350,163 @@ class TestRepartitionOOMHistoryTrigger:assert capture.call_args_list == []+class TestCoarsenTrigger:+ 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 _fragmented_schema(self, team, **overrides) -> ExternalDataSchema:+ return _make_schema(+ team,+ {+ "partitioning_enabled": True,+ "partition_mode": "md5",+ "partition_count": 16,+ "partitioning_keys": ["id"],+ "last_repartition_at": (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=30)).isoformat(),+ **overrides,+ },+ )++ def test_flags_an_over_fragmented_table_for_coarsening(self, team):+ # The reverse direction: a table split far below what memory safety needs pays for every one of+ # those pieces on each merge. Most tables in this state were put there by the finer path+ # reacting to failures that were never about size, and nothing else brings them back.+ schema = self._fragmented_schema(team)+ with tempfile.TemporaryDirectory() as d:+ delta = _write_partitioned_delta(f"{d}/t", [str(bucket) for bucket in range(16)])+ with (+ patch.object(ctrl, "target_partition_bytes", return_value=10**12),+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),+ patch.object(ctrl, "is_auto_coarsen_enabled", return_value=True),+ patch.object(ctrl, "capture_repartition_event") as capture,+ ):+ self._detect(team, schema, delta)++ schema.refresh_from_db()+ pending = schema.repartition_pending+ assert pending is not None+ assert pending["trigger_reason"] == "coarsening"+ assert pending["partition_mode"] == "md5"+ assert pending["partition_count"] < 16+ assert capture.call_args.args[0] == "warehouse_repartition_flagged"++ @pytest.mark.parametrize(+ "case",+ [+ # Any memory-attributed OOM means bigger partitions are the wrong direction for this table.+ "recent_oom",+ # A layout that was just rewritten hasn't had a chance to prove itself; undoing it within+ # the day is how the two directions would start handing the table back and forth.+ "fresh_layout",+ # Enrolment is per-schema, like the finer path's.+ "flag_disabled",+ ],+ )+ def test_does_not_coarsen_when_a_guard_applies(self, team, case):+ overrides = (+ {"last_repartition_at": datetime.datetime.now(datetime.UTC).isoformat()} if case == "fresh_layout" else {}+ )+ schema = self._fragmented_schema(team, **overrides)+ if case == "recent_oom":+ ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(+ team_id=schema.team_id, schema=schema, run_id="run-1"+ )++ with tempfile.TemporaryDirectory() as d:+ delta = _write_partitioned_delta(f"{d}/t", [str(bucket) for bucket in range(16)])+ with (+ patch.object(ctrl, "target_partition_bytes", return_value=10**12),+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),+ patch.object(ctrl, "is_auto_coarsen_enabled", return_value=case != "flag_disabled"),+ patch.object(ctrl, "capture_repartition_event"),+ ):+ self._detect(team, schema, delta)++ schema.refresh_from_db()+ assert schema.repartition_pending is None++ def test_operator_nomination_overrides_the_policy_gates(self, team):+ # The backlog of already-over-split tables is blocked by the OOM-free gate, because the signal+ # that over-split them keeps firing. A nomination is how an operator gets past that, so it has+ # to work with OOM history present, the flag off, and a layout younger than the age gate.+ schema = self._fragmented_schema(+ team,+ last_repartition_at=datetime.datetime.now(datetime.UTC).isoformat(),+ coarsen_requested={"requested_at": "2026-08-03T00:00:00+00:00", "requested_by": "danielc"},+ )+ ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(+ team_id=schema.team_id, schema=schema, run_id="run-1"+ )++ with tempfile.TemporaryDirectory() as d:+ delta = _write_partitioned_delta(f"{d}/t", [str(bucket) for bucket in range(16)])+ with (+ patch.object(ctrl, "target_partition_bytes", return_value=10**12),+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),+ patch.object(ctrl, "is_auto_coarsen_enabled", return_value=False),+ patch.object(ctrl, "capture_repartition_event"),+ ):+ self._detect(team, schema, delta)++ schema.refresh_from_db()+ pending = schema.repartition_pending+ assert pending is not None+ assert pending["trigger_reason"] == "coarsening_requested"+ # Consumed either way, so a table the selector keeps refusing isn't re-measured every sync.+ assert schema.coarsen_requested is None++ def test_nomination_survives_a_failed_staging_write(self, team):+ # The clear and the pending write are separate commits. If the marker were consumed first, a+ # crash or DB failure between the two would silently drop the operator's nomination with+ # nothing left to restore it, so the marker must still be there after a failed staging.+ schema = self._fragmented_schema(+ team,+ coarsen_requested={"requested_at": "2026-08-03T00:00:00+00:00", "requested_by": "danielc"},+ )++ with tempfile.TemporaryDirectory() as d:+ delta = _write_partitioned_delta(f"{d}/t", [str(bucket) for bucket in range(16)])+ with (+ patch.object(ctrl, "target_partition_bytes", return_value=10**12),+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),+ patch.object(ctrl, "is_auto_coarsen_enabled", return_value=False),+ patch.object(ctrl, "capture_repartition_event"),+ patch.object(ExternalDataSchema, "set_repartition_pending", side_effect=RuntimeError("pooler dropped")),+ ):+ self._detect(team, schema, delta)++ schema.refresh_from_db()+ assert schema.repartition_pending is None+ assert schema.coarsen_requested is not None, "a failed staging must not consume the nomination"++ def test_operator_nomination_does_not_override_the_selector(self, team):+ # The one thing a nomination must never do. This table carries the unknown-date sentinel among+ # its hour keys, so the merged layout can't be derived and coarsening it would be a guess about+ # where those bytes land. An operator asking nicely does not make the guess safe.+ schema = self._fragmented_schema(+ team,+ partition_mode="datetime",+ partition_format="hour",+ partitioning_keys=["created_at"],+ coarsen_requested={"requested_at": "2026-08-03T00:00:00+00:00", "requested_by": "danielc"},+ )++ with tempfile.TemporaryDirectory() as d:+ buckets = [f"2024-01-01T{hour:02d}" for hour in range(15)] + ["1970-01"]+ delta = _write_partitioned_delta(f"{d}/t", buckets)+ with (+ patch.object(ctrl, "target_partition_bytes", return_value=10**12),+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=False),+ patch.object(ctrl, "is_auto_coarsen_enabled", return_value=False),+ patch.object(ctrl, "capture_repartition_event"),+ ):+ self._detect(team, schema, delta)++ schema.refresh_from_db()+ assert schema.repartition_pending is None+ assert schema.coarsen_requested is None++# An Exception-derived cancellation, named exactly `CancelledError`: models how `async_to_sync` can# surface a worker-shutdown cancel so it slips past a plain BaseException catch. `_is_cancellation`# keys on the type name, so this must be named `CancelledError`.diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.pyindex b4866f3c589b..384e815f8bc3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py@@ -14,7 +14,9 @@ from unittest import mockfrom unittest.mock import AsyncMockfrom django.conf import settings+from django.core.management import call_commandfrom django.test import override_settings+from django.utils import timezoneimport s3fsimport orjson@@ -70,6 +72,7 @@ from products.warehouse_sources.backend.facade.models import (get_latest_run_if_exists,)from products.warehouse_sources.backend.models.external_table_definitions import external_tables+from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEventfrom products.warehouse_sources.backend.temporal.data_imports.cdp_producer_job import CDPProducerJobWorkflowfrom products.warehouse_sources.backend.temporal.data_imports.external_data_job import ExternalDataJobWorkflowfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY@@ -2226,6 +2229,356 @@ async def test_in_place_repartition_to_finer_datetime_format(team, postgres_confassert count_after.results[0][0] == 5+_COARSEN_FLAGS_ON = (+ "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table"+ ".is_auto_repartition_enabled",+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"+ ".is_auto_coarsen_enabled",+)+++async def _seed_dated_rows(postgres_connection, postgres_config, table: str, timestamps: list[str]) -> None:+ await postgres_connection.execute(+ "CREATE TABLE IF NOT EXISTS {schema}.{table} (id uuid PRIMARY KEY, created_at timestamp)".format(+ schema=postgres_config["schema"], table=table+ )+ )+ for ts in timestamps:+ await postgres_connection.execute(+ "INSERT INTO {schema}.{table} (id, created_at) VALUES ('{id}', '{ts}T12:00:00.000Z')".format(+ schema=postgres_config["schema"], table=table, id=uuid.uuid4(), ts=ts+ )+ )+ await postgres_connection.commit()+++async def _partition_keys_on_s3(minio_client, team, source_id, table: str) -> set[str]:+ job = await sync_to_async(+ lambda: ExternalDataJob.objects.filter(team_id=team.pk, pipeline_id=source_id).order_by("-created_at").first()+ )()+ assert job is not None+ folder_path = await sync_to_async(job.folder_path)()+ listing = await minio_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=f"{folder_path}/{table}/")+ keys = set()+ for obj in listing.get("Contents", []):+ for part in obj["Key"].split("/"):+ if part.startswith(f"{PARTITION_KEY}="):+ keys.add(part.split("=", 1)[1])+ return keys+++async def _row_ids(team, table: str) -> list[str]:+ # Explicit LIMIT: HogQL defaults to 100 rows, which would silently truncate the identity+ # comparison and let a row-losing rewrite pass on any table bigger than that.+ result = await sync_to_async(execute_hogql_query)(f"SELECT id FROM {table} ORDER BY id LIMIT 10000", team)+ return [str(row[0]) for row in result.results]+++@sync_to_async+def _record_suspected_ooms(team, schema, count: int) -> None:+ # Whole call inside the sync context: resolving the team-scoped manager touches the DB, so it+ # cannot be evaluated while building the sync_to_async argument.+ for _ in range(count):+ ExternalDataSchemaOOMEvent.objects.for_team(team.pk).create(+ team_id=team.pk, schema_id=schema.id, run_id=str(uuid.uuid4())+ )+++@sync_to_async+def _backdate_last_repartition(schema, days: int) -> None:+ # A staged rewrite stamps last_repartition_at, and a freshly rewritten layout is protected by the+ # coarsening age gate. Backdating mirrors the real backlog, whose damage is weeks old.+ schema.refresh_from_db(fields=["sync_type_config"])+ schema.sync_type_config["last_repartition_at"] = (timezone.now() - timedelta(days=days)).isoformat()+ schema.save(update_fields=["sync_type_config"])++[email protected]_db(transaction=True)+async def test_in_place_coarsening_merges_weekly_partitions_into_months(+ team, postgres_config, postgres_connection, minio_client+):+ # The reverse direction, end to end on real data. A year of weekly partitions is over-fragmented,+ # so the controller merges it up to months in place. Week into month is the transition that cannot+ # be sized exactly (ISO weeks straddle month boundaries), so this is the one that most needs to be+ # proven against real Delta files rather than a simulation.+ # One row every 7 days for a year: 52 distinct ISO weeks over 12 months. A month holds only about+ # 4.3 weeks, so a full year is what clears the 4x minimum reduction with any margin.+ timestamps = [(datetime(2025, 1, 1) + timedelta(days=7 * week)).strftime("%Y-%m-%d") for week in range(52)]+ await _seed_dated_rows(postgres_connection, postgres_config, "test_coarsen_week", timestamps)++ _workflow_id, inputs = await _run(+ team=team,+ schema_name="test_coarsen_week",+ table_name="postgres_test_coarsen_week",+ source_type="Postgres",+ job_inputs=_postgres_job_inputs(postgres_config),+ 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_format == "week"+ keys_before = await _partition_keys_on_s3(minio_client, team, inputs.external_data_source_id, "test_coarsen_week")+ assert len(keys_before) >= 16, keys_before+ ids_before = await _row_ids(team, "postgres_test_coarsen_week")+ assert len(ids_before) == len(timestamps)++ # Coarsening evaluates on the next sync and, finding a layout that fits, rewrites in the same run.+ with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True), mock.patch(_COARSEN_FLAGS_ON[1], return_value=True):+ 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 == "month", "the table should have been merged up to monthly partitions"+ assert schema.repartition_pending is None, "the rewrite should have consumed its own pending target"++ keys_after = await _partition_keys_on_s3(minio_client, team, inputs.external_data_source_id, "test_coarsen_week")+ assert keys_after == {f"2025-{month:02d}" for month in range(1, 13)}, keys_after+ assert not any(key.startswith("2025-w") for key in keys_after), keys_after++ # The rewrite moves every row between partitions, so identity is what has to survive, not just count.+ assert await _row_ids(team, "postgres_test_coarsen_week") == ids_before++ # And it must settle: a table just coarsened must not be split straight back on the next sync.+ with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True), mock.patch(_COARSEN_FLAGS_ON[1], return_value=True):+ 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 == "month", "the layout should have settled rather than oscillating"+ assert schema.repartition_pending is None++[email protected]_db(transaction=True)+async def test_oom_history_does_not_split_a_table_with_tiny_partitions(+ team, postgres_config, postgres_connection, minio_client+):+ # The bug this whole change exists for. Repeated OOM occurrences on a table whose partitions are+ # kilobytes used to drive the scheme finer and finer; the split floor must leave it alone, because+ # partition size cannot be what is exhausting memory here.+ timestamps = [f"2025-{month:02d}-{day:02d}" for month in range(1, 13) for day in (1, 15)]+ await _seed_dated_rows(postgres_connection, postgres_config, "test_oom_floor", timestamps)++ _workflow_id, inputs = await _run(+ team=team,+ schema_name="test_oom_floor",+ table_name="postgres_test_oom_floor",+ source_type="Postgres",+ job_inputs=_postgres_job_inputs(postgres_config),+ 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_format == "week"++ await _record_suspected_ooms(team, schema, 3) # enough to trip the OOM trigger on its own++ with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True):+ 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 == "week", "OOM history must not split a table whose partitions are already tiny"+ assert schema.repartition_pending is None, "no finer rewrite should have been queued"++[email protected]_db(transaction=True)+async def test_operator_nomination_coarsens_a_table_the_automatic_path_refuses(+ team, postgres_config, postgres_connection, minio_client+):+ # The backlog path. This table has OOM history, so the automatic gate would never touch it, which+ # is exactly the state the already-over-split tables in production are in. Nominating it through+ # the management command has to get past that gate and still land a layout that fits.+ timestamps = [(datetime(2025, 1, 1) + timedelta(days=7 * week)).strftime("%Y-%m-%d") for week in range(52)]+ await _seed_dated_rows(postgres_connection, postgres_config, "test_nominated", timestamps)++ _workflow_id, inputs = await _run(+ team=team,+ schema_name="test_nominated",+ table_name="postgres_test_nominated",+ source_type="Postgres",+ job_inputs=_postgres_job_inputs(postgres_config),+ 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)+ ids_before = await _row_ids(team, "postgres_test_nominated")+ await _record_suspected_ooms(team, schema, 3)++ await sync_to_async(call_command)(+ "stage_warehouse_coarsening", "--execute", f"--schema-id={schema.id}", "--requested-by=e2e"+ )+ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)+ assert schema.coarsen_requested is not None++ # No feature flag patched here: the nomination is what gets this table measured at all.+ 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 == "month", "the nominated table should have been coarsened"+ assert schema.coarsen_requested is None, "the nomination should be consumed once evaluated"+ assert await _row_ids(team, "postgres_test_nominated") == ids_before++[email protected]_db(transaction=True)+async def test_in_place_coarsening_merges_hourly_partitions_up(+ team, postgres_config, postgres_connection, minio_client+):+ # The production damage shape: most over-split tables were driven to the hour tier by the finer+ # path, exactly as staged here. Coarsening must jump straight to the coarsest tier that fits (month+ # for this data) rather than crawling back one tier per daily cooldown cycle.+ timestamps = [(datetime(2025, 1, 1) + timedelta(days=7 * week)).strftime("%Y-%m-%d") for week in range(52)]+ await _seed_dated_rows(postgres_connection, postgres_config, "test_coarsen_hour", timestamps)++ _workflow_id, inputs = await _run(+ team=team,+ schema_name="test_coarsen_hour",+ table_name="postgres_test_coarsen_hour",+ source_type="Postgres",+ job_inputs=_postgres_job_inputs(postgres_config),+ mock_data_response=[],+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},+ ignore_assertions=True,+ )++ # Stage the damage the finer path used to do: rewrite the table down to hourly partitions.+ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)+ await sync_to_async(schema.set_repartition_pending)(+ {+ "partition_mode": "datetime",+ "partition_format": "hour",+ "partition_keys": ["created_at"],+ "partition_count": None,+ "partition_size": None,+ "trigger_reason": "test",+ "attempts": 0,+ }+ )+ # The rollout flag gates the queued rewrite too (a pending repartition is released, not run, when+ # it's off), so force it on for the staging run that produces the over-split layout.+ with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True):+ 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 == "hour"+ keys_hourly = await _partition_keys_on_s3(minio_client, team, inputs.external_data_source_id, "test_coarsen_hour")+ assert len(keys_hourly) == len(timestamps) and all("T" in key for key in keys_hourly), keys_hourly+ ids_before = await _row_ids(team, "postgres_test_coarsen_hour")++ await _backdate_last_repartition(schema, days=8)+ with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True), mock.patch(_COARSEN_FLAGS_ON[1], return_value=True):+ 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 == "month", "hourly partitions should merge straight up to monthly"+ keys_after = await _partition_keys_on_s3(minio_client, team, inputs.external_data_source_id, "test_coarsen_hour")+ assert keys_after == {f"2025-{month:02d}" for month in range(1, 13)}, keys_after+ assert await _row_ids(team, "postgres_test_coarsen_hour") == ids_before++[email protected]_db(transaction=True)+ "mode,staged_target,expected_after",+ [+ # md5 buckets merge only into a divisor of the current count; for a tiny table the coarsest+ # divisor that fits is a single bucket.+ (+ "md5",+ {"partition_mode": "md5", "partition_count": 16, "partition_keys": ["id"]},+ {"partition_mode": "md5", "partition_count": 1},+ ),+ # Numerical buckets are id // size, so coarsening multiplies the size; 320 dense ids at size 10+ # give 32 buckets that merge into one bucket of size 320.+ (+ "numerical",+ {"partition_mode": "numerical", "partition_size": 10, "partition_keys": ["id"]},+ {"partition_mode": "numerical", "partition_size": 320},+ ),+ ],+)+async def test_in_place_coarsening_for_hashed_and_numerical_modes(+ team, postgres_config, postgres_connection, minio_client, mode, staged_target, expected_after+):+ # The non-datetime modes use entirely different bucket arithmetic (modulo merge vs size multiply),+ # so datetime passing e2e proves nothing about them. Same shape as the datetime tests: stage the+ # over-split layout, coarsen, verify layout and row identity on real Delta files.+ table = f"test_coarsen_{mode}"+ await postgres_connection.execute(+ "CREATE TABLE IF NOT EXISTS {schema}.{table} (id integer PRIMARY KEY)".format(+ schema=postgres_config["schema"], table=table+ )+ )+ await postgres_connection.execute(+ "INSERT INTO {schema}.{table} (id) SELECT generate_series(1, 320)".format(+ schema=postgres_config["schema"], table=table+ )+ )+ await postgres_connection.commit()++ _workflow_id, inputs = await _run(+ team=team,+ schema_name=table,+ table_name=f"postgres_{table}",+ source_type="Postgres",+ job_inputs=_postgres_job_inputs(postgres_config),+ mock_data_response=[],+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},+ ignore_assertions=True,+ )++ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)+ await sync_to_async(schema.set_repartition_pending)(+ {+ **staged_target,+ "partition_count": staged_target.get("partition_count"),+ "partition_size": staged_target.get("partition_size"),+ "trigger_reason": "test",+ "attempts": 0,+ }+ )+ # Same as the datetime test: the rollout flag must be on for the staging rewrite to run at all.+ with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True):+ 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_mode == mode+ keys_fragmented = await _partition_keys_on_s3(minio_client, team, inputs.external_data_source_id, table)+ assert len(keys_fragmented) >= 16, keys_fragmented+ ids_before = await _row_ids(team, f"postgres_{table}")+ assert len(ids_before) == 320++ await _backdate_last_repartition(schema, days=8)+ with mock.patch(_COARSEN_FLAGS_ON[0], return_value=True), mock.patch(_COARSEN_FLAGS_ON[1], return_value=True):+ 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)+ for field, value in expected_after.items():+ assert getattr(schema, field) == value, (field, getattr(schema, field))+ keys_after = await _partition_keys_on_s3(minio_client, team, inputs.external_data_source_id, table)+ assert len(keys_after) * 4 <= len(keys_fragmented), (keys_fragmented, keys_after)+ assert await _row_ids(team, f"postgres_{table}") == ids_before++@pytest.mark.django_db(transaction=True)@pytest.mark.asyncio@pytest.mark.parametrize(diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.pyindex 4b39805305bd..308cb82ac9e3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py@@ -157,12 +157,15 @@ def _needs_pre_extraction_detection(schema: ExternalDataSchema, enabled: bool) -read the live partition sizes from the Delta log each run and let `maybe_flag_for_repartition` judgeagainst the real, current size. The cost is one metadata-only Delta-log read per sync, bounded toflagged schemas; a disabled flag still short-circuits to a zero-I/O no-op.++ A table nominated for coarsening is measured whether or not the rollout flag covers it, since the+ nomination is the operator asking for exactly this measurement. CDC stays excluded either way."""- if not enabled:- return Falseif schema.sync_type == ExternalDataSchema.SyncType.CDC:return False- return True+ if schema.coarsen_requested is not None:+ return True+ return enableddef _maybe_flag_pre_extraction(diff --git a/products/warehouse_sources/backend/tests/management/test_stage_warehouse_coarsening.py b/products/warehouse_sources/backend/tests/management/test_stage_warehouse_coarsening.pynew file mode 100644index 000000000000..4a39da2041af--- /dev/null+++ b/products/warehouse_sources/backend/tests/management/test_stage_warehouse_coarsening.py@@ -0,0 +1,88 @@+import uuid+from io import StringIO++from posthog.test.base import BaseTest++from django.core.management import call_command++from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+++class TestStageWarehouseCoarsening(BaseTest):+ def _schema(self, name: str, sync_type_config: dict) -> 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=name, sync_type_config=sync_type_config+ )++ def _fragmented(self, name: str, **overrides) -> ExternalDataSchema:+ return self._schema(+ name,+ {+ "partitioning_enabled": True,+ "partition_mode": "datetime",+ "partition_format": "hour",+ "max_partition_bytes": 1_000,+ **overrides,+ },+ )++ def _run(self, **options) -> str:+ out = StringIO()+ call_command("stage_warehouse_coarsening", stdout=out, team_id=self.team.pk, **options)+ return out.getvalue()++ def test_dry_run_reports_candidates_without_nominating(self) -> None:+ # Staging a rewrite on a table blocks its next sync for as long as the rewrite takes, so a run+ # that was meant to be a preview must not leave markers behind.+ schema = self._fragmented("orders")++ output = self._run()++ assert str(schema.id) in output+ schema.refresh_from_db()+ assert schema.coarsen_requested is None++ def test_execute_nominates_and_records_who_asked(self) -> None:+ schema = self._fragmented("orders")++ self._run(execute=True, requested_by="danielc")++ schema.refresh_from_db()+ marker = schema.coarsen_requested+ assert marker is not None+ assert marker["requested_by"] == "danielc"++ def test_skips_tables_that_are_not_over_fragmented_or_are_already_busy(self) -> None:+ # Each exclusion is a way to waste a rewrite or collide with one in flight: a table whose+ # partitions are already a healthy size has nothing to merge, and a table mid-rewrite or+ # awaiting a corruption revive must not have a second rewrite queued behind it.+ healthy = self._fragmented("healthy", max_partition_bytes=400_000_000)+ already_queued = self._fragmented("queued", repartition_pending={"partition_mode": "datetime"})+ reviving = self._fragmented("reviving", delta_revive_required={"reason": "x"})+ coarse = self._fragmented("coarse", partition_format="month")+ eligible = self._fragmented("eligible")++ output = self._run(execute=True)++ assert str(eligible.id) in output+ for schema in (healthy, already_queued, reviving, coarse):+ schema.refresh_from_db()+ assert schema.coarsen_requested is None, schema.name++ def test_named_schemas_skip_the_shape_filters(self) -> None:+ # Naming a table explicitly is the operator overriding the heuristics, which is the point of+ # having the escape hatch. Safety is still the pipeline's call, not this command's.+ healthy = self._fragmented("healthy", max_partition_bytes=400_000_000)++ self._run(execute=True, schema_id=[str(healthy.id)])++ healthy.refresh_from_db()+ assert healthy.coarsen_requested is not Nonediff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex 5cfc8f799136..74a0269fa9ed 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -332,8 +332,18 @@ class TestExternalDataSchemaOOMEvent(BaseTest):def _schema(self, name: str) -> ExternalDataSchema:return ExternalDataSchema.objects.create(team_id=self.team.pk, source=self._source(), name=name)- def _oom(self, schema: ExternalDataSchema, *, age_days: float = 0) -> ExternalDataSchemaOOMEvent:- event = ExternalDataSchemaOOMEvent.objects.for_team(self.team.pk).create(team_id=self.team.pk, schema=schema)+ def _oom(+ self,+ schema: ExternalDataSchema,+ *,+ age_days: float = 0,+ run_id: str | None = None,+ ) -> ExternalDataSchemaOOMEvent:+ event = ExternalDataSchemaOOMEvent.objects.for_team(self.team.pk).create(+ team_id=self.team.pk,+ schema=schema,+ run_id=run_id,+ )if age_days:# created_at is auto_now_add, so backdate via an update to place the row outside the window.ExternalDataSchemaOOMEvent.objects.unscoped().filter(pk=event.pk).update(@@ -376,6 +386,16 @@ class TestExternalDataSchemaOOMEvent(BaseTest):self._oom(schema)assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 1+ def test_recent_count_counts_every_retry_attempt(self) -> None:+ # Retries of one job are separate attempts at the same merge, each rescheduled onto whichever+ # worker picks it up. A job that OOMs attempt after attempt is a table failing deterministically,+ # so collapsing those into one occurrence would discard the clearest evidence this log carries.+ schema = self._schema("orders")+ for _ in range(5):+ self._oom(schema, run_id="run-1")++ assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 5+class TestUpdateSyncTypeConfigKeys(BaseTest):"""The locked-merge helper that keeps the CDC extract activity and concurrent API PATCHes from