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(data-warehouse): wait out v3 full-refresh delta rebuild in ducklake copy (#75124)

Eric Duong683a53c3b02c
diff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
index cf3b2e8504c2..02a42b53a076 100644
--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
@@ -1,4 +1,5 @@
import json
+import time
import uuid
import typing
import datetime as dt
@@ -332,6 +333,52 @@ def _copy_data_imports_via_duckdb(inputs: DuckLakeCopyDataImportsActivityInputs,
logger.info("Successfully materialized DuckLake table", ducklake_table=qualified_table)
+# A v3 full-refresh sync purges the source Delta table during extract and the
+# delta-load consumer rebuilds it asynchronously after the import job (and therefore
+# this copy, fired at job end) has already started. Reads that land in that window see
+# an empty _delta_log. The wait budget covers the p99.9 of observed rebuild latency;
+# a consumer outage beyond it fails the copy, and the next sync retries.
+DELTA_REBUILD_WAIT_SECONDS = 600
+DELTA_REBUILD_POLL_SECONDS = 20
+
+
+def _is_delta_table_absent_error(error: Exception) -> bool:
+ """Whether an error means the source Delta table does not currently exist."""
+ if isinstance(error, deltalake.exceptions.TableNotFoundError):
+ return True
+ return isinstance(error, deltalake.exceptions.DeltaError) and "No files in log segment" in str(error)
+
+
+def _stage_delta_table_waiting_for_rebuild(
+ *, source_uri: str, catalog_bucket: str, organization_id: str, logger: typing.Any
+) -> None:
+ """Stage the source Delta table, waiting out the v3 full-refresh rebuild window.
+
+ Only the two "table momentarily absent" signals are absorbed; every other error
+ propagates immediately. Runs inside the activity's HeartbeaterSync, so the sleeps
+ keep heartbeating and a dead worker is still detected via heartbeat timeout.
+ """
+ deadline = time.monotonic() + DELTA_REBUILD_WAIT_SECONDS
+ while True:
+ try:
+ stage_delta_table(
+ source_uri=source_uri,
+ catalog_bucket=catalog_bucket,
+ organization_id=organization_id,
+ )
+ return
+ except Exception as error:
+ if not _is_delta_table_absent_error(error) or time.monotonic() >= deadline:
+ raise
+ logger.info(
+ "Source Delta table not readable yet, waiting for the loader to rebuild it",
+ source_uri=source_uri,
+ error=str(error),
+ poll_seconds=DELTA_REBUILD_POLL_SECONDS,
+ )
+ time.sleep(DELTA_REBUILD_POLL_SECONDS)
+
+
def _copy_data_imports_via_duckgres(inputs: DuckLakeCopyDataImportsActivityInputs, logger: typing.Any) -> None:
"""Stage Delta files and create the DuckLake table via duckgres."""
org_id = _get_org_id_for_team(inputs.team_id)
@@ -349,10 +396,11 @@ def _copy_data_imports_via_duckgres(inputs: DuckLakeCopyDataImportsActivityInput
source_uri=inputs.model.source_table_uri,
staging_uri=inputs.model.staging_uri,
)
- stage_delta_table(
+ _stage_delta_table_waiting_for_rebuild(
source_uri=inputs.model.source_table_uri,
catalog_bucket=bucket,
organization_id=org_id,
+ logger=logger,
)
schema = inputs.model.ducklake_schema_name
diff --git a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py
index d5bc172d3645..741970549ebb 100644
--- a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py
+++ b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock
from django.conf import settings
from django.test import override_settings
+import deltalake
import temporalio.worker
import temporalio.converter
from temporalio import activity as temporal_activity
@@ -1411,3 +1412,92 @@ async def test_ducklake_copy_data_imports_workflow_calls_cleanup_after_verify(mo
assert call_counts["copy"] == 1
assert call_counts["verify"] == 1
assert call_counts["cleanup"] == 1
+
+
+class _FakeClock:
+ def __init__(self) -> None:
+ self.now = 0.0
+ self.sleeps: list[float] = []
+
+ def monotonic(self) -> float:
+ return self.now
+
+ def sleep(self, seconds: float) -> None:
+ self.sleeps.append(seconds)
+ self.now += seconds
+
+
+ "absent_error",
+ [
+ deltalake.exceptions.DeltaError("Generic delta kernel error: No files in log segment"),
+ deltalake.exceptions.TableNotFoundError("no log files"),
+ ],
+)
+def test_stage_waits_out_delta_rebuild_window(monkeypatch, absent_error):
+ # A v3 full-refresh sync purges the source Delta table and the loader rebuilds it
+ # asynchronously; the first stage attempts land in that window and must be retried,
+ # not treated as fatal.
+ clock = _FakeClock()
+ monkeypatch.setattr(ducklake_module, "time", clock)
+ attempts = {"count": 0}
+
+ def stage(**kwargs):
+ attempts["count"] += 1
+ if attempts["count"] <= 2:
+ raise absent_error
+
+ monkeypatch.setattr(ducklake_module, "stage_delta_table", stage)
+
+ ducklake_module._stage_delta_table_waiting_for_rebuild(
+ source_uri="s3://bucket/folder/table",
+ catalog_bucket="catalog",
+ organization_id="org",
+ logger=MagicMock(),
+ )
+
+ assert attempts["count"] == 3
+ assert clock.sleeps == [ducklake_module.DELTA_REBUILD_POLL_SECONDS] * 2
+
+
+def test_stage_raises_immediately_on_non_absent_errors(monkeypatch):
+ clock = _FakeClock()
+ monkeypatch.setattr(ducklake_module, "time", clock)
+ attempts = {"count": 0}
+
+ def stage(**kwargs):
+ attempts["count"] += 1
+ raise deltalake.exceptions.DeltaError("Generic error: something else broke")
+
+ monkeypatch.setattr(ducklake_module, "stage_delta_table", stage)
+
+ with pytest.raises(deltalake.exceptions.DeltaError):
+ ducklake_module._stage_delta_table_waiting_for_rebuild(
+ source_uri="s3://bucket/folder/table",
+ catalog_bucket="catalog",
+ organization_id="org",
+ logger=MagicMock(),
+ )
+
+ assert attempts["count"] == 1
+ assert clock.sleeps == []
+
+
+def test_stage_gives_up_after_rebuild_wait_budget(monkeypatch):
+ clock = _FakeClock()
+ monkeypatch.setattr(ducklake_module, "time", clock)
+
+ def stage(**kwargs):
+ raise deltalake.exceptions.DeltaError("Generic delta kernel error: No files in log segment")
+
+ monkeypatch.setattr(ducklake_module, "stage_delta_table", stage)
+
+ with pytest.raises(deltalake.exceptions.DeltaError):
+ ducklake_module._stage_delta_table_waiting_for_rebuild(
+ source_uri="s3://bucket/folder/table",
+ catalog_bucket="catalog",
+ organization_id="org",
+ logger=MagicMock(),
+ )
+
+ assert clock.now <= ducklake_module.DELTA_REBUILD_WAIT_SECONDS + ducklake_module.DELTA_REBUILD_POLL_SECONDS