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.

fix(warehouse-sources): checkpoint rewrite progress instead of only at the deadline (#87262)

Daniel RC096a776832be
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 44cca4882eb2..d6eba41fb96f 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1206,6 +1206,31 @@ def update_sync_type_config_keys(
return config
+def save_repartition_checkpoint_if_claimed(
+ schema: ExternalDataSchema, *, claim_token: str, checkpoint: dict[str, Any]
+) -> bool:
+ """Write a rewrite checkpoint only while `claim_token` still owns the schema. Returns whether it did.
+
+ Checking the claim before calling `set_repartition_rewrite` is not enough: that saves the whole
+ `sync_type_config` column from an in-memory copy, so a worker superseded between the check and the
+ save writes back its own stale `repartition_claim` and un-fences itself. Re-reading the claim under
+ the row lock, in the same transaction as the write, closes that window — the same reason
+ `update_sync_type_config_keys` exists.
+ """
+ claimed = False
+
+ def _write(config: dict[str, Any]) -> None:
+ nonlocal claimed
+ claim = config.get("repartition_claim")
+ if not (claim and claim.get("token") == claim_token):
+ return
+ config["repartition_rewrite"] = checkpoint
+ claimed = True
+
+ update_sync_type_config_keys(schema_id=schema.id, team_id=schema.team_id, mutate=_write)
+ return claimed
+
+
def complete_schema_run(schema: ExternalDataSchema, *, last_synced_at: datetime) -> bool:
"""Mark a schema COMPLETED after a successful run, atomically with the broken-state check.
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 bae21a5c3740..340b3f70da76 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
@@ -33,7 +33,10 @@ from structlog.types import FilteringBoundLogger
from posthog.temporal.common.utils import retry_on_db_connection_drop
from products.data_warehouse.backend.facade.api import aget_s3_client
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ save_repartition_checkpoint_if_claimed,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
evolve_pyarrow_schema,
normalize_column_name,
@@ -79,6 +82,14 @@ DEFAULT_REPARTITION_BATCH_SIZE = 1_000
# 0 disables the throttle (check every batch).
CLAIM_RECHECK_INTERVAL_SECONDS = 10.0
+# Minimum gap between rewrite checkpoints. The deadline handler saves one too, but only a rewrite that
+# survives to raise can reach it: an OOM-killed worker takes SIGKILL, so no `except` or `finally` runs
+# and nothing is persisted. That left every memory death restarting from row 0 forever. Checkpointing
+# on committed progress instead means an attempt converges across runs whatever kills it. Throttled
+# because it costs a claim check and a row write per checkpoint, and bounds re-done work to this
+# interval rather than to the whole rewrite.
+CHECKPOINT_INTERVAL_SECONDS = 30.0
+
# Arrow payload the rewrite may hold in its coalescing buffer. Half the package's per-table cap
# deliberately: the batch that triggers a flush is already materialised and stays resident while the
# buffer drains, so the true peak is buffer + one incoming batch. Budgeting half keeps that sum inside
@@ -698,6 +709,8 @@ async def _rewrite_into_temp(
logger: FilteringBoundLogger,
ensure_claim: Callable[[], Awaitable[None]] | None = None,
claim_recheck_interval_seconds: float = CLAIM_RECHECK_INTERVAL_SECONDS,
+ save_checkpoint: Callable[[int, RepartitionTarget], Awaitable[None]] | None = None,
+ checkpoint_interval_seconds: float = CHECKPOINT_INTERVAL_SECONDS,
deadline: float | None = None,
total_rows: int | None = None,
skip_rows: int = 0,
@@ -766,6 +779,29 @@ async def _rewrite_into_temp(
fields["eta_seconds"] = round(max(total_rows - rows_written, 0) / rate) if rate else None
return fields
+ last_checkpoint_at: float | None = None
+
+ async def maybe_checkpoint() -> None:
+ """Persist resumable progress, at most once per `checkpoint_interval_seconds`.
+
+ Called after a commit lands, so the recorded row count is always backed by data actually in
+ temp. Failing to checkpoint must not fail the rewrite: the attempt is still making progress,
+ and the next one simply resumes from further back.
+ """
+ nonlocal last_checkpoint_at
+ if save_checkpoint is None:
+ return
+ now = time.monotonic()
+ if last_checkpoint_at is not None and now - last_checkpoint_at < checkpoint_interval_seconds:
+ return
+ last_checkpoint_at = now
+ try:
+ await save_checkpoint(rows_written, resolved or target)
+ except RepartitionSupersededError:
+ raise
+ except Exception:
+ await logger.awarning("repartition: could not save rewrite checkpoint", exc_info=True)
+
async def flush() -> None:
"""Write the buffered batches as one Delta commit, then report progress."""
nonlocal buffered, buffered_rows, buffered_bytes, rows_written, commits
@@ -788,6 +824,7 @@ async def _rewrite_into_temp(
rows_written += combined.num_rows
commits += 1
report_buffer_bytes(0)
+ await maybe_checkpoint()
fields = progress()
await logger.ainfo(f"repartition: rewrite progress {_format_fields(fields)}", **fields)
@@ -1060,12 +1097,36 @@ async def repartition_table_in_place(
async with aget_s3_client(fresh_instance=True) as s3:
await _purge_stale_temp_tables(s3, live_uri)
+ async def save_checkpoint(rows_so_far: int, resolved_target: RepartitionTarget) -> None:
+ # Same payload as the deadline handler below, written on committed progress instead. The
+ # claim is re-checked under the row lock inside the write rather than before it: checking
+ # first would leave a window where a superseded worker still saves, and that save carries
+ # its whole stale `sync_type_config` — including its own `repartition_claim`, which would
+ # un-fence the zombie. A checkpoint skipped because we lost the claim is correct; the new
+ # claimant owns the rewrite now.
+ if claim_token is None:
+ return
+ checkpoint_version = await asyncio.to_thread(old_delta.version)
+ await asyncio.to_thread(
+ save_repartition_checkpoint_if_claimed,
+ schema,
+ claim_token=claim_token,
+ checkpoint={
+ "temp_uri": temp_uri,
+ "rows_written": rows_so_far,
+ "target": resolved_target.to_dict(),
+ "live_version": checkpoint_version,
+ "held_at": datetime.now(UTC).isoformat(),
+ },
+ )
+
try:
rows_written, resolved = await _rewrite_into_temp(
old_delta=old_delta,
temp_uri=temp_uri,
storage_options=storage_options,
target=rewrite_target,
+ save_checkpoint=save_checkpoint,
batch_size=batch_size,
logger=logger,
ensure_claim=ensure_claim,
@@ -1079,17 +1140,18 @@ async def repartition_table_in_place(
# attempt. The classifier needs the distinction (see `_handle_budget_exceeded`).
e.had_prior_checkpoint = rewrite_checkpoint is not None
# Checkpoint the half-built temp so the next attempt resumes instead of re-streaming from
- # row 0. Guard with a claim check first: a superseded zombie must not clobber the newer
- # claimant's state (the check raises RepartitionSupersededError, which the caller handles
- # by standing down without recording a failure). Only checkpoint real forward progress.
+ # row 0. Fenced on the claim inside the row lock, like the progress checkpoint above: a
+ # superseded zombie writing here would restore its own claim along with the whole config.
+ # Only checkpoint real forward progress.
await ensure_claim()
partial_rows = await _valid_delta_row_count(temp_uri, storage_options)
- if partial_rows:
- e.checkpoint_saved = True
+ if partial_rows and claim_token is not None:
live_version = await asyncio.to_thread(old_delta.version)
- await asyncio.to_thread(
- schema.set_repartition_rewrite,
- {
+ e.checkpoint_saved = await asyncio.to_thread(
+ save_repartition_checkpoint_if_claimed,
+ schema,
+ claim_token=claim_token,
+ checkpoint={
"temp_uri": temp_uri,
"rows_written": partial_rows,
"target": (e.resolved or rewrite_target).to_dict(),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
index 2c8f2c4ec566..c8cef5a0f497 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
@@ -592,6 +592,68 @@ class TestRewriteIntoTemp:
assert captured["batch_readahead"] == REWRITE_BATCH_READAHEAD
assert "fragment_readahead" not in captured
+ def test_progress_is_checkpointed_before_any_deadline(self, tmp_path):
+ # The deadline handler is the only other place a checkpoint is written, and an OOM-killed
+ # worker never reaches it, so a rewrite that dies mid-flight must already have one.
+ rows = [(i, datetime.datetime(2024, 1, 1 + (i % 28))) for i in range(40)]
+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)
+ saved: list[tuple[int, str | None]] = []
+
+ async def save_checkpoint(rows_so_far, resolved_target):
+ saved.append((rows_so_far, resolved_target.partition_format))
+
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=str(tmp_path / "tmp"),
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="test",
+ partition_mode="datetime",
+ partition_format="day",
+ ),
+ batch_size=1,
+ logger=logger,
+ save_checkpoint=save_checkpoint,
+ checkpoint_interval_seconds=0,
+ )
+ )
+
+ assert saved, "a rewrite that commits must checkpoint without waiting for the deadline"
+ # Backed by rows actually committed to temp, and carrying the resolved scheme the resume needs.
+ assert saved[-1][0] > 0
+ assert saved[-1][1] == "day"
+
+ def test_a_failing_checkpoint_does_not_fail_the_rewrite(self, tmp_path):
+ # Losing a checkpoint costs redone work on the next attempt; failing the rewrite costs the
+ # whole thing.
+ rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 1, 20))]
+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)
+
+ async def exploding_checkpoint(rows_so_far, resolved_target):
+ raise RuntimeError("pooler dropped")
+
+ rows_written, _ = asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=str(tmp_path / "tmp"),
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="test",
+ partition_mode="datetime",
+ partition_format="day",
+ ),
+ batch_size=1,
+ logger=logger,
+ save_checkpoint=exploding_checkpoint,
+ checkpoint_interval_seconds=0,
+ )
+ )
+
+ assert rows_written == len(rows)
+
def test_stops_mid_stream_once_the_deadline_passes(self, tmp_path):
rows = [
(1, datetime.datetime(2024, 1, 5)),
@@ -1440,6 +1502,7 @@ class TestRewriteCheckpointResume:
patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()),
patch.object(repartition_module, "_current_claim_token", return_value="tok"),
patch.object(repartition_module, "_valid_delta_row_count", new=AsyncMock(return_value=1)),
+ patch.object(repartition_module, "save_repartition_checkpoint_if_claimed", return_value=True) as saved,
patch.object(
repartition_module,
"_rewrite_into_temp",
@@ -1455,8 +1518,10 @@ class TestRewriteCheckpointResume:
)
)
- schema.set_repartition_rewrite.assert_called_once()
- checkpoint = schema.set_repartition_rewrite.call_args.args[0]
+ saved.assert_called_once()
+ # Fenced on the claim this attempt holds, so a superseded worker cannot write here.
+ assert saved.call_args.kwargs["claim_token"] == "tok"
+ checkpoint = saved.call_args.kwargs["checkpoint"]
assert checkpoint["rows_written"] == 1
assert checkpoint["live_version"] == live.version()
assert checkpoint["target"]["partition_format"] == "day"
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.py
index 6e3db6a91f42..612055bc2d98 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
@@ -21,8 +21,12 @@ from temporalio.testing import ActivityEnvironment
from posthog.models.team import Team
+from products.warehouse_sources.backend.models import external_data_schema
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_schema import (
+ ExternalDataSchema,
+ save_repartition_checkpoint_if_claimed,
+)
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 import workload_report
@@ -818,6 +822,51 @@ class TestRepartitionActivity:
pending = schema.repartition_pending
assert pending is not None and pending["attempts"] == 2
+ def test_a_checkpoint_from_a_superseded_attempt_is_dropped(self, team):
+ # The write carries the whole sync_type_config, so a stale worker saving here would restore
+ # its own repartition_claim and un-fence itself.
+ schema = _make_schema(team, {})
+ schema.set_repartition_claim({"token": "newer-claim", "job_id": "j2", "claimed_at": _days_ago_iso(0)})
+
+ wrote = save_repartition_checkpoint_if_claimed(
+ schema, claim_token="stale-claim", checkpoint={"temp_uri": "s3://t", "rows_written": 5}
+ )
+
+ schema.refresh_from_db()
+ assert wrote is False
+ assert schema.repartition_rewrite is None
+ claim = schema.repartition_claim
+ assert claim is not None and claim["token"] == "newer-claim"
+
+ def test_a_checkpoint_from_the_live_claim_is_written(self, team):
+ schema = _make_schema(team, {})
+ schema.set_repartition_claim({"token": "live-claim", "job_id": "j1", "claimed_at": _days_ago_iso(0)})
+
+ wrote = save_repartition_checkpoint_if_claimed(
+ schema, claim_token="live-claim", checkpoint={"temp_uri": "s3://t", "rows_written": 5}
+ )
+
+ schema.refresh_from_db()
+ assert wrote is True
+ rewrite = schema.repartition_rewrite
+ assert rewrite is not None and rewrite["rows_written"] == 5
+
+ def test_the_checkpoint_claim_check_runs_inside_the_row_lock(self, team):
+ # The predicate tests below pass against a plain refresh-then-write, which is the bug: the
+ # check and the write have to share one locked critical section or a superseding claimant can
+ # land between them. Pins that the write goes through the locked primitive.
+ schema = _make_schema(team, {})
+ schema.set_repartition_claim({"token": "live-claim", "job_id": "j1", "claimed_at": _days_ago_iso(0)})
+
+ with patch.object(external_data_schema, "update_sync_type_config_keys") as locked_update:
+ save_repartition_checkpoint_if_claimed(
+ schema, claim_token="live-claim", checkpoint={"temp_uri": "s3://t", "rows_written": 5}
+ )
+
+ locked_update.assert_called_once()
+ # The claim check must be the mutate callback, evaluated against the row read under the lock.
+ assert locked_update.call_args.kwargs["mutate"] is not None
+
def test_a_staged_swap_is_never_abandoned_by_the_attempt_cap(self, team):
# An interrupted swap may already have deleted live, leaving temp the only intact copy. Giving
# up clears the marker that points at it, so the next sync would bootstrap an empty table.