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(managed-warehouse): publish finished stale registrations (#82972)

Eric Duongfd2de3ec9021
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.md
index a734c5fcad15..c58d00a3557c 100644
--- a/products/managed_warehouse/backend/README.md
+++ b/products/managed_warehouse/backend/README.md
@@ -88,6 +88,8 @@ Duckgres stores a table-naming version on the organization. Organizations that e
Each completed import creates a timestamped prepared Parquet snapshot in the data warehouse bucket. The registration workflow copies those objects directly into the DuckLake bucket, preserving Hive partition directories, and registers the generation through one recursive Parquet glob. This gives DuckDB one parallel metadata scan and one generation-sized DuckLake commit. The workflow verifies the shadow table's row count, then swaps it into the stable table name through the Duckgres PostgreSQL connection. Publication uses one short transaction that renames the current table to an attempt-owned backup and the verified shadow to the stable name. A mismatch never enters the publication transaction, so the previous table remains live. The backup is dropped after publication. Each prepared generation gets its own object prefix and child workflow ID.
+A run that is no longer the latest prepared snapshot still publishes after a successful verify, so a long registration can land instead of losing the race to the next snapshot. A later run replaces it. Publication is skipped only when a newer snapshot has already been published, so the live table does not move backward. Prepare still skips a snapshot that is already obsolete before any copy or catalog work starts.
+
The registered objects are permanent DuckLake data files, not staging files. Old generations remain reachable through DuckLake snapshots until snapshot expiration and old-file cleanup make them eligible for object deletion. Choose the bucket lifecycle policy with that retention behavior in mind.
## Required permissions
diff --git a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
index 54b334bf7596..e1415e5c8570 100644
--- a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
+++ b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
@@ -47,6 +47,7 @@ from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehouseSourceJobUpdate,
ManagedWarehouseSourceJobWorkflow,
)
+from products.managed_warehouse.backend.models import ManagedWarehouseSourceJob
from products.managed_warehouse.backend.storage import connect_to_duckgres, setup_duckgres_session
from products.managed_warehouse.backend.temporal.metrics import (
get_ducklake_register_data_imports_bytes_metric,
@@ -341,13 +342,6 @@ def copy_and_register_ducklake_data_imports_activity(inputs: DuckLakeRegisterDat
inputs.metadata.prepared_source_uri,
landing_uri,
)
- if not _prepared_generation_is_current(inputs):
- get_ducklake_register_data_imports_stale_metric(
- team_id=inputs.team_id, schema_id=schema_id, stage="post_copy"
- ).add(1)
- logger.info("Skipping stale prepared Parquet generation after object copy")
- return False
-
try:
with _connect_to_duckgres_for_team(inputs.team_id) as conn:
cancel_delay = _duckgres_cancel_delay(activity_started_monotonic)
@@ -508,15 +502,56 @@ def _copy_prepared_parquet_files(source_uri: str, landing_uri: str) -> tuple[lis
return landing_paths, copied_bytes
-def _prepared_generation_is_current(inputs: DuckLakeRegisterDataImportsActivityInputs) -> bool:
+def _current_prepared_queryable_folder(inputs: DuckLakeRegisterDataImportsActivityInputs) -> str | None:
try:
schema = ExternalDataSchema.objects.select_related("table").get(
id=inputs.metadata.source_schema_id,
team_id=inputs.team_id,
)
except ExternalDataSchema.DoesNotExist:
+ return None
+ if schema.table is None:
+ return None
+ return schema.table.queryable_folder
+
+
+def _prepared_generation_is_current(inputs: DuckLakeRegisterDataImportsActivityInputs) -> bool:
+ return _current_prepared_queryable_folder(inputs) == inputs.metadata.prepared_queryable_folder
+
+
+def _register_completed_for_generation(*, team_id: int, schema_id: str, prepared_queryable_folder: str) -> bool:
+ try:
+ schema_uuid = uuid.UUID(schema_id)
+ except ValueError:
return False
- return schema.table is not None and schema.table.queryable_folder == inputs.metadata.prepared_queryable_folder
+ token = _generation_token(prepared_queryable_folder)
+ return (
+ ManagedWarehouseSourceJob.objects.for_team(team_id)
+ .filter(
+ schema_id=schema_uuid,
+ workflow_type=ManagedWarehouseSourceJob.WorkflowType.REGISTER,
+ status=ManagedWarehouseSourceJob.Status.COMPLETED,
+ attempt_id__endswith=f":{token}",
+ )
+ .exists()
+ )
+
+
+def _should_publish_prepared_generation(inputs: DuckLakeRegisterDataImportsActivityInputs) -> bool:
+ # A newer folder appearing mid-run is the common case for large generations.
+ # Aborting after ducklake_add_data_files leaves the live table unchanged and
+ # the next run can lose the same race. Publish this verified snapshot unless
+ # the newer folder has already landed, so the live table does not move backward.
+ if _prepared_generation_is_current(inputs):
+ return True
+ current_folder = _current_prepared_queryable_folder(inputs)
+ if current_folder is None:
+ return False
+ return not _register_completed_for_generation(
+ team_id=inputs.team_id,
+ schema_id=inputs.metadata.source_schema_id,
+ prepared_queryable_folder=current_folder,
+ )
@contextlib.contextmanager
@@ -682,7 +717,7 @@ def _register_prepared_parquet_files(
generation_is_stale = False
with _stage_timer(stage="publish", team_id=inputs.team_id, schema_id=inputs.metadata.source_schema_id) as timer:
_raise_if_duckgres_cancel_requested(cancel_requested)
- if _prepared_generation_is_current(inputs):
+ if _should_publish_prepared_generation(inputs):
_raise_if_duckgres_cancel_requested(cancel_requested)
publish_attempted = True
# Keep this transaction limited to publication. DuckLake flushes staged file
diff --git a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
index 2c81316f2238..39de770ae5b2 100644
--- a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
+++ b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
@@ -447,33 +447,72 @@ def test_registration_stops_after_glob_query_cancellation(monkeypatch):
assert not any("RENAME TO" in query for query in executed)
-def test_copy_activity_does_not_touch_catalog_for_stale_generation(monkeypatch):
+ ("is_current", "newer_completed", "expected"),
+ [
+ (True, None, True),
+ (False, False, True),
+ (False, True, False),
+ (False, None, False),
+ ],
+)
+def test_should_publish_prepared_generation(
+ is_current: bool,
+ newer_completed: bool | None,
+ expected: bool,
+ monkeypatch,
+) -> None:
+ monkeypatch.setattr(registration_module, "_prepared_generation_is_current", lambda inputs: is_current)
+ monkeypatch.setattr(
+ registration_module,
+ "_current_prepared_queryable_folder",
+ lambda inputs: None if newer_completed is None and not is_current else "customers__query_9999999999_ffffffff",
+ )
+ monkeypatch.setattr(
+ registration_module,
+ "_register_completed_for_generation",
+ lambda **kwargs: bool(newer_completed),
+ )
+
+ assert registration_module._should_publish_prepared_generation(_activity_inputs()) is expected
+
+
+def test_copy_activity_registers_when_prepared_generation_is_no_longer_current(monkeypatch):
monkeypatch.setattr(
registration_module,
"_copy_prepared_parquet_files",
lambda source_uri, landing_uri: ([f"{landing_uri}/file.parquet"], 100),
)
monkeypatch.setattr(registration_module, "_prepared_generation_is_current", lambda inputs: False)
+ monkeypatch.setattr(registration_module, "_should_publish_prepared_generation", lambda inputs: True)
+ conn = MagicMock()
+
+ def execute(query: object) -> MagicMock:
+ if "SELECT count(*) FROM" in str(query):
+ return MagicMock(fetchone=MagicMock(return_value=(1,)))
+ return MagicMock()
+
+ conn.execute.side_effect = execute
monkeypatch.setattr(
registration_module,
"_connect_to_duckgres_for_team",
- MagicMock(side_effect=AssertionError("stale generations must not update the catalog")),
+ lambda team_id: contextlib.nullcontext(conn),
)
+ monkeypatch.setattr(registration_module, "setup_duckgres_session", MagicMock())
heartbeater = MagicMock()
heartbeater.__enter__ = MagicMock(return_value=heartbeater)
heartbeater.__exit__ = MagicMock(return_value=False)
monkeypatch.setattr(registration_module, "HeartbeaterSync", MagicMock(return_value=heartbeater))
- stale_counter = MagicMock()
- stale_metric = MagicMock(return_value=stale_counter)
- monkeypatch.setattr(registration_module, "get_ducklake_register_data_imports_stale_metric", stale_metric)
workload_metrics = _mock_activity_workload_metrics(monkeypatch)
- assert copy_and_register_ducklake_data_imports_activity(_activity_inputs()) is False
- stale_metric.assert_called_once_with(team_id=1, schema_id="schema", stage="post_copy")
- stale_counter.add.assert_called_once_with(1)
- workload_metrics.files.record.assert_not_called()
- workload_metrics.rows.record.assert_not_called()
- workload_metrics.bytes.record.assert_not_called()
+ assert copy_and_register_ducklake_data_imports_activity(_activity_inputs()) is True
+
+ executed = [str(call.args[0]) for call in conn.execute.call_args_list]
+ assert any("ducklake_add_data_files" in query for query in executed)
+ assert sum("RENAME TO" in query for query in executed) == 2
+ workload_metrics.files.record.assert_called_once_with(1.0)
+ workload_metrics.rows.record.assert_called_once_with(1.0)
+ workload_metrics.bytes.record.assert_called_once_with(100.0)
def test_copy_activity_does_not_publish_a_row_count_mismatch_when_cleanup_fails(monkeypatch):
@@ -515,14 +554,13 @@ def test_copy_activity_does_not_publish_a_row_count_mismatch_when_cleanup_fails(
assert not any("RENAME TO" in query for query in executed)
-def test_copy_activity_cleans_shadow_when_generation_becomes_stale_before_publish(monkeypatch):
+def test_copy_activity_skips_publish_when_newer_generation_already_landed(monkeypatch):
monkeypatch.setattr(
registration_module,
"_copy_prepared_parquet_files",
lambda source_uri, landing_uri: ([f"{landing_uri}/file.parquet"], 100),
)
- freshness = MagicMock(side_effect=[True, False])
- monkeypatch.setattr(registration_module, "_prepared_generation_is_current", freshness)
+ monkeypatch.setattr(registration_module, "_should_publish_prepared_generation", lambda inputs: False)
conn = MagicMock()
def execute(query: object) -> MagicMock:
@@ -548,8 +586,8 @@ def test_copy_activity_cleans_shadow_when_generation_becomes_stale_before_publis
assert copy_and_register_ducklake_data_imports_activity(_activity_inputs()) is False
executed = [str(call.args[0]) for call in conn.execute.call_args_list]
- assert freshness.call_count == 2
conn.transaction.assert_not_called()
+ assert any("ducklake_add_data_files" in query for query in executed)
assert sum("DROP TABLE IF EXISTS" in query and "__ph_register_" in query for query in executed) == 1
assert not any("RENAME TO" in query for query in executed)
stale_metric.assert_called_once_with(team_id=1, schema_id="schema", stage="publish")