Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): OOM-driven repartition and delta maintenance (#68639)

Tom Owers906d86422625
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 56da25eeba0a..25f22483f781 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -146,6 +146,7 @@ rules:
|ExportedRecording
|ExternalDataJob
|ExternalDataSchema
+ |ExternalDataSchemaOOMEvent
|ExternalDataSource
|FeatureFlag
|TeamExperimentsConfig
@@ -429,6 +430,7 @@ rules:
|ExportedRecording
|ExternalDataJob
|ExternalDataSchema
+ |ExternalDataSchemaOOMEvent
|ExternalDataSource
|FeatureFlag
|TeamExperimentsConfig
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.py
index 73b78d0a7a6c..293a6735f880 100644
--- a/posthog/settings/data_warehouse.py
+++ b/posthog/settings/data_warehouse.py
@@ -20,13 +20,30 @@ USE_LOCAL_SETUP = TEST or (DEBUG and len(os.getenv("OBJECT_STORAGE_ENDPOINT", "h
PYARROW_DEBUG_LOGGING = get_from_env("PYARROW_DEBUG_LOGGING", False, type_cast=str_to_bool)
# At-rest (compressed) byte budget per Delta partition. The auto-repartition controller rewrites a
-# table into a finer scheme once its largest partition exceeds this. delta-rs merges need ~20x the
-# partition's at-rest size in memory, so ~1 GB keeps worst-case merge memory (~20 GB) under the
-# 29 GB worker limit with headroom.
+# table into a finer scheme once its largest partition exceeds this. delta-rs merges decompress the
+# whole target partition into an Arrow working set — roughly ~20x the at-rest size, and far more for
+# wide nested-JSON columns. Worker pods are multi-tenant (a single OOM kills every co-tenant activity),
+# so the budget must leave headroom for concurrent merges under the 29 GB pod limit, not just fit one.
+# ~0.5 GB → ~10 GB worst-case working set, leaving room for other activities on the same pod.
+# The wide-column case (where the ~20x multiplier under-counts) is caught empirically by the OOM-history
+# override below rather than by trying to model per-column expansion here.
DATA_WAREHOUSE_TARGET_PARTITION_BYTES = get_from_env(
- "DATA_WAREHOUSE_TARGET_PARTITION_BYTES", 1_000_000_000, type_cast=int
+ "DATA_WAREHOUSE_TARGET_PARTITION_BYTES", 500_000_000, type_cast=int
)
+# A schema that records at least this many sync OOMs within the lookback window is force-repartitioned
+# even when its largest partition is within the size budget — its real merge working set is bigger than
+# the compressed at-rest size implies (e.g. wide nested-JSON columns). See ExternalDataSchemaOOMEvent.
+DATA_WAREHOUSE_REPARTITION_OOM_THRESHOLD = get_from_env("DATA_WAREHOUSE_REPARTITION_OOM_THRESHOLD", 3, type_cast=int)
+DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS = get_from_env(
+ "DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS", 7, 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.
+DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD = get_from_env("DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD", 100, type_cast=int)
+
GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL")
GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY")
GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID")
diff --git a/products/warehouse_sources/backend/migrations/0058_externaldataschemaoomevent.py b/products/warehouse_sources/backend/migrations/0058_externaldataschemaoomevent.py
new file mode 100644
index 000000000000..0583d3d6938d
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0058_externaldataschemaoomevent.py
@@ -0,0 +1,53 @@
+import django.db.models.manager
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1247_oauthaccesstoken_token_idx"),
+ ("warehouse_sources", "0057_alter_externaldatasource_source_type_and_more"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ExternalDataSchemaOOMEvent",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("run_id", models.CharField(blank=True, max_length=400, null=True)),
+ ("host", models.CharField(blank=True, max_length=400, null=True)),
+ ("gap_seconds", models.FloatField(blank=True, null=True)),
+ (
+ "schema",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="oom_events",
+ to="warehouse_sources.externaldataschema",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"
+ ),
+ ),
+ ],
+ options={
+ "default_manager_name": "all_teams",
+ "indexes": [
+ models.Index(fields=["schema", "created_at"], name="dwh_oom_schema_created_idx"),
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 86946c017ab5..6280b8b6be11 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0057_alter_externaldatasource_source_type_and_more
+0058_externaldataschemaoomevent
diff --git a/products/warehouse_sources/backend/models/__init__.py b/products/warehouse_sources/backend/models/__init__.py
index ebc3ca27a61a..c622c1e6036c 100644
--- a/products/warehouse_sources/backend/models/__init__.py
+++ b/products/warehouse_sources/backend/models/__init__.py
@@ -5,6 +5,7 @@ from .custom_oauth2_integration import CustomOAuth2Integration
from .external_data_job import ExternalDataJob
from .external_data_schema import ExternalDataSchema
from .external_data_source import ExternalDataSource
+from .oom_event import ExternalDataSchemaOOMEvent
from .pending_source_credential import PendingSourceCredential
from .table import DataWarehouseTable
@@ -14,6 +15,7 @@ __all__ = [
"DataWarehouseTable",
"ExternalDataJob",
"ExternalDataSchema",
+ "ExternalDataSchemaOOMEvent",
"ExternalDataSource",
"PendingSourceCredential",
"WarehouseColumnAnnotation",
diff --git a/products/warehouse_sources/backend/models/oom_event.py b/products/warehouse_sources/backend/models/oom_event.py
new file mode 100644
index 000000000000..ef1356190003
--- /dev/null
+++ b/products/warehouse_sources/backend/models/oom_event.py
@@ -0,0 +1,56 @@
+from datetime import timedelta
+from typing import TYPE_CHECKING
+
+from django.db import models
+from django.utils import timezone
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel, sane_repr
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+
+class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):
+ """Append-only log of detected sync OOMs (pod heartbeat-timeouts) for an external data schema.
+
+ Recorded once per Temporal retry attempt that follows an OOM'd attempt — a single job can OOM
+ many times before its terminal status — so this is an occurrence log, not a counter. Drives the
+ repartition trigger via `recent_count()`; kept bounded by pruning to a retention window.
+ """
+
+ # db_constraint=False on the Team FK: a real constraint takes a SHARE ROW EXCLUSIVE lock on the
+ # hot posthog_team table on create. Team scoping is enforced at the app layer by TeamScopedRootMixin.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ schema = models.ForeignKey(
+ "warehouse_sources.ExternalDataSchema", on_delete=models.CASCADE, related_name="oom_events"
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ # Context captured from the prior (OOM'd) attempt's last heartbeat.
+ run_id = models.CharField(max_length=400, null=True, blank=True)
+ host = models.CharField(max_length=400, null=True, blank=True)
+ gap_seconds = models.FloatField(null=True, blank=True)
+
+ all_teams = models.Manager() # noqa: DJ012 — both are managers, ruff misclassifies this
+
+ __repr__ = sane_repr("schema_id", "created_at")
+
+ class Meta:
+ # Django framework internals (cascade delete, related-object access, prefetch) read through
+ # `_default_manager` / `_base_manager` and expect an unfiltered manager. Point them at the plain
+ # `all_teams` so a schema delete that cascades to `oom_events` doesn't hit the fail-closed manager.
+ # `objects` (from TeamScopedRootMixin) stays fail-closed for explicit app code (recent_count / recording).
+ default_manager_name = "all_teams"
+ indexes = [
+ models.Index(fields=["schema", "created_at"], name="dwh_oom_schema_created_idx"),
+ ]
+
+ @classmethod
+ def recent_count(cls, schema: "ExternalDataSchema", *, days: int) -> int:
+ """Number of OOM occurrences recorded for this schema within the last `days`.
+
+ `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.
+ """
+ since = timezone.now() - timedelta(days=days)
+ return cls.objects.for_team(schema.team_id).filter(schema_id=schema.pk, created_at__gte=since).count()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index 5ff2a897c18d..4fc580505bc5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -38,14 +38,15 @@ The manual flow above re-pulls every row from the source. We also have an automa
How it works:
-- **Detection.** After each sync, the controller measures per-partition bytes from the Delta log (`get_add_actions` — no S3 LIST, no scan) and always records `max_partition_bytes` on the schema for observability. When the largest partition is over the budget it records a `repartition_pending` target on the schema: the next finer tier (md5 count grows, numerical size shrinks, datetime `month` → `week` → `day` → `hour`).
+- **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.
- **Rewrite.** On the next run, a pre-extraction activity streams the live Delta table one record-batch at a time, recomputes `_ph_partition_key` under the finer scheme, and writes a sibling temp table. It then does a crash-safe swap: delete live → server-side copy temp → verify row count → delete temp. Memory is bounded by batch size, independent of partition size. Temp stays the source of truth until the swap is verified, so a worker death at any point loses wasted compute, never data.
- **Safety.** The repartition is the sole writer (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), so it needs no new locking. A repartition failure never fails the sync — it's swallowed, retried on a later run, and capped at `MAX_REPARTITION_ATTEMPTS` (3) consecutive failures before it gives up and alerts.
Tuning and gating:
- Gated by the `data-warehouse-auto-repartition` feature flag plus a 24h per-table cooldown. The flag can be released to a single schema (`schema_id = <id>`) before rolling out by team/org/project.
-- The budget is tunable via the `DATA_WAREHOUSE_TARGET_PARTITION_BYTES` setting (default ~1 GB at-rest → ~20 GB worst-case merge, under the 29 GB pod limit with headroom).
+- 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.
- 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/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index f993baf90bc5..d1032e31cfe9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -158,6 +158,24 @@ def report_heartbeat_timeout(inputs: "ImportDataActivityInputs", logger: Filteri
"attempt": info.attempt,
},
)
+
+ # Durable per-occurrence OOM record for the repartition trigger to read. Best-effort:
+ # a write failure here must never disrupt the sync.
+ try:
+ from products.warehouse_sources.backend.models.oom_event import ( # noqa: PLC0415 — Django models must not be imported at this activity module's load time
+ ExternalDataSchemaOOMEvent,
+ )
+
+ if inputs.schema_id is not None:
+ ExternalDataSchemaOOMEvent.objects.for_team(inputs.team_id).create(
+ team_id=inputs.team_id,
+ schema_id=inputs.schema_id,
+ run_id=inputs.run_id,
+ host=last_heartbeat_host,
+ gap_seconds=gap_between_beats,
+ )
+ except Exception as record_error:
+ logger.debug(f"Failed to record OOM event for schema {inputs.schema_id}: {record_error}")
else:
logger.debug("Last heartbeat was within the heartbeat timeout window. No action needed.")
except Exception as e:
@@ -258,6 +276,96 @@ async def handle_reset_or_full_refresh(
await database_sync_to_async_pool(schema.update_sync_type_config_for_reset_pipeline)()
+async def handle_corrupted_delta_log(
+ schema: "ExternalDataSchema",
+ job: "ExternalDataJob",
+ delta_table_helper: DeltaTableHelper,
+ logger: FilteringBoundLogger,
+) -> bool:
+ """Detect and revive a Delta table whose `_delta_log` is unreadable, before extraction.
+
+ Interrupted repartition swaps and OOM-crashed merges can leave `_delta_log` inconsistent (open raises
+ DeltaError / FileNotFoundError), after which every sync fails to open the table and loops forever.
+ Runs before extraction so the table self-heals in the same run:
+
+ - Salvage: an interrupted repartition swap that left a `ready` temp table is finished from temp (no
+ re-pull from source).
+ - Otherwise the table is reset so this run rebuilds it from source, and the job is marked
+ non-billable — the corruption is our fault, not the customer's.
+
+ Returns True if a revive happened. Best-effort: any failure here must not block the sync.
+ """
+ try:
+ if not await delta_table_helper.is_table_corrupted():
+ return False
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+ await logger.awarning(
+ f"handle_corrupted_delta_log: unreadable delta log detected, reviving schema_id={schema.id}",
+ schema_id=str(schema.id),
+ )
+
+ # Salvage first: finish an interrupted repartition swap from its `ready` temp table (delete the corrupt
+ # live, copy temp into place) rather than re-pull from source. `_resume_swap_with_missing_live` skips
+ # and clears the markers when temp is also gone (the terminal corrupt state), so we then fall to reset.
+ swap = schema.repartition_swap
+ if swap and swap.get("state") == "ready" and swap.get("temp_uri") and swap.get("live_uri"):
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import ( # noqa: PLC0415 — deferred to avoid an import cycle with the repartition modules
+ _resume_swap_with_missing_live,
+ )
+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table import ( # noqa: PLC0415 — deferred to avoid an import cycle with the repartition modules
+ RepartitionTarget,
+ _target_from_schema,
+ )
+
+ try:
+ target = (
+ RepartitionTarget.from_dict(schema.repartition_pending)
+ if schema.repartition_pending is not None
+ else _target_from_schema(schema)
+ )
+ result = await _resume_swap_with_missing_live(
+ helper=delta_table_helper,
+ schema=schema,
+ target=target,
+ temp_uri=swap["temp_uri"],
+ live_uri=swap["live_uri"],
+ storage_options=delta_table_helper._get_credentials(),
+ logger=logger,
+ )
+ if result.get("outcome") == "completed":
+ await logger.ainfo(
+ f"handle_corrupted_delta_log: salvaged from interrupted swap schema_id={schema.id}",
+ schema_id=str(schema.id),
+ )
+ return True
+ except Exception as e:
+ capture_exception(e)
+ await logger.aexception(f"handle_corrupted_delta_log: salvage failed, resetting: {e}", exc_info=e)
+
+ # Reset + rebuild from source in this run, marked non-billable — we caused the corruption.
+ from products.warehouse_sources.backend.models.external_data_schema import ( # noqa: PLC0415 — Django model import kept off this activity module's load path
+ update_sync_type_config_keys,
+ )
+
+ await delta_table_helper.reset_table()
+ await database_sync_to_async_pool(schema.update_sync_type_config_for_reset_pipeline)()
+ await database_sync_to_async_pool(update_sync_type_config_keys)(
+ schema.id, schema.team_id, removes=["repartition_pending", "repartition_swap"]
+ )
+ if job.billable:
+ job.billable = False
+ await database_sync_to_async_pool(job.save)(update_fields=["billable"])
+
+ await logger.awarning(
+ f"handle_corrupted_delta_log: reset corrupt table for non-billable rebuild schema_id={schema.id}",
+ schema_id=str(schema.id),
+ )
+ return True
+
+
def cleanup_memory(pa_memory_pool: pa.MemoryPool, py_table: pa.Table | None = None) -> None:
if py_table is not None:
del py_table
@@ -409,20 +517,36 @@ async def run_pre_write_defensive_compact(
) -> None:
"""Best-effort pre-write compact + vacuum at the start of a sync run.
- Triggers `DeltaTableHelper.compact_if_fragmented` so a sync that arrived at a
- fragmented Delta target (e.g. because earlier attempts failed before reaching
- `_post_run_operations`) cleans up before adding more small files — keeping the
- subsequent per-partition merge scans cheap. Wrapped in try/except so a
- compaction failure never blocks the actual sync; the original error path is
- unaffected.
-
- Used by both `PipelineNonDLT.run` (v2) and `PipelineV3.run` to keep the
- behaviour identical across pipelines without each having to know how to look
- up `partition_count` or how to swallow compaction errors.
+ Delegates to `DeltaTableHelper.run_maintenance`, which compacts a fragmented Delta
+ target (a sync that arrived fragmented because earlier attempts failed before
+ reaching `_post_run_operations` — keeping the subsequent per-partition merge scans
+ cheap) and otherwise vacuums on a commit-count cadence so a table that OOMs its merge
+ every run and never reaches post-load compaction still sheds tombstones (the
+ ~99%-dead-file tables). The helper returns the single vacuum watermark to persist, so
+ this function is the sole writer of `last_vacuum_version`. Wrapped in try/except so a
+ maintenance failure never blocks the actual sync; the original error path is unaffected.
+
+ Used by both `PipelineNonDLT.run` (v2) and `PipelineV3.run` to keep the behaviour
+ identical across pipelines without each having to know how to look up `partition_count`
+ or how to swallow maintenance errors.
"""
try:
+ from products.warehouse_sources.backend.models.external_data_schema import ( # noqa: PLC0415 — Django model import kept off this activity module's load path
+ update_sync_type_config_keys,
+ )
+
partition_count_for_compact = schema.partition_count or resource.partition_count
- await delta_table_helper.compact_if_fragmented(partition_count=partition_count_for_compact)
+ last_vacuum_version = (schema.sync_type_config or {}).get("last_vacuum_version")
+ commit_threshold = int(getattr(settings, "DATA_WAREHOUSE_VACUUM_COMMIT_THRESHOLD", 100))
+ new_version = await delta_table_helper.run_maintenance(
+ partition_count=partition_count_for_compact,
+ last_vacuum_version=last_vacuum_version,
+ commit_threshold=commit_threshold,
+ )
+ if new_version is not None and new_version != last_vacuum_version:
+ await database_sync_to_async_pool(update_sync_type_config_keys)(
+ schema.id, schema.team_id, updates={"last_vacuum_version": new_version}
+ )
except Exception as e:
capture_exception(e)
- await logger.aexception(f"Pre-write compaction failed: {e}", exc_info=e)
+ await logger.aexception(f"Pre-write maintenance failed: {e}", exc_info=e)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
index f2176a7c7d29..807936fda15b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
@@ -1,9 +1,20 @@
+import uuid
+from datetime import UTC, datetime, timedelta
+
import pytest
+from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
+from asgiref.sync import async_to_sync
from parameterized import parameterized
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
+ handle_corrupted_delta_log,
+ report_heartbeat_timeout,
run_pre_write_defensive_compact,
)
@@ -13,7 +24,7 @@ _EXTRACT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipe
class TestRunPreWriteDefensiveCompact:
@parameterized.expand(
[
- # (schema_partition_count, resource_partition_count, expected_passed_to_compact)
+ # (schema_partition_count, resource_partition_count, expected_passed_to_run_maintenance)
("schema_value_wins", 10, 72, 10),
("falls_back_to_resource", None, 72, 72),
("both_none_passes_none", None, None, None),
@@ -23,30 +34,157 @@ class TestRunPreWriteDefensiveCompact:
async def test_resolves_partition_count_schema_over_resource(
self, _name: str, schema_count: int | None, resource_count: int | None, expected: int | None
):
- compact = AsyncMock(return_value=False)
- helper = MagicMock(compact_if_fragmented=compact)
+ run_maintenance = AsyncMock(return_value=None)
+ helper = MagicMock(run_maintenance=run_maintenance)
await run_pre_write_defensive_compact(
helper,
- MagicMock(partition_count=schema_count),
+ MagicMock(partition_count=schema_count, sync_type_config={}),
MagicMock(partition_count=resource_count),
MagicMock(aexception=AsyncMock()),
)
- compact.assert_awaited_once_with(partition_count=expected)
+ assert run_maintenance.await_args is not None
+ assert run_maintenance.await_args.kwargs["partition_count"] == expected
@pytest.mark.asyncio
- async def test_swallows_compaction_failure(self):
- # The whole point of the wrapper: a compaction error must never propagate and
+ async def test_swallows_maintenance_failure(self):
+ # The whole point of the wrapper: a maintenance error must never propagate and
# block the sync — it's captured and logged instead.
- compact = AsyncMock(side_effect=RuntimeError("compaction blew up"))
- helper = MagicMock(compact_if_fragmented=compact)
+ helper = MagicMock(run_maintenance=AsyncMock(side_effect=RuntimeError("maintenance blew up")))
logger = MagicMock(aexception=AsyncMock())
+ schema = MagicMock(partition_count=5, sync_type_config={})
with patch(f"{_EXTRACT_MODULE}.capture_exception") as mock_capture:
- await run_pre_write_defensive_compact(
- helper, MagicMock(partition_count=5), MagicMock(partition_count=None), logger
- )
+ await run_pre_write_defensive_compact(helper, schema, MagicMock(partition_count=None), logger)
mock_capture.assert_called_once()
logger.aexception.assert_awaited_once()
+
+
+class TestReportHeartbeatTimeoutRecording(BaseTest):
+ def _schema(self) -> 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="orders")
+
+ def _info(self, *, attempt: int, gap_seconds: float) -> MagicMock:
+ info = MagicMock()
+ info.heartbeat_timeout = timedelta(minutes=2)
+ info.attempt = attempt
+ scheduled = datetime(2026, 7, 6, 12, 0, 0, tzinfo=UTC)
+ info.current_attempt_scheduled_time = scheduled
+ info.heartbeat_details = [{"host": "pod-abc", "ts": scheduled.timestamp() - gap_seconds}]
+ return info
+
+ @parameterized.expand(
+ [
+ # A gap past the 2-min heartbeat timeout is a detected OOM → one durable row.
+ ("oom_records_row", 300, 1),
+ # Within the timeout is a normal retry: the write must stay inside the OOM branch, not fire.
+ ("within_timeout_records_nothing", 30, 0),
+ ]
+ )
+ def test_records_one_row_per_detected_oom(self, _name: str, gap_seconds: float, expected_rows: int) -> None:
+ schema = self._schema()
+ inputs = MagicMock(team_id=self.team.pk, schema_id=schema.id, source_id=str(uuid.uuid4()), run_id="run-1")
+
+ with (
+ patch(f"{_EXTRACT_MODULE}.activity.info", return_value=self._info(attempt=2, gap_seconds=gap_seconds)),
+ patch(f"{_EXTRACT_MODULE}.posthoganalytics"),
+ ):
+ report_heartbeat_timeout(inputs, MagicMock())
+
+ rows = ExternalDataSchemaOOMEvent.objects.for_team(self.team.pk).filter(schema_id=schema.id)
+ assert rows.count() == expected_rows
+ if expected_rows:
+ event = rows.get()
+ assert event.host == "pod-abc"
+ assert event.run_id == "run-1"
+ assert event.gap_seconds == pytest.approx(gap_seconds)
+
+
+# transaction=True: handle_corrupted_delta_log writes to the DB from the async thread pool
+# (database_sync_to_async_pool), which can't see an atomic TestCase's uncommitted rows.
[email protected]_db(transaction=True)
+class TestHandleCorruptedDeltaLog:
+ def _schema_and_job(self, team) -> tuple[ExternalDataSchema, ExternalDataJob]:
+ source = ExternalDataSource.objects.create(
+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=team, source_type="Stripe"
+ )
+ schema = ExternalDataSchema.objects.create(name="Invoice", team=team, source=source, sync_type_config={})
+ job = ExternalDataJob.objects.create(
+ team=team,
+ pipeline=source,
+ schema=schema,
+ status=ExternalDataJob.Status.RUNNING,
+ rows_synced=0,
+ billable=True,
+ )
+ return schema, job
+
+ def _logger(self) -> MagicMock:
+ return MagicMock(awarning=AsyncMock(), ainfo=AsyncMock(), aexception=AsyncMock())
+
+ def test_healthy_table_is_a_noop(self, team):
+ # Guard: a readable table must never be reset or flipped non-billable — that would nuke healthy
+ # data and stop billing the customer for a legitimate sync.
+ schema, job = self._schema_and_job(team)
+ helper = MagicMock(is_table_corrupted=AsyncMock(return_value=False), reset_table=AsyncMock())
+
+ result = async_to_sync(handle_corrupted_delta_log)(schema, job, helper, self._logger())
+
+ assert result is False
+ helper.reset_table.assert_not_awaited()
+ job.refresh_from_db()
+ assert job.billable is True
+
+ def test_corrupt_table_without_salvage_resets_non_billable(self, team):
+ # A corrupt table with no recoverable repartition swap is reset for an in-run rebuild, and the job
+ # is marked non-billable — the corruption is our fault, so the customer isn't charged for the rebuild.
+ schema, job = self._schema_and_job(team) # sync_type_config has no repartition_swap → no salvage path
+ helper = MagicMock(is_table_corrupted=AsyncMock(return_value=True), reset_table=AsyncMock())
+
+ result = async_to_sync(handle_corrupted_delta_log)(schema, job, helper, self._logger())
+
+ assert result is True
+ helper.reset_table.assert_awaited_once()
+ job.refresh_from_db()
+ assert job.billable is False
+
+ def test_corrupt_table_with_ready_swap_is_salvaged(self, team):
+ # A corrupt table whose interrupted repartition swap left a `ready` temp table is finished from temp
+ # rather than reset — the customer's data is recovered without a rebuild, so reset_table never runs
+ # and the job stays billable. Guards the salvage-from-temp branch against regressing to a reset.
+ schema, job = self._schema_and_job(team)
+ schema.sync_type_config = {
+ "repartition_swap": {"state": "ready", "temp_uri": "s3://bucket/temp", "live_uri": "s3://bucket/live"}
+ }
+ schema.save(update_fields=["sync_type_config"])
+ helper = MagicMock(
+ is_table_corrupted=AsyncMock(return_value=True),
+ reset_table=AsyncMock(),
+ _get_credentials=MagicMock(return_value={}),
+ )
+
+ repartition_module = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition"
+ repartition_table_module = (
+ "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.repartition_table"
+ )
+ resume = AsyncMock(return_value={"outcome": "completed"})
+ with (
+ patch(f"{repartition_module}._resume_swap_with_missing_live", resume),
+ patch(f"{repartition_table_module}._target_from_schema", return_value=MagicMock()),
+ ):
+ result = async_to_sync(handle_corrupted_delta_log)(schema, job, helper, self._logger())
+
+ assert result is True
+ resume.assert_awaited_once()
+ helper.reset_table.assert_not_awaited()
+ job.refresh_from_db()
+ assert job.billable is True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/batcher.py
index e93eb0b0b7bf..3b415063e089 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/batcher.py
@@ -55,8 +55,19 @@ def _column_payload_bytes(col: pa.ChunkedArray) -> int:
if pa.types.is_list(col_type):
elements = int(pc.sum(pc.list_value_length(col)).as_py() or 0)
return elements + col_length * 4
- # Fixed-width primitives expose bit_width; variable-length / nested types raise -> 0.
- # Known limitation: deeply-nested struct/map and sub-byte bool columns undercount to 0 (we only bound large string/JSON payloads, the actual OOM driver).
+ if pa.types.is_struct(col_type):
+ # Recurse into child fields so a nested struct (e.g. a Mongo document carried under `data`) is
+ # counted instead of undercounting to 0 — otherwise the per-table byte split never sees the
+ # payload that actually drives the merge's memory. `flatten()` yields one ChunkedArray per field.
+ # Guarded like the fixed-width branch below: an unexpected flatten failure degrades to 0 rather
+ # than propagating and breaking size accounting for the whole table.
+ try:
+ return sum(_column_payload_bytes(child) for child in col.flatten())
+ except Exception:
+ return 0
+ # Fixed-width primitives expose bit_width; variable-length / other nested types raise -> 0.
+ # Known limitation: map and sub-byte bool columns still undercount to 0 (we bound large string/JSON
+ # and struct payloads, the actual OOM drivers).
try:
bit_width = col_type.bit_width
except (ValueError, AttributeError):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
index 3e012b3abc91..5a281f3e9eeb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
@@ -246,6 +246,32 @@ class DeltaTableHelper:
return None
+ async def is_table_corrupted(self) -> bool:
+ """True when the Delta log exists but the table can't be opened (DeltaError / FileNotFoundError).
+
+ The signature of a `_delta_log` left inconsistent by an interrupted repartition swap or an
+ OOM-crashed merge — after which every sync fails to open the table and loops. Non-destructive:
+ only attempts an open (bypassing the get_delta_table cache). A table that simply doesn't exist is
+ not corrupt; an unknown open error is not classified as corrupt, so a transient failure never
+ triggers a destructive revive.
+ """
+ delta_uri = await self._get_delta_table_uri()
+ storage_options = self._get_credentials()
+
+ is_delta = await asyncio.to_thread(
+ deltalake.DeltaTable.is_deltatable, table_uri=delta_uri, storage_options=storage_options
+ )
+ if not is_delta:
+ return False
+
+ try:
+ await asyncio.to_thread(deltalake.DeltaTable, table_uri=delta_uri, storage_options=storage_options)
+ return False
+ except (deltalake.exceptions.DeltaError, FileNotFoundError):
+ return True
+ except Exception:
+ return False
+
async def reset_table(self):
delta_uri = await self._get_delta_table_uri()
@@ -650,23 +676,65 @@ class DeltaTableHelper:
"""
return await self.has_commit_with_metadata({"run_uuid": run_uuid, "batch_index": str(batch_index)})
- async def compact_table(self) -> None:
+ async def vacuum_table(self) -> None:
table = await self.get_delta_table()
if table is None:
raise Exception("Deltatable not found")
- await self._logger.adebug("Compacting table...")
- compact_stats = await asyncio.to_thread(table.optimize.compact)
- await self._logger.adebug(json.dumps(compact_stats))
-
await self._logger.adebug("Vacuuming table...")
vacuum_stats = await asyncio.to_thread(
table.vacuum, retention_hours=24, enforce_retention_duration=False, dry_run=False
)
await self._logger.adebug(json.dumps(vacuum_stats))
+ async def compact_table(self) -> None:
+ table = await self.get_delta_table()
+ if table is None:
+ raise Exception("Deltatable not found")
+
+ await self._logger.adebug("Compacting table...")
+ compact_stats = await asyncio.to_thread(table.optimize.compact)
+ await self._logger.adebug(json.dumps(compact_stats))
+
+ await self.vacuum_table()
await self._logger.adebug("Compacting and vacuuming complete")
+ async def vacuum_if_stale(self, last_vacuum_version: int | None, commit_threshold: int) -> int | None:
+ """Vacuum tombstoned files once enough commits have accrued since the last vacuum.
+
+ Decoupled from merge success (called pre-write) so a table that OOMs its merge every run still
+ gets cleaned — the post-load compaction never runs for it, which is how tables reach ~99% dead
+ files. Vacuum only deletes dead files (an S3 LIST + delete), so unlike `compact_table`'s
+ `optimize.compact` (which rewrites partitions) it is memory-safe even on an oversized table.
+
+ Uses the delta version (commit count) as a cheap proxy for tombstone accumulation — no S3 LIST to
+ decide. Returns the current version to persist as the new watermark when it vacuumed, or on first
+ encounter (seeding the watermark without vacuuming, to avoid a synchronized vacuum wave on deploy);
+ None when nothing changed.
+ """
+ table = await self.get_delta_table()
+ if table is None:
+ return None
+
+ version = await asyncio.to_thread(table.version)
+ if last_vacuum_version is None:
+ # First encounter: seed the watermark without vacuuming so existing tables clean up gradually
+ # over the next `commit_threshold` commits rather than all vacuuming at once on deploy.
+ return version
+
+ commits_since = version - last_vacuum_version
+ if commits_since < commit_threshold:
+ await self._logger.adebug(
+ f"vacuum_if_stale: skipping, {commits_since} commits since last vacuum (< {commit_threshold})"
+ )
+ return None
+
+ await self._logger.ainfo(
+ f"vacuum_if_stale: {commits_since} commits since last vacuum (>= {commit_threshold}), vacuuming"
+ )
+ await self.vacuum_table()
+ return version
+
async def compact_if_fragmented(
self,
partition_count: int | None,
@@ -709,3 +777,29 @@ class DeltaTableHelper:
await self._logger.ainfo(f"compact_if_fragmented: triggering compact ({stats})")
await self.compact_table()
return True
+
+ async def run_maintenance(
+ self,
+ partition_count: int | None,
+ last_vacuum_version: int | None,
+ commit_threshold: int,
+ ) -> int | None:
+ """Single pre-write maintenance entry point: compact if fragmented, else vacuum on commit cadence.
+
+ The two triggers are orthogonal — fragmentation (active file count) vs. commit cadence (tombstone
+ accrual) — but they share one outcome, the vacuum watermark. `compact_if_fragmented` already
+ vacuums as part of compaction, so when it runs it supersedes the cadence vacuum (no double vacuum
+ in one run) and the watermark advances to the post-compaction version. When nothing was fragmented,
+ fall through to `vacuum_if_stale`. Returns the single delta version to persist as the new
+ `last_vacuum_version` watermark, or None when nothing changed; the caller is the sole writer of
+ the watermark so it lives in exactly one place.
+ """
+ compacted = await self.compact_if_fragmented(partition_count=partition_count)
+ if compacted:
+ table = await self.get_delta_table()
+ if table is None:
+ return None
+ # Compaction (which vacuumed) added a commit, advancing the version; reset the cadence
+ # watermark to it so the next vacuum is measured from this cleanup, not the old baseline.
+ return await asyncio.to_thread(table.version)
+ return await self.vacuum_if_stale(last_vacuum_version, commit_threshold)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
index 5fa7ebc022b1..14c7b54acf24 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
cdp_producer_clear_chunks,
cleanup_memory,
finalize_desc_sort_incremental_value,
+ handle_corrupted_delta_log,
handle_reset_or_full_refresh,
reset_rows_synced_if_needed,
run_pre_write_defensive_compact,
@@ -234,6 +235,10 @@ class PipelineNonDLT(Generic[ResumableData]):
row_count = 0
chunk_index = 0
+ # Revive a corrupt-`_delta_log` table (from an interrupted repartition swap or OOM-crashed
+ # merge) before extraction so it self-heals in this run instead of looping forever.
+ await handle_corrupted_delta_log(self._schema, self._job, self._delta_table_helper, self._logger)
+
await handle_reset_or_full_refresh(
self._reset_pipeline, should_resume, self._schema, self._delta_table_helper, self._logger
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.py
index d61eef1c745a..b03cef3ecf25 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition_controller.py
@@ -24,6 +24,7 @@ from posthog.utils import get_machine_id
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
measure_partition_bytes,
select_repartition_target,
@@ -47,7 +48,15 @@ MAX_REPARTITION_ATTEMPTS = 3
def target_partition_bytes() -> int:
- return int(getattr(settings, "DATA_WAREHOUSE_TARGET_PARTITION_BYTES", 1_000_000_000))
+ return int(getattr(settings, "DATA_WAREHOUSE_TARGET_PARTITION_BYTES", 500_000_000))
+
+
+def repartition_oom_threshold() -> int:
+ return int(getattr(settings, "DATA_WAREHOUSE_REPARTITION_OOM_THRESHOLD", 3))
+
+
+def repartition_oom_window_days() -> int:
+ return int(getattr(settings, "DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS", 7))
def is_auto_repartition_enabled(schema: ExternalDataSchema) -> bool:
@@ -150,26 +159,50 @@ async def maybe_flag_for_repartition(
await asyncio.to_thread(schema.record_partition_measurement, max_bytes)
budget = target_partition_bytes()
- if max_bytes <= budget:
+ over_budget = max_bytes > budget
+
+ # Hybrid trigger: a table that has actually OOM'd repeatedly is repartitioned even when its
+ # largest partition looks within budget — the compressed at-rest size under-counts the merge's
+ # real working set (e.g. wide nested-JSON columns that decompress far more than typical data).
+ # Only query the OOM log when the size check didn't already trip: an over-budget table
+ # repartitions regardless, so the count would only feed observability props there — skip the
+ # per-sync indexed COUNT for it and report 0.
+ if over_budget:
+ oom_count = 0
+ oom_triggered = False
+ else:
+ oom_count = await asyncio.to_thread(
+ ExternalDataSchemaOOMEvent.recent_count, schema, days=repartition_oom_window_days()
+ )
+ oom_triggered = oom_count >= repartition_oom_threshold()
+
+ if not over_budget and not oom_triggered:
await logger.adebug(
- f"repartition: not needed, largest partition within budget schema_id={schema.id} "
- f"max_partition_bytes={max_bytes} budget_bytes={budget} partition_count={len(partition_bytes)}",
+ f"repartition: not needed, within budget and no repeated OOMs schema_id={schema.id} "
+ f"max_partition_bytes={max_bytes} budget_bytes={budget} recent_oom_count={oom_count} "
+ f"partition_count={len(partition_bytes)}",
schema_id=str(schema.id),
max_partition_bytes=max_bytes,
budget_bytes=budget,
+ recent_oom_count=oom_count,
partition_count=len(partition_bytes),
)
return
+ trigger_reason = "proactive_threshold" if over_budget else "oom_history"
+
if enabled is None:
enabled = await asyncio.to_thread(is_auto_repartition_enabled, schema)
if not enabled:
await logger.adebug(
- f"repartition: over budget but skipped, controller disabled by feature flag "
- f"schema_id={schema.id} max_partition_bytes={max_bytes} budget_bytes={budget}",
+ f"repartition: needs repartition but skipped, controller disabled by feature flag "
+ f"schema_id={schema.id} trigger_reason={trigger_reason} max_partition_bytes={max_bytes} "
+ f"budget_bytes={budget} recent_oom_count={oom_count}",
schema_id=str(schema.id),
+ trigger_reason=trigger_reason,
max_partition_bytes=max_bytes,
budget_bytes=budget,
+ recent_oom_count=oom_count,
)
return
@@ -198,16 +231,27 @@ async def maybe_flag_for_repartition(
)
return
- target, reason = select_repartition_target(schema, partition_bytes, budget)
+ # 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)
+ target, reason = select_repartition_target(schema, partition_bytes, split_budget)
if target is None:
- # Over budget but nothing finer to do (datetime at hour, numerical can't shrink, unpartitionable).
+ # Needs repartition but nothing finer to do (datetime at hour, numerical can't shrink, unpartitionable).
# `reason` is reported on the metric + event so a skipped table is diagnosable.
DELTA_REPARTITION_SKIP_TOTAL.labels(team_id=str(schema.team_id), reason=reason).inc()
props = base_event_props(schema, source, str(job.id))
- props.update({"max_partition_bytes_before": max_bytes, "reason": reason})
+ props.update(
+ {
+ "max_partition_bytes_before": max_bytes,
+ "reason": reason,
+ "trigger_reason": trigger_reason,
+ "recent_oom_count": oom_count,
+ }
+ )
await asyncio.to_thread(capture_repartition_event, "warehouse_repartition_skipped", props)
await logger.adebug(
- f"repartition: over budget but skipped, no finer partitioning target available "
+ f"repartition: needs repartition but skipped, no finer partitioning target available "
f"schema_id={schema.id} reason={reason} max_partition_bytes={max_bytes} budget_bytes={budget} "
f"partition_mode={schema.partition_mode} partition_format={schema.partition_format} "
f"partition_count={len(partition_bytes)}",
@@ -222,14 +266,15 @@ async def maybe_flag_for_repartition(
capture_exception(Exception(f"Repartition needed but skipped for schema {schema.id}: {reason}"))
return
- pending = {**target.to_dict(), "trigger_reason": "proactive_threshold", "attempts": 0}
+ pending = {**target.to_dict(), "trigger_reason": trigger_reason, "attempts": 0}
await asyncio.to_thread(schema.set_repartition_pending, pending)
props = base_event_props(schema, source, str(job.id))
props.update(
{
"max_partition_bytes_before": max_bytes,
- "trigger_reason": "proactive_threshold",
+ "trigger_reason": trigger_reason,
+ "recent_oom_count": oom_count,
"partition_mode_after": target.partition_mode,
"partition_format_after": target.partition_format,
"partition_count_after": target.partition_count,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_batcher.py
index cd3a5a126a73..d049fca8e65c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_batcher.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_batcher.py
@@ -207,7 +207,13 @@ def test_batcher_splits_buffered_list_items():
("int64", pa.array([1, 2, 3], type=pa.int64()), 24),
("bool_subbyte_is_zero", pa.array([True, False, True], type=pa.bool_()), 0),
("nulls_counted_as_zero_payload", pa.array([None, "abc"], type=pa.string()), 3 + 8),
- ("unsupported_nested_is_zero", pa.array([{"x": 1}], type=pa.struct([("x", pa.int64())])), 0),
+ # Struct now recurses into child fields (int64: 1*8=8; string "aa": 2 value + 1*4 offset = 6) so a
+ # nested Mongo-style document under `data` is bounded by the byte split instead of counting as 0.
+ (
+ "struct_counts_child_payload",
+ pa.array([{"x": 1, "s": "aa"}], type=pa.struct([("x", pa.int64()), ("s", pa.string())])),
+ 8 + 6,
+ ),
]
)
def test_column_payload_bytes(_name: str, array: pa.Array, expected: int):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
index 282acee45004..56871ff8f15f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
@@ -706,3 +706,106 @@ class TestWriteMisalignedDecimalEndToEnd:
assert set(final.column("amount").to_pylist()) == {5, 7}
closed = final.filter(pc.equal(final.column("amount"), Decimal("5.00")))
assert closed.column("valid_to").to_pylist() == [ts2]
+
+
+class TestVacuumIfStale:
+ def _helper(self) -> DeltaTableHelper:
+ return DeltaTableHelper("t", MagicMock(), MagicMock(adebug=AsyncMock(), ainfo=AsyncMock()), False)
+
+ @parameterized.expand(
+ [
+ # (last_vacuum_version, expect_vacuum, expected_return) — current version=150, threshold=100.
+ # First encounter must seed the watermark WITHOUT vacuuming (else every existing table vacuums
+ # at once on deploy); below threshold must skip (else vacuum runs every sync); at/above threshold
+ # must vacuum (else tombstones accumulate forever on tables that never reach post-load compaction).
+ ("first_encounter_seeds_no_vacuum", None, False, 150),
+ ("below_threshold_skips", 100, False, None),
+ ("at_threshold_vacuums", 50, True, 150),
+ ("above_threshold_vacuums", 40, True, 150),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_vacuum_cadence(
+ self, _name: str, last_version: int | None, expect_vacuum: bool, expected_return: int | None
+ ):
+ helper = self._helper()
+ table = MagicMock()
+ table.version = MagicMock(return_value=150)
+ with (
+ patch.object(helper, "get_delta_table", new=AsyncMock(return_value=table)),
+ patch.object(helper, "vacuum_table", new=AsyncMock()) as vacuum,
+ ):
+ result = await helper.vacuum_if_stale(last_version, 100)
+
+ assert result == expected_return
+ assert vacuum.await_count == (1 if expect_vacuum else 0)
+
+
+class TestRunMaintenance:
+ """run_maintenance is the single pre-write entry point: compaction supersedes the cadence vacuum."""
+
+ def _helper(self) -> DeltaTableHelper:
+ return DeltaTableHelper("t", MagicMock(), MagicMock(adebug=AsyncMock(), ainfo=AsyncMock()), False)
+
+ @pytest.mark.asyncio
+ async def test_compaction_supersedes_vacuum_and_advances_watermark(self):
+ # Fragmented table: compact runs (and vacuums as part of it), so the cadence vacuum is skipped —
+ # no double vacuum in one run — and the watermark advances to the post-compaction version.
+ helper = self._helper()
+ table = MagicMock(version=MagicMock(return_value=200))
+ with (
+ patch.object(helper, "compact_if_fragmented", new=AsyncMock(return_value=True)),
+ patch.object(helper, "get_delta_table", new=AsyncMock(return_value=table)),
+ patch.object(helper, "vacuum_if_stale", new=AsyncMock()) as vacuum_if_stale,
+ ):
+ result = await helper.run_maintenance(partition_count=10, last_vacuum_version=50, commit_threshold=100)
+
+ assert result == 200
+ vacuum_if_stale.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_falls_through_to_vacuum_when_not_fragmented(self):
+ # Not fragmented → no compaction; fall through to the commit-cadence vacuum and return its watermark.
+ helper = self._helper()
+ with (
+ patch.object(helper, "compact_if_fragmented", new=AsyncMock(return_value=False)),
+ patch.object(helper, "vacuum_if_stale", new=AsyncMock(return_value=150)) as vacuum_if_stale,
+ ):
+ result = await helper.run_maintenance(partition_count=10, last_vacuum_version=40, commit_threshold=100)
+
+ assert result == 150
+ vacuum_if_stale.assert_awaited_once_with(40, 100)
+
+
+class TestIsTableCorrupted:
+ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper"
+
+ def _helper(self) -> DeltaTableHelper:
+ return DeltaTableHelper("t", MagicMock(), MagicMock(adebug=AsyncMock()), False)
+
+ @parameterized.expand(
+ [
+ # (is_deltatable, open_exception, expected_corrupt) — only DeltaError/FileNotFoundError on a
+ # table whose _delta_log exists count as corrupt; a missing table or an unknown error must NOT,
+ # so we never trigger a destructive revive on a non-existent table or a transient failure.
+ ("not_a_delta_table", False, None, False),
+ ("opens_fine", True, None, False),
+ ("delta_error_is_corrupt", True, deltalake.exceptions.DeltaError("no protocol"), True),
+ ("file_not_found_is_corrupt", True, FileNotFoundError("missing data file"), True),
+ ("unknown_error_not_corrupt", True, ValueError("transient"), False),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_is_table_corrupted(self, _name: str, is_delta: bool, open_exc: Exception | None, expected: bool):
+ helper = self._helper()
+ with (
+ patch.object(helper, "_get_delta_table_uri", new=AsyncMock(return_value="s3://b/t")),
+ patch.object(helper, "_get_credentials", return_value={}),
+ patch(f"{self._MODULE}.deltalake.DeltaTable") as mock_dt,
+ ):
+ mock_dt.is_deltatable = MagicMock(return_value=is_delta)
+ if open_exc is not None:
+ mock_dt.side_effect = open_exc
+ result = await helper.is_table_corrupted()
+
+ assert result is expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
index ae51869194d1..da22d68f36b1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition_controller.py
@@ -14,6 +14,7 @@ from temporalio.testing import ActivityEnvironment
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline import repartition_controller as ctrl
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.repartition import (
@@ -159,6 +160,59 @@ class TestRepartitionDetection:
assert capture.call_args.args[0] == "warehouse_repartition_skipped"
assert capture.call_args.args[1]["reason"] == "unpartitionable_no_keys"
+ def test_unpartitioned_over_budget_with_keys_enables_partitioning(self, team):
+ # An unpartitioned table that's over budget but HAS a usable key must be flagged to become
+ # partitioned (partition_mode=None → auto-detect on the rewrite), not skipped — this is the
+ # not-partitioned → partitioned transition.
+ schema = _make_schema(team, {"primary_key_columns": ["id"]})
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_unpartitioned_delta(f"{d}/u")
+ with (
+ patch.object(ctrl, "target_partition_bytes", return_value=1),
+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),
+ patch.object(ctrl, "capture_repartition_event"),
+ ):
+ self._detect(team, schema, delta)
+
+ schema.refresh_from_db()
+ assert schema.repartition_pending is not None
+ assert schema.repartition_pending["partition_mode"] is None
+ assert schema.repartition_pending["partition_keys"] == ["id"]
+
+
+class TestRepartitionOOMHistoryTrigger:
+ 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)
+
+ @pytest.mark.parametrize("oom_count,expect_flag", [(3, True), (2, False)])
+ def test_repeated_ooms_flag_a_within_budget_table(self, team, oom_count, expect_flag):
+ # The hybrid trigger's reason for existing: a table whose compressed partition looks within
+ # budget but that keeps OOMing (its real working set is bigger — e.g. wide nested JSON) must be
+ # repartitioned once it crosses the OOM threshold, and left alone below it.
+ schema = _make_schema(
+ team,
+ {"partitioning_enabled": True, "partition_mode": "md5", "partition_count": 2, "partitioning_keys": ["id"]},
+ )
+ for _ in range(oom_count):
+ ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(team_id=schema.team_id, schema=schema)
+
+ with tempfile.TemporaryDirectory() as d:
+ delta = _write_partitioned_delta(f"{d}/t", ["0", "1"])
+ with (
+ patch.object(ctrl, "target_partition_bytes", return_value=10**12), # well within the size budget
+ patch.object(ctrl, "repartition_oom_threshold", return_value=3),
+ patch.object(ctrl, "is_auto_repartition_enabled", return_value=True),
+ patch.object(ctrl, "capture_repartition_event"),
+ ):
+ self._detect(team, schema, delta)
+
+ schema.refresh_from_db()
+ if expect_flag:
+ assert schema.repartition_pending is not None
+ assert schema.repartition_pending["trigger_reason"] == "oom_history"
+ else:
+ assert schema.repartition_pending is None
+
class TestRepartitionActivity:
def _inputs(self, team, schema: ExternalDataSchema) -> RepartitionActivityInputs:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 0f41f8f44c01..130a78782697 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
cdp_producer_clear_chunks,
cleanup_memory,
finalize_desc_sort_incremental_value,
+ handle_corrupted_delta_log,
handle_reset_or_full_refresh,
reset_rows_synced_if_needed,
run_pre_write_defensive_compact,
@@ -274,6 +275,10 @@ class PipelineV3(Generic[ResumableData]):
# overwrite handles it. Wiping the delta table mid-retry while the consumer
# is loading the previous attempt's batches causes data loss.
if self._attempt <= 1:
+ # Revive a corrupt-`_delta_log` table before extraction so it self-heals in this run
+ # instead of looping forever (an interrupted repartition swap or OOM-crashed merge).
+ await handle_corrupted_delta_log(self._schema, self._job, self._delta_table_helper, self._logger)
+
await handle_reset_or_full_refresh(
self._reset_pipeline, should_resume, self._schema, self._delta_table_helper, self._logger
)
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 827e864f7030..524d2996f9ec 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -1,11 +1,12 @@
import uuid
-from datetime import date, datetime
+from datetime import date, datetime, timedelta
import pytest
from posthog.test.base import BaseTest
from unittest.mock import patch
from django.db.models import Model
+from django.utils import timezone
from posthog.models.signals import model_activity_signal
@@ -18,6 +19,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.models.util import CLICKHOUSE_HOGQL_MAPPING, clean_type
from products.warehouse_sources.backend.types import IncrementalFieldType
@@ -192,6 +194,43 @@ class TestExternalDataSchemaActivityLogging(BaseTest):
assert schema.incremental_field_last_value == 42
+class TestExternalDataSchemaOOMEvent(BaseTest):
+ def _source(self) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+
+ 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)
+ 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(
+ created_at=timezone.now() - timedelta(days=age_days)
+ )
+ return event
+
+ def test_recent_count_windows_and_scopes_to_schema(self) -> None:
+ # A miscounted window or a dropped schema filter would force-repartition a healthy table
+ # (or never fire): recent_count must count only this schema's occurrences inside the window.
+ schema_a = self._schema("orders")
+ schema_b = self._schema("events")
+ self._oom(schema_a)
+ self._oom(schema_a)
+ self._oom(schema_a, age_days=10) # outside a 7-day window
+ self._oom(schema_b) # different schema
+
+ assert ExternalDataSchemaOOMEvent.recent_count(schema_a, days=7) == 2
+ assert ExternalDataSchemaOOMEvent.recent_count(schema_a, days=30) == 3
+ assert ExternalDataSchemaOOMEvent.recent_count(schema_b, days=7) == 1
+
+
class TestUpdateSyncTypeConfigKeys(BaseTest):
"""The locked-merge helper that keeps the CDC extract activity and concurrent API PATCHes from
clobbering each other's sync_type_config keys."""