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): hold imports while a repartition rewrite converges (#83139)

Tom Owersfeb9eb35c8ac
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 4512de717330..79e7ac076409 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -6,7 +6,7 @@ from collections.abc import Callable, Generator, Iterable
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
-from datetime import date, datetime, timedelta
+from datetime import UTC, date, datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal, Optional
from django.conf import settings
@@ -40,6 +40,12 @@ SYNC_DISABLED_JOB_ERROR = "Sync stopped because syncing was turned off"
SCHEMA_DELETED_JOB_ERROR = "Sync stopped because the table was deleted"
AUTO_DISABLED_JOB_ERROR = "Sync stopped because of an error that retrying would not fix"
+# How stale a rewrite checkpoint may get before its import hold lapses. Generous on purpose: a
+# multi-budget rewrite renews the stamp on every advancing attempt, and attempts arrive at the
+# schema's own sync cadence, which can be six hours apart. The number that matters is the ceiling on
+# how long a rewrite nobody is advancing can pause a table's imports.
+REPARTITION_HOLD_MAX_AGE = timedelta(hours=48)
+
@dataclass(frozen=True, kw_only=True)
class SyncDisableContext:
@@ -638,7 +644,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
appending from that offset instead of re-streaming from row 0, so a table too large to rewrite
in one activity converges across attempts rather than giving up terminally. Cleared once temp
is fully built (a swap is staged) or when the controller gives up. Shape:
- {"temp_uri": str, "rows_written": int, "target": dict}.
+ {"temp_uri": str, "rows_written": int, "target": dict, "live_version": int, "held_at": str}.
"""
if self.sync_type_config:
marker = self.sync_type_config.get("repartition_rewrite", None)
@@ -646,6 +652,37 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
return marker
return None
+ @property
+ def repartition_holds_import(self) -> bool:
+ """Whether an unfinished rewrite should pause this schema's imports.
+
+ A rewrite spanning several activity budgets can only resume while live stays at the Delta
+ version its checkpoint was built against, and this schema's own merge is what moves it. Left
+ alone, every sync invalidates the checkpoint the previous run wrote, so the rewrite restarts
+ from row 0 forever and the table never converges. Holding imports for the duration trades
+ staleness on one table for a rewrite that can finish.
+
+ `held_at` is restamped on every checkpoint write, so a rewrite that keeps advancing keeps
+ renewing the hold. One that stops advancing lets it lapse after `REPARTITION_HOLD_MAX_AGE`,
+ so a wedged or abandoned rewrite cannot pause ingestion indefinitely — the worst case is a
+ stale table, never a stopped one.
+ """
+ rewrite = self.repartition_rewrite
+ if not rewrite:
+ return False
+ held_at = rewrite.get("held_at")
+ if not isinstance(held_at, str):
+ # A checkpoint written before `held_at` existed. Treat it as lapsed rather than holding on
+ # a timestamp we cannot age out.
+ return False
+ try:
+ stamped = datetime.fromisoformat(held_at)
+ except ValueError:
+ return False
+ if stamped.tzinfo is None:
+ stamped = stamped.replace(tzinfo=UTC)
+ return datetime.now(UTC) - stamped < REPARTITION_HOLD_MAX_AGE
+
@property
def repartition_claim(self) -> dict[str, Any] | None:
"""The fencing claim of the newest repartition attempt: {"token", "job_id", "claimed_at"}.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
index d8661740e46b..9e12229412a5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
@@ -1077,6 +1077,10 @@ async def repartition_table_in_place(
# Fences the resume: only valid while live stays at this version (see the
# resume path). A merge that commits between attempts bumps it and invalidates.
"live_version": live_version,
+ # Stamped on every checkpoint write, so it moves forward only while the rewrite
+ # keeps advancing. The import gate reads it to decide whether this rewrite is
+ # still live enough to be worth pausing ingestion for.
+ "held_at": datetime.now(UTC).isoformat(),
},
)
raise
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.py
index 0b9160f481a0..0cf141c23506 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
@@ -42,6 +42,10 @@ if TYPE_CHECKING:
WAREHOUSE_AUTO_REPARTITION_FLAG = "data-warehouse-auto-repartition"
WAREHOUSE_AUTO_COARSEN_FLAG = "data-warehouse-auto-coarsen"
+# Gates pausing a schema's imports while a multi-budget rewrite converges. Separate from the
+# repartition flag, and off by default: repartitioning a table costs us worker time, pausing its
+# imports costs the customer freshness, so the second is not a decision the first should make.
+WAREHOUSE_REPARTITION_HOLD_FLAG = "data-warehouse-repartition-hold"
# Coarsening gates. The two directions deliberately don't meet: a table is split finer above the budget
# and merged coarser only below an eighth of it, and a coarsen aims at half the budget. So a freshly
@@ -103,6 +107,10 @@ def is_auto_coarsen_enabled(schema: ExternalDataSchema) -> bool:
return _is_flag_enabled(schema, WAREHOUSE_AUTO_COARSEN_FLAG)
+def is_repartition_hold_enabled(schema: ExternalDataSchema) -> bool:
+ return _is_flag_enabled(schema, WAREHOUSE_REPARTITION_HOLD_FLAG)
+
+
def _is_flag_enabled(schema: ExternalDataSchema, flag: str) -> bool:
"""Evaluate a rollout flag for this schema.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index ccf3633ac8f2..dc770744164e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -44,6 +44,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (
is_transient_object_store_error,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (
+ capture_repartition_event,
+ is_repartition_hold_enabled,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import PipelineInputs
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLT
@@ -168,6 +172,43 @@ async def _warehouse_parent_reuse_available(
return True
+def _import_held_for_repartition(schema: ExternalDataSchema | None, logger: FilteringBoundLogger) -> bool:
+ """Whether an in-flight repartition should pause this schema's import for one run.
+
+ Both conditions have to hold: the schema opted into the hold, and a rewrite checkpoint is fresh
+ enough to be worth waiting for. The flag is checked second so a schema without it never pays for
+ the evaluation, and a flag lookup that throws leaves the import running — pausing a customer's
+ ingestion is the more expensive way to be wrong.
+ """
+ if schema is None or not schema.repartition_holds_import:
+ return False
+ try:
+ if not is_repartition_hold_enabled(schema):
+ return False
+ except Exception:
+ logger.warning("Could not evaluate the repartition hold flag; importing", exc_info=True)
+ return False
+
+ rewrite = schema.repartition_rewrite or {}
+ logger.info(
+ "Holding import: a repartition rewrite is converging on this table",
+ schema_id=str(schema.id),
+ rows_written=rewrite.get("rows_written"),
+ held_at=rewrite.get("held_at"),
+ )
+ capture_repartition_event(
+ "warehouse_repartition_import_held",
+ {
+ "team_id": schema.team_id,
+ "schema_id": str(schema.id),
+ "resource_name": schema.name,
+ "rows_written": rewrite.get("rows_written"),
+ "held_at": rewrite.get("held_at"),
+ },
+ )
+ return True
+
+
@activity.defn
async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> PipelineResult:
bind_contextvars(team_id=inputs.team_id)
@@ -211,6 +252,16 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
consumer_manages_job_status=True,
)
+ # A rewrite spanning several activity budgets resumes only while live stays at the Delta
+ # version its checkpoint was built against, and the merge below is what moves it. Importing
+ # here invalidates the checkpoint the previous run wrote, so the rewrite restarts from row 0
+ # and the table never converges. Skipping leaves this run a clean no-op: the workflow
+ # finalizes as usual and the next sync picks the data up once the rewrite lands. The hold
+ # lapses on its own if the rewrite stops advancing, so a stuck one costs freshness rather
+ # than ingestion.
+ if await database_sync_to_async_pool(_import_held_for_repartition)(model.schema, logger):
+ return PipelineResult(should_trigger_cdp_producer=False, consumer_manages_job_status=False)
+
await logger.adebug("Running import_data_activity")
source_type = ExternalDataSourceType(model.pipeline.source_type)
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 4a5bd4c00195..b154cd841724 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -1,5 +1,5 @@
import uuid
-from datetime import date, datetime, timedelta
+from datetime import UTC, date, datetime, timedelta
from typing import Any
import pytest
@@ -21,6 +21,7 @@ from posthog.models.team import Team
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
+ REPARTITION_HOLD_MAX_AGE,
ExternalDataSchema,
apply_incremental_lookback,
complete_schema_run,
@@ -1202,3 +1203,55 @@ class TestSSHTunnelPortValidation(SimpleTestCase):
passphrase=None,
)
assert tunnel.has_valid_port()[0] is expected_valid
+
+
+class TestRepartitionHoldsImport:
+ """The hold pauses a schema's imports so a multi-budget rewrite can keep its checkpoint.
+
+ Every condition here decides whether a customer's table keeps ingesting, so each case is a
+ distinct way of getting that wrong: no rewrite at all, a rewrite still advancing, one that
+ stopped, and checkpoints whose stamp we cannot age out.
+ """
+
+ def _schema_with(self, rewrite: dict[str, Any] | None) -> ExternalDataSchema:
+ config: dict[str, Any] = {}
+ if rewrite is not None:
+ config["repartition_rewrite"] = rewrite
+ return ExternalDataSchema(sync_type_config=config)
+
+ def _stamped(self, ago: timedelta) -> dict[str, Any]:
+ return {"temp_uri": "s3://t", "rows_written": 10, "held_at": (datetime.now(UTC) - ago).isoformat()}
+
+ @parameterized.expand(
+ [
+ ("no_rewrite", None, False),
+ ("fresh_checkpoint", timedelta(minutes=5), True),
+ ("within_the_window", REPARTITION_HOLD_MAX_AGE - timedelta(hours=1), True),
+ ("lapsed", REPARTITION_HOLD_MAX_AGE + timedelta(hours=1), False),
+ ]
+ )
+ def test_hold_tracks_whether_the_rewrite_is_still_advancing(
+ self, _name: str, ago: timedelta | None, expected: bool
+ ) -> None:
+ rewrite = None if ago is None else self._stamped(ago)
+ assert self._schema_with(rewrite).repartition_holds_import is expected
+
+ @parameterized.expand(
+ [
+ # A checkpoint written before `held_at` existed. Holding on it would pause imports with no
+ # way to ever age the hold out.
+ ("missing_stamp", {"temp_uri": "s3://t", "rows_written": 10}),
+ ("unparseable_stamp", {"temp_uri": "s3://t", "held_at": "not-a-timestamp"}),
+ ("non_string_stamp", {"temp_uri": "s3://t", "held_at": 1234}),
+ ]
+ )
+ def test_an_unusable_stamp_never_holds(self, _name: str, rewrite: dict[str, Any]) -> None:
+ assert self._schema_with(rewrite).repartition_holds_import is False
+
+ def test_a_naive_stamp_is_read_as_utc(self) -> None:
+ # `held_at` is written with `datetime.now(UTC).isoformat()`, but a hand-edited or older row
+ # can carry a naive string. Comparing that against an aware now() raises, which would fail
+ # the import activity rather than skip the hold.
+ naive = (datetime.now(UTC) - timedelta(minutes=5)).replace(tzinfo=None).isoformat()
+ schema = self._schema_with({"temp_uri": "s3://t", "held_at": naive})
+ assert schema.repartition_holds_import is True