:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): commit a repartition buffer that fills too slowly (#103601)
Tom Owerse064d2008c66
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex e8cf398f74d1..5451393d35fd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -46,7 +46,7 @@ How it works:Week into month is the one transition that cannot be computed exactly, because ISO weeks straddle month boundaries and the key does not say how a week's bytes divide between two months. It is sized by upper bound instead, charging each straddling week's full size to both months, so a layout that fits under the bound fits in reality. The transition is worth supporting rather than skipping: the finer path's first step is month into week, so without it a table this controller wrongly split could never be merged back. Note the bound also makes it the narrowest transition on offer, since a month holds only about 4.3 weeks against a 4x minimum reduction, so in practice it needs roughly a year of weekly partitions to qualify.-- **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. 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.+- **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. Batches coalesce into one commit per buffer, and the buffer also commits once it has been held for the checkpoint interval, so a scan too slow to fill it inside one worker's life still leaves resumable progress behind. 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.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 7a40a955b124..869b40a65535 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@@ -90,7 +90,9 @@ CLAIM_RECHECK_INTERVAL_SECONDS = 10.0# 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.+# interval rather than to the whole rewrite. A checkpoint only records committed rows, so this also+# bounds how long the coalescing buffer may be held before it commits — a buffer that fills slower+# than this would otherwise leave the rewrite with nothing to resume from.CHECKPOINT_INTERVAL_SECONDS = 30.0# Arrow payload the rewrite may hold in its coalescing buffer. Half the package's per-table cap@@ -991,6 +993,7 @@ async def _rewrite_into_temp(buffered: list[pa.Table] = []buffered_rows = 0buffered_bytes = 0+ buffer_opened_at: float | None = Nonestarted_at = time.monotonic()commits = 0@@ -1037,9 +1040,10 @@ async def _rewrite_into_temp(async def flush() -> None:"""Write the buffered batches as one Delta commit, then report progress."""- nonlocal buffered, buffered_rows, buffered_bytes, rows_written, commits+ nonlocal buffered, buffered_rows, buffered_bytes, rows_written, commits, buffer_opened_atif not buffered:return+ buffer_opened_at = None# Every buffered table was already aligned to `live_schema`, so they concat without promotion.combined = buffered[0] if len(buffered) == 1 else pa.concat_tables(buffered)buffered = []@@ -1145,11 +1149,23 @@ async def _rewrite_into_temp(# or a nearly-full buffer could still take a further full-sized batch. Peak residency is this# buffer plus the batch in hand, which `REWRITE_BUFFER_MAX_BYTES` budgets for.table_bytes = table_payload_bytes(partitioned_table)+ # Age closes the buffer as well as size. The scan yields at least one batch per source file,+ # so on an over-fragmented table — the kind a coarsening rewrite exists to fix — filling the+ # buffer can take longer than the worker survives. Nothing commits, so nothing checkpoints,+ # and every attempt resumes from the same row until the attempt cap abandons the table.+ buffer_held_too_long = (+ buffer_opened_at is not None and time.monotonic() - buffer_opened_at >= checkpoint_interval_seconds+ )if buffered and (buffered_rows + partitioned_table.num_rows > REWRITE_BUFFER_MAX_ROWSor buffered_bytes + table_bytes > REWRITE_BUFFER_MAX_BYTES+ or buffer_held_too_long):await flush()+ if save_checkpoint is not None and buffer_opened_at is None:+ # Only tracked when there is a checkpoint to protect, so a caller that cannot resume+ # keeps the size-only commits it had.+ buffer_opened_at = time.monotonic()buffered.append(partitioned_table)buffered_rows += partitioned_table.num_rowsbuffered_bytes += table_bytesdiff --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 81d44d05e781..01448fbe8489 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@@ -715,6 +715,43 @@ class TestRewriteIntoTemp:assert saved[-1][0] > 0assert saved[-1][1] == "day"+ def test_a_slow_scan_checkpoints_before_the_buffer_is_full(self, tmp_path):+ # An over-fragmented table yields one small batch per source file, so the buffer can take+ # longer to fill than the worker survives. With no commit there is no checkpoint either, and+ # every attempt then resumes from the same row until the attempt cap abandons the table.+ rows = [(i, datetime.datetime(2024, 1, 1 + i)) for i in range(4)]+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)+ saved: list[int] = []++ async def save_checkpoint(rows_so_far, _resolved_target):+ saved.append(rows_so_far)++ # Every clock read lands a minute later, so the buffer is always older than the checkpoint+ # interval while holding far less than REWRITE_BUFFER_MAX_ROWS/BYTES.+ clock = Mock(side_effect=itertools.count(0.0, 60.0))++ with patch.object(repartition_module, "time", Mock(monotonic=clock)):+ 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,+ )+ )++ assert saved, "a rewrite that keeps reading must record progress it can resume from"+ # Recorded mid-scan, not only by the final flush every rewrite does anyway.+ assert saved[0] < len(rows)+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.