: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(warehouse-sources): stop infrastructure deaths from blocking coarsening (#83222)
Daniel RC7dffeef0a137
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.pyindex 97447d9fece8..8c35d76db3e5 100644--- a/posthog/settings/data_warehouse.py+++ b/posthog/settings/data_warehouse.py@@ -103,6 +103,13 @@ DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS = get_from_env(# tenant's schemas at once, which is not infrastructure and must not suppress other tenants' counting.DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS = get_from_env("DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS", 10, type_cast=int)+# A merge-phase death whose own peak buffer crossed this blocks coarsening whatever the classification+# rules concluded, because enlarging the merge of a table last seen holding real memory is not a safe+# bet to make on a plausible exclusion.+DATA_WAREHOUSE_COARSEN_BLOCK_MERGE_PEAK_BYTES = get_from_env(+ "DATA_WAREHOUSE_COARSEN_BLOCK_MERGE_PEAK_BYTES", 1_048_576, type_cast=int+)+# Pre-write vacuum runs when this many delta commits have accrued since the last vacuum. Decoupled from# merge success so tables that OOM their merge still get their tombstones cleared (the compact-after-merge# path never runs for them). Vacuum only deletes dead files, so it's memory-safe even on oversized tables.diff --git a/products/warehouse_sources/backend/models/oom_event.py b/products/warehouse_sources/backend/models/oom_event.pyindex 7de6542afe2e..83df4126924b 100644--- a/products/warehouse_sources/backend/models/oom_event.py+++ b/products/warehouse_sources/backend/models/oom_event.py@@ -23,23 +23,11 @@ if TYPE_CHECKING:NON_MERGE_PHASES = ("extract", "load", "finished")-def infra_burst_window_seconds() -> int:- return int(getattr(settings, "DATA_WAREHOUSE_OOM_INFRA_BURST_WINDOW_SECONDS", 1800))---def infra_burst_min_schemas() -> int:- return int(getattr(settings, "DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS", 50))---def infra_burst_min_teams() -> int:- return int(getattr(settings, "DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS", 10))--def evidence_freshness_bound_seconds() -> float:# A phase flip reaches Redis only on the next periodic sample, so evidence up to one interval old# is normal. Twice the interval tolerates one missed write; beyond that the report describes what# the run was doing earlier, not what killed it.- return 2.0 * float(getattr(settings, "DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS", 30.0))+ return 2.0 * settings.DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS@dataclass(frozen=True, kw_only=True)@@ -113,41 +101,30 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):def recent_count(cls, schema: "ExternalDataSchema", *, days: int) -> int:"""Occurrences within the last `days` that still look like this table's own merge OOM.- Three rules narrow the raw stopped-heartbeating signal, each with a distinct evidence source,- and each failing open (an occurrence the evidence cannot explain away stays counted):+ Three rules narrow the raw stopped-heartbeating signal, all failing open so an occurrence the+ evidence cannot explain stays counted:- * **Phase** — a death self-reported in a non-merge phase is not a repartitioning problem,- whatever killed the worker (see `NON_MERGE_PHASES`).- * **Culprit** — a pod OOM kills every co-tenant. If something else on the pod self-reported a- strictly larger peak buffer than us, we were plausibly collateral, not the cause. The- snapshot only carries co-tenant peaks time-correlated with the death (see- `enrich_death_event_properties`): a neighbour that crashed an hour earlier, or a lifetime- peak long since released, must not exonerate a death it had nothing to do with.+ * **Phase** — a death self-reported outside a merge is not a repartitioning problem, whatever+ killed the worker (see `NON_MERGE_PHASES`).+ * **Culprit** — a pod OOM kills every co-tenant, so a neighbour reporting a strictly larger+ peak buffer makes us plausibly collateral. Only peaks time-correlated with the death are+ carried (see `enrich_death_event_properties`), because a neighbour that crashed an hour+ earlier cannot exonerate this one.* **Infra burst** — a deploy, node drain or incident takes down many unrelated schemas at- once; an occurrence sharing a window with a fleet-wide burst is attributed to infrastructure.- A burst must span many distinct *teams* as well as schemas — one tenant's own outage is not- infrastructure and must not suppress other tenants' counting.- Judged at read time from the rows themselves, because the burst window extends past the- occurrence being judged (later rows are part of its evidence).-- The phase and culprit rules additionally require the snapshot to be *fresh* relative to the- death (see `_evidence_excludes`): self-reports are periodic, so stale evidence predates- whatever killed the worker and cannot exonerate.-- Every retry attempt counts, including repeats within one job: each is a separate attempt at- the same merge, rescheduled onto whichever worker picks it up, so a job failing attempt after- attempt is the clearest evidence the 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.-- The window is also floored at the schema's `last_repartition_at`: a completed repartition- addresses the OOMs that preceded it, so counting them again would re-trigger a repartition on- the same (now healthy) table every cooldown until they age out.-- This is the *filtered* view for the split trigger, where failing open means counting. Gates- that must stay conservative in the opposite direction (coarsening, which grows the merge- working set) use `has_recent_occurrences` — the raw signal — instead.+ once. The burst must span many distinct teams as well as schemas, since one tenant's own+ outage is not infrastructure. Judged at read time because the window extends past the+ occurrence being judged, so later rows are part of its evidence.++ Phase and culprit additionally require the snapshot to be fresh relative to the death (see+ `_evidence_excludes`): self-reports are periodic, so stale evidence predates whatever killed+ the worker.++ Every retry attempt counts, including repeats within one job, because each is a fresh attempt+ at the same merge on whichever worker picks it up.++ The window is floored at `last_repartition_at`: a completed repartition addresses the OOMs+ that preceded it, so counting them again would re-trigger on a now-healthy table every+ cooldown until they age out. `blocks_coarsening` deliberately drops that floor."""since = timezone.now() - timedelta(days=days)last_repartition_at = schema.last_repartition_at@@ -156,8 +133,11 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):since = max(since, parser.parse(last_repartition_at))except (ValueError, TypeError):pass+ return cls._classified_count(cls._events_since(schema, since), since)- events = list(+ @classmethod+ def _events_since(cls, schema: "ExternalDataSchema", since: datetime) -> list[dict[str, Any]]:+ return list(cls.objects.for_team(schema.team_id).filter(schema_id=schema.pk, created_at__gte=since).values(@@ -168,33 +148,48 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):"co_tenant_correlated_max_peak_buffer_bytes",))- # Healthy schemas have no rows, so they pay for one indexed lookup and no rule evaluation.- # The in-memory rules run first so exonerated rows never reach the burst check at all.++ @classmethod+ def _classified_count(cls, events: list[dict[str, Any]], since: datetime) -> int:+ # Cheap rules first, so exonerated rows never reach the fleet-wide burst query below.candidates = [event for event in events if not cls._evidence_excludes(event)]if not candidates:return 0- # Burst screening is one fleet-wide bucketed aggregate over the whole window, whatever the- # candidate count: a half-window bucket that alone crosses the thresholds proves any window- # fully containing it does too (distinct counts are monotone under containment), so each- # candidate's verdict is an in-memory containment check. Bursts spread too thin for any- # single bucket to prove fail open and count. The extra window before `since` keeps a burst- # just outside the window boundary visible to the candidates near it.- window = timedelta(seconds=infra_burst_window_seconds())+ # One bucketed aggregate serves every candidate: distinct counts are monotone under+ # containment, so a half-window bucket that alone crosses the thresholds proves any window+ # containing it does too, and each candidate's verdict becomes an in-memory check. Bursts too+ # thin for a single bucket to prove fail open and count. Reaching one window back from `since`+ # keeps a burst straddling the boundary visible to the candidates near it.+ window = timedelta(seconds=settings.DATA_WAREHOUSE_OOM_INFRA_BURST_WINDOW_SECONDS)buckets = cls._burst_bucket_stats(since - window, timezone.now())return sum(1 for event in candidates if not cls._window_has_burst_bucket(event["created_at"], buckets))@classmethod- def has_recent_occurrences(cls, schema: "ExternalDataSchema", *, days: int) -> bool:- """Whether ANY occurrence exists in the window — the raw signal, no rules applied.-- For gates whose conservative direction is inverted relative to the split trigger: coarsening- grows the merge working set, so any recent death evidence — even one the rules would explain- away as a victim or infrastructure — must block it. Exclusion exists to withhold a split,- never to enable a coarsen.+ def blocks_coarsening(cls, schema: "ExternalDataSchema", *, days: int) -> bool:+ """Whether recent evidence says a coarser layout would be unsafe for this table.++ Coarsening grows the merge working set, so it must not run on a table whose merges are already+ dying. The classification is deliberately reused rather than the raw log, because one+ fleet-wide restart would otherwise withhold coarsening from every table it touched. The rules+ fail open, so a death nothing explains still blocks.++ A merge-phase death whose own peak crossed `DATA_WAREHOUSE_COARSEN_BLOCK_MERGE_PEAK_BYTES`+ blocks as well, whatever verdict the rules reached, because the two directions are not+ symmetric: a merely plausible exclusion costs the split trigger a rewrite it did not need, but+ costs this one an enlarged merge on a table last seen holding real memory."""+ # No `last_repartition_at` floor, unlike `recent_count`. Coarsening undoes a split, so the+ # OOMs that justified that split are the evidence most worth keeping; flooring them away would+ # let the table coarsen straight back and split again on the next OOM.since = timezone.now() - timedelta(days=days)- return cls.objects.for_team(schema.team_id).filter(schema_id=schema.pk, created_at__gte=since).exists()+ events = cls._events_since(schema, since)+ if cls._classified_count(events, since) > 0:+ return True+ peak_bound = settings.DATA_WAREHOUSE_COARSEN_BLOCK_MERGE_PEAK_BYTES+ return any(+ event["self_phase"] == "merge" and (event["self_peak_buffer_bytes"] or 0) > peak_bound for event in events+ )@classmethoddef _evidence_excludes(cls, event: dict[str, Any]) -> bool:@@ -225,7 +220,7 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):verdict infrastructure — one tenant's own outage takes out many of its schemas at once andmust not classify other tenants' contemporaneous deaths as infra."""- bucket_seconds = infra_burst_window_seconds() / 2+ bucket_seconds = settings.DATA_WAREHOUSE_OOM_INFRA_BURST_WINDOW_SECONDS / 2rows = (cls.all_teams.filter(created_at__gte=start, created_at__lte=end).annotate(bucket=Floor(Extract("created_at", "epoch") / bucket_seconds))@@ -242,11 +237,12 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):# Sound in the exclusion direction only: a bucket fully inside [t - window, t + window] whose# own distinct counts cross the thresholds proves the window's do (distinct counts are# monotone under containment). No such bucket proves nothing, so the candidate counts.- window_seconds = float(infra_burst_window_seconds())+ window_seconds = float(settings.DATA_WAREHOUSE_OOM_INFRA_BURST_WINDOW_SECONDS)bucket_seconds = window_seconds / 2low = created_at.timestamp() - window_secondshigh = created_at.timestamp() + window_seconds- min_schemas, min_teams = infra_burst_min_schemas(), infra_burst_min_teams()+ min_schemas = settings.DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS+ min_teams = settings.DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMSreturn any(bucket.start_epoch >= lowand bucket.start_epoch + bucket_seconds <= highdiff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex a16ece07f959..c1a2b58fe897 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -42,7 +42,7 @@ How it works:- **Detection.** After each sync, the controller measures per-partition bytes from the Delta log (`get_add_actions` — no S3 LIST, no scan) and always records `max_partition_bytes` on the schema for observability. 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 occurrence at the heartbeat-timeout detection point. _Suspected_, because the raw signal ("the previous attempt stopped heartbeating") is equally a deploy, an eviction or a lost heartbeat. Each row snapshots the workload self-report evidence available at recording time (own phase, own peak buffer, co-tenant aggregates — see the self-reporting section above), and `recent_count` only counts occurrences the evidence cannot explain away: deaths self-reported outside the merge phase are excluded (their remedy is chunking or routing, not partitioning), deaths where a pod co-tenant reported a strictly larger peak buffer are excluded as collateral, and occurrences inside a fleet-wide burst of many distinct schemas are attributed to infrastructure. Exonerating evidence must also be fresh relative to the death — self-reports are periodic, so a stale snapshot describes an earlier phase of the run. Every rule fails open — missing or stale evidence never exonerates.- **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.+- **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, no occurrence in the last 14 days still looks like its own merge OOM once the classification rules have run (infrastructure bursts and non-merge deaths do not block it, an unexplained death does, and a merge-phase death whose own peak buffer crossed `DATA_WAREHOUSE_COARSEN_BLOCK_MERGE_PEAK_BYTES` blocks whatever the rules concluded), 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.@@ -56,6 +56,7 @@ Tuning and gating:- 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.+- The coarsening gate's own tunables are `COARSEN_OOM_FREE_DAYS` (default 14, deliberately longer than the split window) and `DATA_WAREHOUSE_COARSEN_BLOCK_MERGE_PEAK_BYTES` (default 1 MB), the peak above which a merge-phase death blocks regardless of how the classification rules explained it. `DELTA_COARSEN_DECLINE_TOTAL` records which gate declined, labelled by reason.- 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_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.pyindex 9ef01bc69f98..0b9160f481a0 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@@ -226,9 +226,9 @@ async def maybe_flag_for_coarsening(measured_partitions = len(partition_bytes)def _decline(reason: str) -> None:- # Why an over-fragmented table did NOT coarsen. Without this a stalled rollout is invisible:- # every gate below returns silently, so "nothing happened" and "nothing was eligible" look- # identical from outside. A counter rather than an event because this runs per sync per table.+ # Every gate below returns silently, so without this "the rollout stalled" and "nothing was+ # eligible" look identical from outside. A counter rather than an event because this runs on+ # every table on every sync.DELTA_COARSEN_DECLINE_TOTAL.labels(reason=reason).inc()# Never fight a rewrite that is already staged or mid-swap, however the evaluation was prompted.@@ -237,16 +237,15 @@ async def maybe_flag_for_coarsening(requested = schema.coarsen_requestedif requested is None:- # Below these two the table is not over-fragmented, so it is not a coarsening candidate at all- # and its decline carries no information — returning before `_decline` keeps the metric to the- # population the rollout is about rather than every table on every sync.+ # Below these two the table is not over-fragmented at all, so returning before `_decline`+ # keeps the metric scoped to the population the rollout is about.if measured_partitions < COARSEN_MIN_PARTITIONS:returnif max_bytes * COARSEN_TRIGGER_DIVISOR > budget:return- # Cheap short-circuit on the count the caller already has. NOT the OOM-free guarantee: this- # count is rule-filtered, so a table whose deaths were all explained away passes it — the- # authoritative raw-signal gate is `has_recent_occurrences` further down.+ # Cheap short-circuit on the count the caller already has: it covers the split trigger's+ # shorter window, so the authoritative gate over `COARSEN_OOM_FREE_DAYS` is+ # `blocks_coarsening` further down.if recent_oom_count > 0:return _decline("oom_history_recent")layout_age = _seconds_since_last_repartition(schema)@@ -280,12 +279,9 @@ async def maybe_flag_for_coarsening(return _decline(reason)if requested is None:- # Raw occurrences, not the rule-filtered `recent_count`: the rules exist to withhold splits,- # and a death they explain away (victim, deploy, extract) is still death evidence — coarsening- # doubles the merge working set, so any of it blocks the automatic path.- if await asyncio.to_thread(- ExternalDataSchemaOOMEvent.has_recent_occurrences, schema, days=COARSEN_OOM_FREE_DAYS- ):+ # Classified, not raw: a nightly restart that kills a hundred unrelated schemas says nothing+ # about any of their merges, and blocking on it would withhold coarsening from all of them.+ if await asyncio.to_thread(ExternalDataSchemaOOMEvent.blocks_coarsening, schema, days=COARSEN_OOM_FREE_DAYS):return _decline("oom_within_free_window")if not await asyncio.to_thread(is_auto_coarsen_enabled, schema):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 8ebe92e53346..12575a86155c 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@@ -7,6 +7,8 @@ import pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.db import OperationalError+from django.test import override_settings+from django.utils import timezoneimport pyarrow as paimport deltalake as deltalake@@ -15,6 +17,8 @@ from asgiref.sync import async_to_syncfrom temporalio.exceptions import ApplicationErrorfrom temporalio.testing import ActivityEnvironment+from posthog.models.team import Team+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -38,6 +42,13 @@ logger = structlog.get_logger(__name__)pytestmark = pytest.mark.django_db(transaction=True)+_NOMINATION = {"requested_at": "2026-08-03T00:00:00+00:00", "requested_by": "danielc"}+++def _days_ago_iso(days: float) -> str:+ return (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=days)).isoformat()++def _write_partitioned_delta(path: str, buckets: list[str]) -> deltalake.DeltaTable:table = pa.table({@@ -379,27 +390,48 @@ class TestCoarsenTrigger:"partition_mode": "md5","partition_count": 16,"partitioning_keys": ["id"],- "last_repartition_at": (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=30)).isoformat(),+ "last_repartition_at": _days_ago_iso(30),**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)+ def _detect_over_fragmented(+ self, team, schema: ExternalDataSchema, *, coarsen_enabled: bool = True, buckets: list[str] | None = None+ ) -> MagicMock:with tempfile.TemporaryDirectory() as d:- delta = _write_partitioned_delta(f"{d}/t", [str(bucket) for bucket in range(16)])+ delta = _write_partitioned_delta(f"{d}/t", buckets or [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, "is_auto_coarsen_enabled", return_value=coarsen_enabled),patch.object(ctrl, "capture_repartition_event") as capture,):self._detect(team, schema, delta)-schema.refresh_from_db()+ return capture++ def _record_oom(self, schema: ExternalDataSchema, *, days_ago: float = 0, **evidence) -> None:+ event = ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(+ team_id=schema.team_id, schema=schema, run_id="run-1", **evidence+ )+ if days_ago:+ ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).filter(pk=event.pk).update(+ created_at=timezone.now() - datetime.timedelta(days=days_ago)+ )++ def _record_fleet_wide_burst(self, team) -> None:+ for _ in range(3):+ other_team = Team.objects.create(organization=team.organization)+ self._record_oom(_make_schema(other_team, {}))++ 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)++ capture = self._detect_over_fragmented(team, schema)+pending = schema.repartition_pendingassert pending is not Noneassert pending["trigger_reason"] == "coarsening"@@ -410,12 +442,8 @@ class TestCoarsenTrigger:@pytest.mark.parametrize("case",[- # Any memory-attributed OOM means bigger partitions are the wrong direction for this table.+ # The cheap short-circuit on the split trigger's own count, ahead of the 14-day gate."recent_oom",- # The gate reads the RAW signal: an occurrence the classification rules would explain- # away (here: fresh extract-phase evidence, excluded from the split trigger) is still- # death evidence, and exclusion must never enable a coarsen it would have blocked.- "rule_excluded_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",@@ -424,75 +452,86 @@ class TestCoarsenTrigger:],)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, **({"last_repartition_at": _days_ago_iso(0)} 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"- )- elif case == "rule_excluded_oom":- ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(- team_id=schema.team_id,- schema=schema,- run_id="run-1",- self_phase="extract",- self_report_age_at_death_seconds=1.0,- )+ self._record_oom(schema)- 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)+ self._detect_over_fragmented(team, schema, coarsen_enabled=case != "flag_disabled")- schema.refresh_from_db()assert schema.repartition_pending is None+ @override_settings(DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS=3, DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS=3)+ def test_a_death_the_rules_blame_on_infrastructure_does_not_block_coarsening(self, team):+ # A nightly restart takes out hundreds of unrelated schemas at once, which says nothing about+ # any one table's merge memory. Blocking on it froze the whole over-split backlog.+ schema = self._fragmented_schema(team)+ self._record_oom(schema, self_phase="merge", self_report_age_at_death_seconds=1.0, self_peak_buffer_bytes=1024)+ self._record_fleet_wide_burst(team)++ self._detect_over_fragmented(team, schema)++ assert schema.repartition_pending is not None+ assert schema.repartition_pending["trigger_reason"] == "coarsening"++ def test_an_oom_that_predates_the_last_rewrite_still_blocks_coarsening(self, team):+ # `recent_count` floors its window at `last_repartition_at`, which would hide this death.+ # Coarsening undoes that rewrite, so the OOM that justified it is the evidence that matters.+ schema = self._fragmented_schema(team, last_repartition_at=_days_ago_iso(8))+ self._record_oom(schema, days_ago=10)++ self._detect_over_fragmented(team, schema)++ assert schema.repartition_pending is None++ @override_settings(DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS=3, DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS=3)+ @pytest.mark.parametrize(+ "phase,days_ago,blocks",+ [+ # A burst window is where a self-inflicted merge death hides, so the backstop looks past+ # the infrastructure verdict at the peak the merge itself reported.+ ("merge", 0, True),+ # Scoped to merges: an extract holding 200 MB says nothing about the merge working set.+ ("extract", 0, False),+ # Scoped to the window too, or one big merge death would freeze the layout forever.+ ("merge", 20, False),+ ],+ )+ def test_the_backstop_blocks_only_big_recent_merge_deaths(self, team, phase, days_ago, blocks):+ schema = self._fragmented_schema(team)+ self._record_oom(+ schema,+ days_ago=days_ago,+ self_phase=phase,+ self_report_age_at_death_seconds=1.0,+ self_peak_buffer_bytes=200 * 1024 * 1024,+ )+ self._record_fleet_wide_burst(team)++ self._detect_over_fragmented(team, schema)++ assert (schema.repartition_pending is None) is blocks+@pytest.mark.parametrize("case,expected_reason",[- ("rule_excluded_oom", "oom_within_free_window"),+ ("unexplained_oom", "oom_within_free_window"),("fresh_layout", "layout_too_young"),("flag_disabled", "flag_disabled"),],)def test_declining_to_coarsen_records_which_gate_stopped_it(self, team, case, expected_reason):- # A stalled rollout is otherwise invisible: every gate returns silently, so "the flag reached- # nobody" and "no table was eligible" look identical from outside. The reason label is what- # tells those apart without shell access to a customer's tables.schema = self._fragmented_schema(- team,- **(- {"last_repartition_at": datetime.datetime.now(datetime.UTC).isoformat()}- if case == "fresh_layout"- else {}- ),+ team, **({"last_repartition_at": _days_ago_iso(0)} if case == "fresh_layout" else {}))- if case == "rule_excluded_oom":- ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(- team_id=schema.team_id,- schema=schema,- run_id="run-1",- self_phase="extract",- self_report_age_at_death_seconds=1.0,- )+ if case == "unexplained_oom":+ # Past the split trigger's 7-day window, so its cheap short-circuit passes and the 14-day+ # coarsening gate is what stops it. Only a death in that gap reaches the longer window.+ self._record_oom(schema, days_ago=10)- 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"),- patch.object(ctrl, "DELTA_COARSEN_DECLINE_TOTAL") as decline_metric,- ):- self._detect(team, schema, delta)+ with patch.object(ctrl, "DELTA_COARSEN_DECLINE_TOTAL") as decline_metric:+ self._detect_over_fragmented(team, schema, coarsen_enabled=case != "flag_disabled")assert decline_metric.labels.call_args.kwargs == {"reason": expected_reason}@@ -500,26 +539,11 @@ class TestCoarsenTrigger:# 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"- )+ schema = self._fragmented_schema(team, last_repartition_at=_days_ago_iso(0), coarsen_requested=_NOMINATION)+ self._record_oom(schema)- 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)+ self._detect_over_fragmented(team, schema, coarsen_enabled=False)- schema.refresh_from_db()pending = schema.repartition_pendingassert pending is not Noneassert pending["trigger_reason"] == "coarsening_requested"@@ -530,23 +554,11 @@ class TestCoarsenTrigger:# 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"},- )+ schema = self._fragmented_schema(team, coarsen_requested=_NOMINATION)- 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)+ with patch.object(ExternalDataSchema, "set_repartition_pending", side_effect=RuntimeError("pooler dropped")):+ self._detect_over_fragmented(team, schema, coarsen_enabled=False)- schema.refresh_from_db()assert schema.repartition_pending is Noneassert schema.coarsen_requested is not None, "a failed staging must not consume the nomination"@@ -559,21 +571,12 @@ class TestCoarsenTrigger:partition_mode="datetime",partition_format="hour",partitioning_keys=["created_at"],- coarsen_requested={"requested_at": "2026-08-03T00:00:00+00:00", "requested_by": "danielc"},+ coarsen_requested=_NOMINATION,)+ buckets = [f"2024-01-01T{hour:02d}" for hour in range(15)] + ["1970-01"]- 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)+ self._detect_over_fragmented(team, schema, coarsen_enabled=False, buckets=buckets)- schema.refresh_from_db()assert schema.repartition_pending is Noneassert schema.coarsen_requested is None