: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(managed-warehouse): serialize register and extend timeout (#82987)
Eric Duong4b846195dc09
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.mdindex c58d00a3557c..39f1fef964aa 100644--- a/products/managed_warehouse/backend/README.md+++ b/products/managed_warehouse/backend/README.md@@ -86,7 +86,7 @@ Every copy is written to a deterministic schema inside DuckLake. Each workflow nDuckgres stores a table-naming version on the organization. Organizations that existed when versioning was introduced keep the batch sink's snake-case format, such as `tik_tok_ads_ad_report`. New organizations use the copy workflow format, such as `tiktokads_ad_report`. Copy, registration, the batch sink, and query binding derive the same physical name from that organization-level policy. Do not change the policy after an organization has written data unless the underlying tables are migrated at the same time.-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.+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. The workflow id is one per schema, so a later start is skipped while a run is in flight. The next import after that run finishes can start.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.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.pyindex e1415e5c8570..0347a16383ef 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@@ -73,6 +73,10 @@ _DUCKGRES_CANCEL_MARGIN = dt.timedelta(minutes=1)_DUCKGRES_CANCEL_MAX_ATTEMPTS = 10_DUCKGRES_CANCEL_RETRY_SECONDS = 0.5_DUCKGRES_CANCEL_TIMEOUT_SECONDS = 5.0+# Duckgres cancel fires one minute before this deadline. One attempt: a+# StartToClose timeout has an unknown catalog outcome, so a retry could race+# the original CALL.+_REGISTER_COPY_START_TO_CLOSE = dt.timedelta(hours=4)_SOURCE_JOB_STATE_PATCH_ID = "ducklake-register-source-job-state-2026-08"@@ -395,28 +399,15 @@ def _generation_token(prepared_queryable_folder: str) -> str:return hashlib.sha256(prepared_queryable_folder.encode()).hexdigest()[:12]-def build_register_data_imports_workflow_id(- *,- team_id: int,- schema_id: str,- job_id: str,- prepared_queryable_folder: str,-) -> str:- """Workflow id for one registration attempt, scoped to a single prepared generation.-- The generation belongs in the id because one job can publish several prepared- generations: the v3 load consumer re-runs post-load on a redelivered final batch, and- each run mints a new timestamped queryable folder. A job-scoped id makes every- generation after the first collide with the in-flight run, and the caller treats- WorkflowAlreadyStartedError as "already handled" and drops the trigger. The in-flight- run is pinned to the older generation and correctly refuses to publish it, so the- newest generation reaches DuckLake only on the next sync. Including the generation- gives each one its own run, and a same-generation duplicate still coalesces, which is- what that error should mean.+def build_register_data_imports_workflow_id(*, team_id: int, schema_id: str) -> str:+ """Workflow id for one in-flight registration per schema.++ Callers treat WorkflowAlreadyStartedError as "already running" and drop the+ trigger. Job and generation stay out of the id so a later sync cannot start+ until this run finishes. The next import after that can start and pick up+ the latest prepared folder."""- return (- f"ducklake-register-data-imports-{team_id}-{schema_id}-{job_id}-{_generation_token(prepared_queryable_folder)}"- )+ return f"ducklake-register-data-imports-{team_id}-{schema_id}"def _resolve_data_imports_landing_uri(@@ -865,9 +856,8 @@ class DuckLakeRegisterDataImportsWorkflow(PostHogWorkflow):copy_applied = await workflow.execute_activity(copy_and_register_ducklake_data_imports_activity,activity_inputs,- start_to_close_timeout=dt.timedelta(hours=1),+ start_to_close_timeout=_REGISTER_COPY_START_TO_CLOSE,heartbeat_timeout=dt.timedelta(minutes=2),- # A StartToClose timeout has an unknown Duckgres outcome, so a retry could race the original query.retry_policy=RetryPolicy(maximum_attempts=1),)if not copy_applied: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.pyindex 39de770ae5b2..501b7164a70b 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@@ -690,7 +690,7 @@ async def test_workflow_records_end_to_end_duration_after_gate(monkeypatch):for call in execute_activity.await_args_listif call.args[0] is copy_and_register_ducklake_data_imports_activity)- assert registration_call.kwargs["start_to_close_timeout"] == dt.timedelta(hours=1)+ assert registration_call.kwargs["start_to_close_timeout"] == dt.timedelta(hours=4)assert registration_call.kwargs["retry_policy"].maximum_attempts == 1assert _recorded_source_job_statuses(execute_activity) == [registration_module.ManagedWarehouseSourceJobStatus.RUNNING,@@ -901,40 +901,20 @@ def _recorded_source_job_statuses(execute_activity: AsyncMock) -> list[ManagedWa]-def _workflow_id(prepared_queryable_folder: str) -> str:- return build_register_data_imports_workflow_id(- team_id=473662,- schema_id="019ef5df-e4c7-0000-b543-8ef7f13b5f15",- job_id="019fb012-26e7-0000-2959-704b254131bd",- prepared_queryable_folder=prepared_queryable_folder,- )-+def test_workflow_id_is_stable_for_one_schema():+ schema_id = "019ef5df-e4c7-0000-b543-8ef7f13b5f15"- [- (- "timestamped",- "customer_balance_transaction__query_1785365519_02076d94",- "customer_balance_transaction__query_1785365530_d3277966",- ),- (- "untimestamped",- "customer_balance_transaction__query",- "customer_balance_transaction__query_legacy",- ),- ]-)-def test_workflow_id_differs_per_prepared_generation(_name, earlier_folder, later_folder):- earlier = _workflow_id(earlier_folder)- later = _workflow_id(later_folder)+ first = build_register_data_imports_workflow_id(team_id=473662, schema_id=schema_id)+ second = build_register_data_imports_workflow_id(team_id=473662, schema_id=schema_id)- assert earlier != later+ assert first == second+ assert first == f"ducklake-register-data-imports-473662-{schema_id}"-def test_workflow_id_is_stable_for_one_prepared_generation():- folder = "customer_balance_transaction__query_1785365530_d3277966"+def test_workflow_id_differs_across_schemas():+ team_id = 473662- first = _workflow_id(folder)- second = _workflow_id(folder)+ first = build_register_data_imports_workflow_id(team_id=team_id, schema_id="019ef5df-e4c7-0000-b543-8ef7f13b5f15")+ second = build_register_data_imports_workflow_id(team_id=team_id, schema_id="019ef5df-e4c8-0000-b543-8ef7f13b5f16")- assert first == second+ assert first != seconddiff --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 c3da09d60869..42bbc360bb2e 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@@ -35,6 +35,7 @@ from products.managed_warehouse.backend.facade.temporal import (DuckLakeCopyDataImportsWorkflow,DuckLakeRegisterDataImportsInputs,DuckLakeRegisterDataImportsWorkflow,+ build_register_data_imports_workflow_id,)from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import (@@ -840,8 +841,9 @@ class ExternalDataJobWorkflow(PostHogWorkflow):schema_id=inputs.external_data_schema_id,prepared_queryable_folder=prepared_queryable_folder,),- id=(- f"ducklake-register-data-imports-{inputs.team_id}-{inputs.external_data_schema_id}-{job_id}"+ id=build_register_data_imports_workflow_id(+ team_id=inputs.team_id,+ schema_id=str(inputs.external_data_schema_id),),task_queue=settings.DUCKLAKE_TASK_QUEUE,parent_close_policy=workflow.ParentClosePolicy.ABANDON,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.pyindex 1b3ebbe7a85c..8c419b266aeb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -578,8 +578,6 @@ def _trigger_ducklake_register_data_imports(export_signal: ExportSignalMessage,id=build_register_data_imports_workflow_id(team_id=export_signal.team_id,schema_id=export_signal.schema_id,- job_id=export_signal.job_id,- prepared_queryable_folder=prepared_queryable_folder,),task_queue=settings.DUCKLAKE_TASK_QUEUE,)@@ -592,8 +590,8 @@ def _trigger_ducklake_register_data_imports(export_signal: ExportSignalMessage,external_data_job_id=export_signal.job_id,)except WorkflowAlreadyStartedError:- # The id is scoped to this prepared generation, so a collision means this exact- # generation is already being registered and dropping the duplicate is correct.+ # The id is one per schema, so a collision means a register is already+ # in flight. The next import after that run finishes can start.logger.info("ducklake_registration_workflow_already_started",team_id=export_signal.team_id,@@ -762,7 +760,6 @@ def _process_message_reported(progress_callback: Callable[[], None] | None,verify_ownership: Callable[[], None] | None,) -> None:-# Reconnect stale app-DB connections up front so the ORM queries below don't burn all batch attempts.close_old_connections()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.pyindex d675c98612fe..a1cbcb67ace0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py@@ -602,7 +602,7 @@ class TestPostImportTrigger:# Any start failure (e.g. no Temporal env vars on the load deployment) must# not fail the load; it is logged and captured.("start_failure_is_captured", RuntimeError("no temporal"), True),- # An id collision means a prior delivery already started this job's run.+ # An id collision means a register is already in flight for this schema.("already_started_is_benign", WorkflowAlreadyStartedError("wf-id", "wf-type"), False),])