:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): stop repartition and cdc runs at a commit on shutdown (#112665)
Tom Owers64f78618bcd6
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.mdindex 7ca9564ed398..bf293b7fa1b4 100644--- a/docs/internal/cdc-buffered-ingress-runbook.md+++ b/docs/internal/cdc-buffered-ingress-runbook.md@@ -245,6 +245,13 @@ same positions with differently-shaped files. Before its first write per schema,file that reaches the position it restarted from (`end_seq >= restart_seq`), because it is about tore-emit all of those positions.+A worker that shuts down does not kill the attempt.+Capture stops at the next page boundary, after the slot has advanced past every change in the buffer, and records the run as completed.+If backlog is left and a retry remains, it raises `WorkerShuttingDownError` so Temporal continues the read on another worker.+That retry starts at the first unread change, so it has no files to remove.+On the last attempt it returns instead, and the next scheduled run reads the backlog.+The log line is `cdc_read_stopped_for_worker_shutdown`.+One file can straddle that position. A micro-flush is cut per event, so it can carry the head of atransaction; the slot then advances only to the previous transaction's end, and the retry re-readsthe straddled transaction from its first row. That file holds settled positions the WAL no longerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex beedefb3c222..6216703a78a5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -50,7 +50,7 @@ Week into month is the one transition that cannot be computed exactly, because I- **Resume.** A rewrite cut short (deadline, OOM, worker restart) resumes from the source files its temp commits record, not from a row count. Delta data files never change, so the resume stays valid after the sync commits to live, as long as every copied file is still live, live has no new column, and temp's row count matches the copied files (`resume_blocker`). Files the sync appended are copied with the rest. Otherwise the checkpoint is discarded and the rewrite starts again. A temp written before source files were recorded is rebuilt the same way.- **Full-refresh tables are not rewritten.** Their next sync deletes the table and writes it again, so a rewrite would only copy rows that sync throws away. The activity stages the target as the `*_override` partition keys, which survive that sync's reset, plus `partition_format`, and the sync writes the new layout (`stage_partition_scheme_for_full_refresh`). It also rotates the claim, so a rewrite still running as a zombie cannot swap its copy back over live. It leaves claim-scoped temp tables alone because a wildcard S3 sweep cannot stay fenced against a newer recovery attempt while awaiting storage. The event is `warehouse_repartition_skipped` with `outcome=deferred`. A staged swap still completes first. Temp stays the source of truth until the swap is verified, so a worker death at any point loses wasted compute, never data. An interruption (OOM, worker restart) can leave the `__repartitioned` temp partial, so every step that could destroy live re-validates temp first: the swap opens temp and checks it holds the full row count before deleting live, and a resume re-validates the temp the `ready` marker points at — discarding it and rebuilding fresh from the intact live rather than copying a broken temp over live. A live table whose own log is unreadable is skipped (the import activity's revival handles it), not counted as a repartition failure.- **Keeping the data and the settings in step.** The swap re-buckets the data in S3, but the scheme it was re-bucketed under lives in the schema row, and the merge computes each incoming row's `_ph_partition_key` from that row. Between the two the table would be describing a layout it no longer has, and a merge there scopes its predicate to a partition the table cannot contain, matches nothing, and inserts every fetched row instead of upserting it — the whole incremental lookback window duplicated, with the job still reporting Completed. Three things keep that window shut. The `repartition_swap` marker records the resolved scheme before the swap starts, so the scheme survives a worker death. The settings, the markers and the cooldown are saved together in one row-locked write (`finalize_repartition_scheme`), so there is no half-applied state to observe. And while the marker is set the table's layout is mid-change by definition, so the import activity holds this schema's syncs — unconditionally, not behind the hold rollout flag, because the alternative is corruption rather than staleness. A run that finds the marker set and temp already gone recomputes a sample of live's keys under the marker's scheme (`_live_matches_scheme`): matching means the swap finished and only its scheme write was lost, so the run saves the scheme and stops instead of rewriting the table for a layout it already has. A swap whose scheme cannot be saved raises `RepartitionSchemePersistError`, which is never classified as transient noise however transient the database error under it was, and the attempt cap never clears an unresolved swap marker.-- **Safety.** Concurrent _syncs_ are excluded (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), but concurrent _repartition attempts_ are not: an attempt Temporal heartbeat-times-out keeps running as a zombie (heartbeat failures are swallowed) while its retry starts, and S3 has no locking. The schema row's `repartition_claim` is the fence — each attempt mints a claim token, temp tables are scoped to it (`__repartitioned_<token>`), and the claim is re-checked before every batch write and every destructive step (temp sweep, swap marker, live delete). A superseded attempt raises `RepartitionSupersededError` and stands down silently; orphaned temp variants from superseded or crashed attempts are swept by name prefix before each fresh rebuild. A repartition failure never fails the sync — it's swallowed, retried on a later run, and capped at `MAX_REPARTITION_ATTEMPTS` (3) consecutive failures before it gives up and alerts. Cancellations, superseded attempts, transient infra errors (DB pooler drops, S3 rate limits), and budget-exceeded attempts that advanced the rewrite checkpoint don't count against that cap — a table too large to rewrite in one activity budget converges across runs via the checkpoint, and only an attempt that made no forward progress is charged. A panic from the native delta stack (pyo3 raises those as `BaseException`, so they do not stop at an `except Exception`) is recorded as a failure too, rather than being left to fail the activity and spend the remaining retries re-reading a log that panics in the same place. An attempt killed outright (a SIGKILLed worker runs no `except` and no `finally`) records nothing at all, so the activity's own retries judge it on the checkpoint instead: a retry re-runs the rewrite only while the attempt it retries left the checkpoint further along than it found it, because repeating a rewrite that died in place holds the sync for another activity budget and the next sync resumes from the same checkpoint anyway. The stand-down reports `reason=attempt_killed_without_progress`. The cap applies that same test across syncs, since a killed attempt is the one shape it cannot read an outcome for: a spent count is reset when the last attempt still moved the checkpoint on, so a table converging one worker death per sync keeps its progress, and the give-up fires only once the checkpoint stops moving. The terminal give-up carries how far the rewrite got.+- **Safety.** Concurrent _syncs_ are excluded (the schedule's `OnlyOne` overlap policy plus the v3 pipeline lock), but concurrent _repartition attempts_ are not: an attempt Temporal heartbeat-times-out keeps running as a zombie (heartbeat failures are swallowed) while its retry starts, and S3 has no locking. The schema row's `repartition_claim` is the fence — each attempt mints a claim token, temp tables are scoped to it (`__repartitioned_<token>`), and the claim is re-checked before every batch write and every destructive step (temp sweep, swap marker, live delete). A superseded attempt raises `RepartitionSupersededError` and stands down silently; orphaned temp variants from superseded or crashed attempts are swept by name prefix before each fresh rebuild. A repartition failure never fails the sync — it's swallowed, retried on a later run, and capped at `MAX_REPARTITION_ATTEMPTS` (3) consecutive failures before it gives up and alerts. Cancellations, superseded attempts, transient infra errors (DB pooler drops, S3 rate limits), and budget-exceeded attempts that advanced the rewrite checkpoint don't count against that cap — a table too large to rewrite in one activity budget converges across runs via the checkpoint, and only an attempt that made no forward progress is charged. A worker that shuts down stops the rewrite at its next commit, which is at most one source file later, or `STOP_GRACE_SECONDS` later when one large source file is still open. The activity saves the checkpoint, refunds the attempt and raises `WorkerShuttingDownError`, so Temporal retries on another worker and the retry copies only the source files that are left (`reason=worker_shutdown`). The activity gets `MAX_REPARTITION_ACTIVITY_ATTEMPTS` Temporal attempts for that reason: each stop uses one, and a sync that runs out of them merges on the old layout, which can invalidate the checkpoint. A panic from the native delta stack (pyo3 raises those as `BaseException`, so they do not stop at an `except Exception`) is recorded as a failure too, rather than being left to fail the activity and spend the remaining retries re-reading a log that panics in the same place. An attempt killed outright (a SIGKILLed worker runs no `except` and no `finally`) records nothing at all, so the activity's own retries judge it on the checkpoint instead: a retry re-runs the rewrite only while the attempt it retries left the checkpoint further along than it found it, because repeating a rewrite that died in place holds the sync for another activity budget and the next sync resumes from the same checkpoint anyway. The stand-down reports `reason=attempt_killed_without_progress`. The cap applies that same test across syncs, since a killed attempt is the one shape it cannot read an outcome for: a spent count is reset when the last attempt still moved the checkpoint on, so a table converging one worker death per sync keeps its progress, and the give-up fires only once the checkpoint stops moving. The terminal give-up carries how far the rewrite got.Tuning and gating:diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex f69dbff7a2b0..e40607cbbf0f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -27,6 +27,7 @@ from temporalio.service import RPCError, RPCStatusCodefrom posthog.temporal.common.errors import NonReportableErrorfrom posthog.temporal.common.heartbeat_sync import HeartbeaterSync+from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownErrorfrom posthog.utils import get_machine_idfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -180,8 +181,11 @@ class CDCExtractActivity:level steps; private methods implement individual phases."""- def __init__(self, inputs: CDCExtractInput) -> None:+ def __init__(self, inputs: CDCExtractInput, should_stop: Callable[[], bool] | None = None) -> None:self.inputs = inputs+ # Asks the read to stop at the next page boundary, for example because the worker shuts down.+ self._should_stop = should_stop+ self.stopped_before_backlog_drained: bool = Falseself.log: structlog.types.FilteringBoundLogger = logger.bind(team_id=inputs.team_id, source_id=str(inputs.source_id))@@ -835,7 +839,20 @@ class CDCExtractActivity:# page that returns rows always commits something and advances. Were that ever to not# hold, grow the window so an oversized single transaction can complete in one peek (or# trip the decoder's MAX_TX_BUFFER_EVENTS guard) instead of re-peeking the same page.- if not self._drain_and_advance_page():+ advanced = self._drain_and_advance_page()++ # Checked after the page advance, so the slot is already past every change this run wrote+ # to the buffer and the next run starts at the first unread change.+ if self._should_stop is not None and self._should_stop():+ self.stopped_before_backlog_drained = True+ self.log.info(+ "cdc_read_stopped_for_worker_shutdown",+ events_so_far=self.event_count,+ position=self.last_confirmed_lsn,+ )+ return++ if not advanced:limit = min(limit * 2, CDC_MAX_CHANGES_LIMIT_CAP)def _drain_and_advance_page(self) -> bool:@@ -1471,7 +1488,14 @@ class CDCExtractActivity:@activity.defndef cdc_extract_activity(inputs: CDCExtractInput) -> None:"""Core CDC extraction activity. Thin wrapper around CDCExtractActivity."""- CDCExtractActivity(inputs).run()+ with ShutdownMonitor() as shutdown_monitor:+ extraction = CDCExtractActivity(inputs, should_stop=shutdown_monitor.is_worker_shutdown)+ extraction.run()+ # The run ended cleanly at a page boundary with its position saved, but with backlog left.+ # Raise so that Temporal continues the read on another worker now. Without a retry left the+ # raise would fail the workflow, so the next scheduled run reads the remaining backlog.+ if extraction.stopped_before_backlog_drained and activity.info().attempt < CDC_MAX_EXTRACTION_ATTEMPTS:+ raise WorkerShuttingDownError.from_activity_context()@activity.defndiff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.pyindex b043cf5f1c4e..cacaabd5063d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -16,6 +16,7 @@ from parameterized import parameterizedfrom temporalio.service import RPCError, RPCStatusCodefrom posthog.temporal.common.errors import NonReportableError+from posthog.temporal.common.shutdown import WorkerShuttingDownErrorfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import CDC_SNAPSHOT_LANE_KEY, ExternalDataSchema@@ -1648,6 +1649,65 @@ class TestCDCBoundedReadLoop:capture.buffer.write_batch.assert_called_once()assert reader.confirmed_positions == ["0/100"]+ @parameterized.expand(+ [+ ("retry_left_continues_on_another_worker", 1, CDC_MAX_CHANGES_PER_READ, True),+ (+ "last_attempt_leaves_the_backlog_to_the_next_run",+ CDC_MAX_EXTRACTION_ATTEMPTS,+ CDC_MAX_CHANGES_PER_READ,+ False,+ ),+ ("backlog_already_drained", 1, 5, False),+ ]+ )+ def test_worker_shutdown_stops_at_a_page_boundary_and_the_next_run_continues(+ self, _name, attempt, first_page_rows, hands_off+ ):+ source = _make_source()+ schema = _make_schema("users", cdc_mode="streaming", source=source)+ schema.sync_type_config["primary_key_columns"] = ["id"]+ first_page = ([_make_event(op="I", table="users", position="0/100")], first_page_rows, "0/100")+ second_page = ([_make_event(op="I", table="users", position="0/200")], 5, "0/200")+ stopped_reader = _ScriptedReader([first_page, second_page])+ written: list[list[int]] = []++ with _capture_harness(source, [schema]) as capture, patch(f"{_ACTIVITIES}.ShutdownMonitor") as monitor:+ monitor.return_value.__enter__.return_value.is_worker_shutdown.return_value = True+ capture.activity.info.return_value.attempt = attempt+ capture.adapter.create_reader.return_value = stopped_reader+ handoff = WorkerShuttingDownError("activity", "cdc_extract_activity", "queue", attempt, "wf-1", "cdc")+ with patch.object(WorkerShuttingDownError, "from_activity_context", return_value=handoff):+ if hands_off:+ with pytest.raises(WorkerShuttingDownError):+ capture.extract()+ else:+ capture.extract()+ written += [+ c.kwargs["table"].column(CDC_SEQ_COLUMN).to_pylist() for c in capture.buffer.write_batch.call_args_list+ ]++ # The second page is not read, and the slot and the stored position are at the end of the+ # first page before the run ends, so the next run starts at the first unread change.+ assert len(stopped_reader.upto_nchanges_calls) == 1+ assert stopped_reader.confirmed_positions == ["0/100"]+ assert schema.sync_type_config["cdc_last_log_position"] == "0/100"+ assert written == [[0x100]]+ if first_page_rows < CDC_MAX_CHANGES_PER_READ:+ return++ next_reader = _ScriptedReader([second_page])+ with _capture_harness(source, [schema]) as capture:+ capture.adapter.create_reader.return_value = next_reader+ capture.extract()+ written += [+ c.kwargs["table"].column(CDC_SEQ_COLUMN).to_pylist() for c in capture.buffer.write_batch.call_args_list+ ]++ assert next_reader.confirmed_positions == ["0/200"]+ assert schema.sync_type_config["cdc_last_log_position"] == "0/200"+ assert written == [[0x100], [0x200]]+def test_full_page_with_no_committed_progress_doubles_the_limit(self):# Defensive backstop: a full page that commits nothing (so the slot can't advance) grows# the window instead of re-peeking the identical page forever.diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 77928d62a87e..9e453dfe85f5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -138,6 +138,11 @@ LOGGER = get_logger(__name__)# expensive retry-exhaustion paths fast.MAX_RESUMABLE_SOURCE_RETRIES = 3 if settings.DEBUG else MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTIONMAX_INCREMENTAL_SOURCE_RETRIES = 3 if settings.DEBUG else 9+# A rewrite that stops for a worker shutdown resumes on its next attempt, and each stop uses one+# attempt. When the attempts end, the sync merges on the old layout, and that merge can remove source+# files the rewrite already copied, which discards its progress. A long rewrite on a fleet that+# deploys often therefore needs the same room as a resumable import.+MAX_REPARTITION_ACTIVITY_ATTEMPTS = MAX_RESUMABLE_SOURCE_RETRIESMISSING_INTEGRATION_MESSAGE = ("The connected account for this source is no longer available — it may have been disconnected. "@@ -957,7 +962,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):),start_to_close_timeout=dt.timedelta(hours=6),heartbeat_timeout=dt.timedelta(minutes=5),- retry_policy=RetryPolicy(maximum_attempts=3),+ retry_policy=RetryPolicy(maximum_attempts=MAX_REPARTITION_ACTIVITY_ATTEMPTS),)except Exception:workflow.logger.warning(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.pyindex 94ce1d6c0c85..02ad3864c78f 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@@ -23,7 +23,7 @@ import dataclassesfrom collections import defaultdictfrom collections.abc import Awaitable, Callablefrom datetime import UTC, datetime, timedelta-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, NoReturnimport pyarrow as paimport deltalake as deltalake@@ -106,6 +106,12 @@ CLAIM_RECHECK_INTERVAL_SECONDS = 10.0# would otherwise leave the rewrite with nothing to resume from.CHECKPOINT_INTERVAL_SECONDS = 30.0+# How long a rewrite that must stop keeps working toward its next source-file boundary. The rewrite+# can only commit there, so a stop inside a file discards the rows read since the last commit. One+# large source file can take longer to copy than a worker shutdown should wait, so after this long+# the rewrite stops without the commit and the next attempt reads that file again.+STOP_GRACE_SECONDS = 120.0+TEMP_URI_SUFFIX = "__repartitioned"@@ -174,6 +180,19 @@ class RepartitionBudgetExceededError(Exception):self.checkpoint_saved = checkpoint_saved+class RepartitionStoppedError(Exception):+ """The rewrite stopped early because its caller asked it to, for example on worker shutdown.++ Not a failure. Temp holds every row of the source files its commits record, and the rewrite+ checkpoint points at it, so the next attempt copies only the other files. `rows_written` counts+ the rows this attempt committed.+ """++ def __init__(self, message: str, *, rows_written: int = 0) -> None:+ super().__init__(message)+ self.rows_written = rows_written++class RepartitionSchemePersistError(Exception):"""The swap re-bucketed the table in S3 but the new scheme could not be saved to the schema row.@@ -918,6 +937,8 @@ async def _rewrite_into_temp(deadline: float | None = None,total_rows: int | None = None,copied_files: frozenset[str] = frozenset(),+ should_stop: Callable[[], bool] | None = None,+ stop_grace_seconds: float = STOP_GRACE_SECONDS,) -> tuple[int, RepartitionTarget]:"""Stream the live table into a temp table under the new partition scheme.@@ -940,6 +961,11 @@ async def _rewrite_into_temp(`copied_files` resumes a prior attempt: temp already holds every row of these source files (see`copied_source_files`), so this call skips them and appends only the rest.++ `should_stop` asks the rewrite to stop early, for example because the worker is shutting down.+ Once it returns True the rewrite commits at the next source-file boundary, saves a checkpoint and+ raises `RepartitionStoppedError`. A source file that is still not finished `stop_grace_seconds`+ later is abandoned with the other uncommitted rows, and the next attempt reads it again."""budget = budget or rewrite_budget()await logger.ainfo(@@ -1021,8 +1047,8 @@ async def _rewrite_into_temp(last_checkpoint_at: float | None = None- async def maybe_checkpoint() -> None:- """Persist resumable progress, at most once per `checkpoint_interval_seconds`.+ async def maybe_checkpoint(force: bool = False) -> None:+ """Persist resumable progress, at most once per `checkpoint_interval_seconds` unless forced.Called after a commit lands, so the recorded row count is always backed by data actually intemp. Failing to checkpoint must not fail the rewrite: the attempt is still making progress,@@ -1032,7 +1058,7 @@ async def _rewrite_into_temp(if save_checkpoint is None:returnnow = time.monotonic()- if last_checkpoint_at is not None and now - last_checkpoint_at < checkpoint_interval_seconds:+ if not force and last_checkpoint_at is not None and now - last_checkpoint_at < checkpoint_interval_seconds:returnlast_checkpoint_at = nowtry:@@ -1120,7 +1146,30 @@ async def _rewrite_into_temp(# Feeds the workload reporter bound by the repartition activity; no-op everywhere else.report_buffer_bytes(writer.buffered_bytes)+ stop_requested_at: float | None = None++ def stop_requested() -> bool:+ nonlocal stop_requested_at+ if should_stop is None or not should_stop():+ return False+ if stop_requested_at is None:+ stop_requested_at = time.monotonic()+ return True++ async def stop() -> NoReturn:+ # The throttled checkpoint can be older than the last commit. The next attempt resumes only+ # from a checkpoint, so save one now. Without a commit from this attempt there is nothing new+ # to record, and temp may not exist yet.+ if commits:+ await maybe_checkpoint(force=True)+ fields = progress()+ await logger.ainfo(f"repartition: rewrite stopped early {_format_fields(fields)}", **fields)+ raise RepartitionStoppedError(+ f"rewrite stopped early after {rows_written} rows written to {temp_uri}", rows_written=rows_written+ )+last_claim_check: float | None = None+ files_left = len(plan)sources = reader.iter_sources(plan)try:while True:@@ -1149,17 +1198,30 @@ async def _rewrite_into_temp(resolved=resolved,resumed_from=inherited_rows,)+ if (+ stop_requested()+ and stop_requested_at is not None+ and time.monotonic() - stop_requested_at >= stop_grace_seconds+ ):+ await stop()staged.append(table)staged_bytes += table.nbytesif staged_bytes >= budget.batch_bytes:await write_staged()completed_sources.append(source.path)+ files_left -= 1+ # After the last file only the final commit is left, so finishing costs less than a stop+ # and a new attempt.+ stopping = files_left > 0 and stop_requested()if ((writer is not None and writer.bytes_since_commit >= budget.commit_bytes)or len(completed_sources) >= budget.max_source_files_per_commitor time.monotonic() - last_commit_at >= checkpoint_interval_seconds+ or stopping):await commit()+ if stopping:+ await stop()await commit()except BaseException:if writer is not None:@@ -1256,6 +1318,7 @@ async def repartition_table_in_place(budget: StreamBudget | None = None,claim_token: str | None = None,deadline: float | None = None,+ should_stop: Callable[[], bool] | None = None,) -> dict[str, Any]:"""Rewrite the schema's Delta table under `target`'s finer partition scheme, in place, from S3.@@ -1276,6 +1339,10 @@ async def repartition_table_in_place(`deadline` (a `time.monotonic()` value) bounds the rewrite phase only. The swap that followsneeds no bound of its own: it records `repartition_swap` before touching live, so a swap cutshort by the activity timeout resumes from the intact temp table on a later run.++ `should_stop` also applies to the rewrite phase only. When it returns True the rewrite stops after+ its next commit and raises `RepartitionStoppedError`, with the temp table and its checkpoint kept+ for the next attempt (see `_rewrite_into_temp`)."""live_uri = await table_ref.get_table_uri()storage_options = table_ref.get_storage_options()@@ -1516,6 +1583,7 @@ async def repartition_table_in_place(deadline=deadline,total_rows=old_row_count,copied_files=copied,+ should_stop=should_stop,)except RepartitionBudgetExceededError as e:# Only a checkpoint this attempt could build on marks a restart. One the resume path@@ -1554,7 +1622,7 @@ async def repartition_table_in_place(},)raise- except (RepartitionSupersededError, RepartitionUnpartitionableError):+ except (RepartitionSupersededError, RepartitionUnpartitionableError, RepartitionStoppedError):raiseexcept Exception as e:missing_path = _missing_live_object_path(e, live_uri)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.pyindex 329324bc3ddb..c838b9353e54 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@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.par)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (RepartitionBudgetExceededError,+ RepartitionStoppedError,RepartitionSupersededError,RepartitionTarget,RepartitionTooLargeForBudgetError,@@ -878,15 +879,17 @@ class TestRewriteIntoTemp:assert 0 < written < len(rows)@pytest.mark.parametrize(- "files_per_commit,rows_per_month",+ "files_per_commit,rows_per_month,interruption",[- pytest.param(1, 1, id="one_file_per_commit"),- pytest.param(2, 1, id="two_files_per_commit"),- pytest.param(1, 3, id="rows_spread_over_several_target_days"),+ pytest.param(1, 1, "deadline", id="one_file_per_commit"),+ pytest.param(2, 1, "deadline", id="two_files_per_commit"),+ pytest.param(1, 3, "deadline", id="rows_spread_over_several_target_days"),+ pytest.param(2, 1, "stop", id="stop_request_before_the_commit_budget"),+ pytest.param(1, 3, "stop", id="stop_request_with_several_batches_per_file"),],)def test_resume_after_an_interruption_completes_the_table_exactly_once(- self, files_per_commit, rows_per_month, tmp_path+ self, files_per_commit, rows_per_month, interruption, tmp_path):# A rewrite stopped mid-way leaves temp holding whole source files, which its commits record.# Resuming from that record must append exactly the other files: every source row present@@ -902,9 +905,24 @@ class TestRewriteIntoTemp:partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day")- clock = Mock(side_effect=itertools.chain([0.0] * (4 + 3 * rows_per_month), itertools.repeat(100.0)))- with patch.object(repartition_module, "time", Mock(monotonic=clock)):- with pytest.raises(RepartitionBudgetExceededError):+ save_checkpoint = AsyncMock()+ if interruption == "deadline":+ clock = Mock(side_effect=itertools.chain([0.0] * (4 + 3 * rows_per_month), itertools.repeat(100.0)))+ with patch.object(repartition_module, "time", Mock(monotonic=clock)):+ with pytest.raises(RepartitionBudgetExceededError):+ asyncio.run(+ _rewrite_into_temp(+ old_delta=live,+ temp_uri=temp_uri,+ storage_options={},+ target=target,+ budget=_budget(max_source_files_per_commit=files_per_commit),+ logger=logger,+ deadline=50.0,+ )+ )+ else:+ with pytest.raises(RepartitionStoppedError) as stopped:asyncio.run(_rewrite_into_temp(old_delta=live,@@ -913,7 +931,9 @@ class TestRewriteIntoTemp:target=target,budget=_budget(max_source_files_per_commit=files_per_commit),logger=logger,- deadline=50.0,+ save_checkpoint=save_checkpoint,+ # The request arrives after the first commit, inside the checkpoint throttle.+ should_stop=lambda: save_checkpoint.await_count >= 1,))partial = deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rows@@ -921,6 +941,12 @@ class TestRewriteIntoTemp:copied = copied_source_files(temp_uri, {})assert copied is not Noneassert len(copied) * rows_per_month == partial+ if interruption == "stop":+ # The stop commits one more file, ahead of the commit budget, and the checkpoint the next+ # attempt resumes from records that commit although the throttle would skip it.+ assert len(copied) == files_per_commit + 1+ assert stopped.value.rows_written == partial+ assert save_checkpoint.await_args_list[-1].args[0] == partialopened: list[str] = []iter_sources = SourceReader.iter_sources@@ -952,6 +978,71 @@ class TestRewriteIntoTemp:f.path for f in repartition_module.plan_source_files(live))+ def test_a_stop_request_abandons_a_source_file_that_outlasts_the_grace(self, tmp_path):+ # One row per batch, so the first source file is still open when the grace of zero ends.+ rows = [(i, datetime.datetime(2024, 1, 1 + i)) for i in range(3)] + [(3, datetime.datetime(2024, 2, 1))]+ live = _write_month_partitioned(str(tmp_path / "live"), rows)+ temp_uri = str(tmp_path / "tmp")+ target = RepartitionTarget(+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"+ )+ save_checkpoint = AsyncMock()++ with pytest.raises(RepartitionStoppedError) as stopped:+ asyncio.run(+ _rewrite_into_temp(+ old_delta=live,+ temp_uri=temp_uri,+ storage_options={},+ target=target,+ budget=_budget(),+ logger=logger,+ save_checkpoint=save_checkpoint,+ should_stop=lambda: True,+ stop_grace_seconds=0.0,+ )+ )++ # Nothing was committed, so there is no checkpoint to point a later attempt at a temp table+ # that holds none of the file's rows.+ assert stopped.value.rows_written == 0+ save_checkpoint.assert_not_awaited()+ assert not deltalake.DeltaTable.is_deltatable(temp_uri)++ rows_written, _ = asyncio.run(+ _rewrite_into_temp(+ old_delta=live, temp_uri=temp_uri, storage_options={}, target=target, budget=_budget(), logger=logger+ )+ )+ assert rows_written == len(rows)+ final = deltalake.DeltaTable(temp_uri).to_pyarrow_table()+ assert sorted(cast(list[int], final.column("id").to_pylist())) == [row[0] for row in rows]++ def test_a_stop_request_on_the_last_source_file_lets_the_rewrite_finish(self, tmp_path):+ rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 1, 20))]+ live = _write_month_partitioned(str(tmp_path / "live"), rows)+ temp_uri = str(tmp_path / "tmp")++ rows_written, _ = asyncio.run(+ _rewrite_into_temp(+ old_delta=live,+ temp_uri=temp_uri,+ storage_options={},+ target=RepartitionTarget(+ partition_keys=["created_at"],+ trigger_reason="t",+ partition_mode="datetime",+ partition_format="day",+ ),+ budget=_budget(),+ logger=logger,+ should_stop=lambda: True,+ )+ )++ assert rows_written == len(rows)+ assert deltalake.DeltaTable(temp_uri).to_pyarrow_table().num_rows == len(rows)+def test_a_temp_without_source_file_records_cannot_be_resumed(self, tmp_path):# An older rewrite appended rows with plain writes. Its temp says how many rows it holds but# not which files, so treating it as resumable would skip the wrong rows.@@ -2711,6 +2802,74 @@ class TestRewriteCheckpointResume:cast(list[int], live_now.column("id").to_pylist()))+ def test_a_rewrite_stopped_for_shutdown_is_completed_by_the_next_attempt(self, tmp_path):+ live_uri = str(tmp_path / "live")+ rows = [(i, datetime.datetime(2024, 1 + i, 5)) for i in range(6)]+ live = _write_month_partitioned(live_uri, rows)+ target = RepartitionTarget(+ partition_keys=["created_at"], trigger_reason="t", partition_mode="datetime", partition_format="day"+ )+ schema = self._base_schema()+ table_ref = _make_table_ref(+ get_table_uri=AsyncMock(return_value=live_uri), get_delta_table=AsyncMock(return_value=live)+ )++ def save_checkpoint(saved_schema, *, claim_token, checkpoint):+ saved_schema.repartition_rewrite = checkpoint+ return True++ with (+ patch.object(repartition_module, "aget_s3_client", return_value=_FakeS3CM(_fake_s3())),+ patch.object(repartition_module, "_purge_stale_temp_tables", new=AsyncMock()) as purge,+ patch.object(repartition_module, "save_repartition_checkpoint_if_claimed", side_effect=save_checkpoint),+ _patch_finalize(),+ patch.object(repartition_module, "_swap_temp_into_live", new=AsyncMock()) as swap,+ ):+ with (+ patch.object(repartition_module, "_current_claim_token", return_value="first"),+ pytest.raises(RepartitionStoppedError),+ ):+ asyncio.run(+ repartition_table_in_place(+ table_ref=table_ref,+ schema=schema,+ target=target,+ logger=logger,+ claim_token="first",+ budget=_budget(),+ should_stop=lambda: True,+ )+ )++ swap.assert_not_awaited()+ schema.clear_repartition_rewrite.assert_not_called()+ checkpoint = schema.repartition_rewrite+ stopped_temp = checkpoint["temp_uri"]+ stopped_rows = deltalake.DeltaTable(stopped_temp).to_pyarrow_table().num_rows+ assert 0 < stopped_rows < len(rows)+ assert checkpoint["rows_written"] == stopped_rows+ purge.reset_mock()++ with patch.object(repartition_module, "_current_claim_token", return_value="second"):+ result = asyncio.run(+ repartition_table_in_place(+ table_ref=table_ref,+ schema=schema,+ target=target,+ logger=logger,+ claim_token="second",+ budget=_budget(),+ )+ )++ assert result["outcome"] == "completed"+ # A fresh build sweeps every temp table, which would delete the stopped attempt's rows.+ purge.assert_not_awaited()+ assert swap.await_args is not None+ assert swap.await_args.kwargs["temp_uri"] == stopped_temp+ rebuilt = deltalake.DeltaTable(stopped_temp).to_pyarrow_table()+ assert sorted(cast(list[int], rebuilt.column("id").to_pylist())) == [row[0] for row in rows]+def test_refuses_to_restart_a_table_one_budget_already_failed_to_cover(self, tmp_path):# The discarded checkpoint above is only harmless while a restart can finish. Once a full# budget has been spent covering fewer rows than live holds, re-streaming from row 0 runs outdiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.pyindex 3171349a86c6..f4ec2a36c65a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py@@ -33,6 +33,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.common.activity_context import current_activity_attemptfrom posthog.temporal.common.heartbeat_sync import HeartbeaterSyncfrom posthog.temporal.common.logger import get_logger+from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownErrorfrom posthog.temporal.common.utils import retry_on_db_connection_dropfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -46,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repRepartitionAttemptsExhausted,RepartitionBudgetExceededError,RepartitionSchemePersistError,+ RepartitionStoppedError,RepartitionSupersededError,RepartitionTarget,RepartitionTooLargeForBudgetError,@@ -473,7 +475,9 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinstart = time.monotonic()try:# HeartbeaterSync heartbeats on a background thread while the (possibly long) rewrite streams,- # and on worker shutdown, so Temporal reschedules us instead of timing the activity out.+ # so Temporal does not time the activity out. The shutdown monitor lets the rewrite stop at+ # its next commit when the worker shuts down, so a rewrite does not hold a draining worker+ # for hours.# The workload reporter makes the rewrite visible to pod co-tenant accounting (see# `workload_report.py`): without it a rewrite-heavy pod looks idle to the OOM classifier's# culprit rule. The run_id is prefixed because the sync's import activity reports under the@@ -481,6 +485,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin# read this rewrite's report as its own last words.with (HeartbeaterSync(logger=logger),+ ShutdownMonitor() as shutdown_monitor,workload_reporting(team_id=inputs.team_id,schema_id=inputs.schema_id,@@ -497,7 +502,20 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterinlogger=logger,claim_token=claim_token,deadline=_rewrite_deadline(activity_started),+ should_stop=shutdown_monitor.is_worker_shutdown,)+ except RepartitionStoppedError as e:+ # The worker is shutting down and the rewrite stopped at a commit. Temp and its checkpoint+ # stay, so the retry that Temporal starts on another worker copies only the source files that+ # are left. This is not a failed attempt, so it must not count toward the give-up cap.+ logger.info(+ f"repartition: stopped at a commit for worker shutdown, handing off rows_written={e.rows_written}",+ rows_written=e.rows_written,+ )+ DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="handed_off").inc()+ _refund_attempt(schema, charged_attempts, logger)+ _capture_stood_down(schema, inputs, trigger_reason, "worker_shutdown", logger)+ raise WorkerShuttingDownError.from_activity_context() from eexcept RepartitionBudgetExceededError as e:# The rewrite didn't fit in one activity's budget. Checkpoint/resume lets a large table# converge across runs, so an attempt that advanced the checkpoint is progress, not a failure,diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.pyindex 04c4a767e91c..19a3f96475f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_repartition_table.py@@ -1,4 +1,5 @@import uuid+import asyncioimport datetime as dtimport contextvarsfrom typing import Any@@ -10,8 +11,10 @@ from django.db import InterfaceError, InternalError, OperationalErrorimport psycopg.errorsfrom parameterized import parameterized+from temporalio.testing import ActivityEnvironmentfrom posthog.exceptions_capture import ambient_exception_properties+from posthog.temporal.common.shutdown import WorkerShuttingDownErrorfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -21,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (RepartitionBudgetExceededError,RepartitionSchemePersistError,+ RepartitionStoppedError,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (MAX_REPARTITION_ATTEMPTS,@@ -337,6 +341,62 @@ class TestBudgetExhaustion:assert "warehouse_repartition_failed" not in emittedassert "warehouse_repartition_skipped" in emitted+ @parameterized.expand([("first_attempt", 0), ("last_attempt_before_give_up", 2)])+ @patch(f"{MODULE}.capture_exception")+ @patch(f"{MODULE}.capture_repartition_event")+ @patch(f"{MODULE}.HeartbeaterSync")+ @patch(f"{MODULE}.repartition_table_in_place", new_callable=AsyncMock)+ @patch(f"{MODULE}.DeltaTableRef")+ @patch(f"{MODULE}.ExternalDataJob")+ @patch(f"{MODULE}.ExternalDataSchema")+ def test_a_worker_shutdown_hands_the_rewrite_off_without_burning_an_attempt(+ self,+ _name: str,+ prior_attempts: int,+ mock_schema_model: MagicMock,+ _mock_job_model: MagicMock,+ _mock_helper_cls: MagicMock,+ mock_repartition: AsyncMock,+ _mock_heartbeater: MagicMock,+ mock_capture_event: MagicMock,+ mock_capture_exception: MagicMock,+ ) -> None:+ schema = _schema(+ name="public.usages",+ s3_folder_name="usages",+ pending={**PENDING_TARGET, "attempts": prior_attempts},+ rewrite={"rows_written": 50_000, "temp_uri": TEMP_URI},+ )+ mock_schema_model.objects.select_related.return_value.get.return_value = schema++ async def rewrite_until_asked_to_stop(*, should_stop: Any, **_kwargs: Any) -> dict[str, Any]:+ async with asyncio.timeout(10):+ while not should_stop():+ await asyncio.sleep(0.01)+ raise RepartitionStoppedError("stopped", rows_written=180_000)++ mock_repartition.side_effect = rewrite_until_asked_to_stop+ environment = ActivityEnvironment()+ environment.worker_shutdown()++ with pytest.raises(WorkerShuttingDownError):+ environment.run(+ _maybe_repartition_table,+ RepartitionActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID, job_id=JOB_ID, source_id=SOURCE_ID),+ MagicMock(),+ )++ # The charge is released, so the retry that continues the rewrite is not judged as the retry+ # of a killed attempt, and the cap counts only the attempts that failed.+ assert schema.repartition_pending["attempts"] == prior_attempts+ assert schema.repartition_pending["charged_job_id"] is None+ schema.clear_repartition_pending.assert_not_called()+ schema.clear_repartition_rewrite.assert_not_called()+ schema.stamp_last_repartition_at.assert_not_called()+ emitted = [c.args[0] for c in mock_capture_event.call_args_list]+ assert "warehouse_repartition_failed" not in emitted+ mock_capture_exception.assert_not_called()+@patch(f"{MODULE}.capture_exception")@patch(f"{MODULE}.capture_repartition_event")@patch(f"{MODULE}.HeartbeaterSync")