: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): batch ducklake add_data_files registration (#83424)
Eric Duong2444e5bf75e9
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.mdindex 39f1fef964aa..dfdcc60ac67c 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. 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.+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. Schema creation still uses one recursive Parquet glob. File registration calls `ducklake_add_data_files` in batches of copied object paths so each catalog transaction stays short. 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 d2e25674ef32..6b0d412d8327 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@@ -10,7 +10,7 @@ import datetime as dtimport threadingimport contextlibimport dataclasses-from collections.abc import Iterator+from collections.abc import Iterator, Sequencefrom django.conf import settingsfrom django.db import close_old_connections@@ -68,6 +68,9 @@ DUCKLAKE_DATA_IMPORTS_REGISTRATION_WORKFLOW_FLAG = "ducklake-data-imports-registDATA_IMPORTS_GENERATIONS_PREFIX = "_imports"DUCKLAKE_REGISTER_STAGE_DURATION_METRIC = "ducklake_register_data_imports_stage_duration"S3_COPY_BATCH_SIZE = 16+# One CALL per batch. A generation-wide glob runs parquet_full_metadata on the+# DuckLake metadata connection and can stall there for large file counts.+_ADD_DATA_FILES_BATCH_SIZE = 200_PARQUET_FILE_GLOB = "**/*.[pP][aA][rR][qQ][uU][eE][tT]"_DUCKGRES_CANCEL_MARGIN = dt.timedelta(minutes=1)_DUCKGRES_CANCEL_MAX_ATTEMPTS = 10@@ -624,6 +627,20 @@ def _raise_if_duckgres_cancel_requested(cancel_requested: threading.Event | Noneraise TimeoutError("Duckgres registration reached the Temporal activity deadline")+def _add_data_files_path_batches(landing_paths: Sequence[str], *, batch_size: int | None = None) -> list[list[str]]:+ resolved_batch_size = _ADD_DATA_FILES_BATCH_SIZE if batch_size is None else batch_size+ if resolved_batch_size < 1:+ raise ValueError("add_data_files batch size must be at least 1")+ return [+ list(landing_paths[index : index + resolved_batch_size])+ for index in range(0, len(landing_paths), resolved_batch_size)+ ]+++def _duckdb_varchar_list_literal(values: Sequence[str]) -> psql.Composed:+ return psql.SQL("[{}]").format(psql.SQL(", ").join(psql.Literal(value) for value in values))++def _register_prepared_parquet_files(inputs: DuckLakeRegisterDataImportsActivityInputs,conn: psycopg.Connection,@@ -671,17 +688,19 @@ def _register_prepared_parquet_files())_raise_if_duckgres_cancel_requested(cancel_requested)- conn.execute(- psql.SQL(- "CALL ducklake_add_data_files({}, {}, {}, schema => {}, "- "allow_missing => true, hive_partitioning => true)"- ).format(- psql.Literal("ducklake"),- psql.Literal(registration_names.shadow_name),- parquet_glob,- psql.Literal(schema_name),+ for path_batch in _add_data_files_path_batches(landing_paths):+ _raise_if_duckgres_cancel_requested(cancel_requested)+ conn.execute(+ psql.SQL(+ "CALL ducklake_add_data_files({}, {}, {}, schema => {}, "+ "allow_missing => true, hive_partitioning => true)"+ ).format(+ psql.Literal("ducklake"),+ psql.Literal(registration_names.shadow_name),+ _duckdb_varchar_list_literal(path_batch),+ psql.Literal(schema_name),+ ))- )with _stage_timer(stage="verify", team_id=inputs.team_id, schema_id=inputs.metadata.source_schema_id):_raise_if_duckgres_cancel_requested(cancel_requested)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 d6fd244abab9..c3cc1c3cb027 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@@ -279,10 +279,10 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke"s3://ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/""1234567890_abcdef12/**/*.[pP][aA][rR][qQ][uU][eE][tT]")- assert parquet_glob in registration_query- assert sum(parquet_glob in query for query in executed) == 3- assert not any(first_path in query for query in executed)- assert not any(second_path in query for query in executed)+ assert first_path in registration_query+ assert second_path in registration_query+ assert parquet_glob not in registration_query+ assert sum(parquet_glob in query for query in executed) == 2assert len(verification_indexes) == 2assert len(rename_indexes) == 2assert max(registration_indexes) < min(verification_indexes)@@ -443,12 +443,46 @@ def test_registration_stops_after_glob_query_cancellation(monkeypatch):executed = [str(call.args[0]) for call in conn.execute.call_args_list]registration_queries = [query for query in executed if "ducklake_add_data_files" in query]assert len(registration_queries) == 1- assert f"{landing_uri}/{registration_module._PARQUET_FILE_GLOB}" in registration_queries[0]+ assert landing_paths[0] in registration_queries[0]+ assert f"{landing_uri}/{registration_module._PARQUET_FILE_GLOB}" not in registration_queries[0]assert not any("SELECT count(*)" in query for query in executed)assert sum("DROP TABLE" in query and "__ph_register_" in query for query in executed) == 1assert not any("RENAME TO" in query for query in executed)+def test_registration_splits_add_data_files_across_path_batches(monkeypatch):+ monkeypatch.setattr(registration_module, "setup_duckgres_session", MagicMock())+ monkeypatch.setattr(registration_module, "_ADD_DATA_FILES_BATCH_SIZE", 1)+ monkeypatch.setattr(registration_module, "_should_publish_prepared_generation", lambda inputs: True)+ conn = MagicMock()++ def execute(query: object) -> MagicMock:+ result = MagicMock()+ result.fetchone.return_value = (2,)+ return result++ conn.execute.side_effect = execute+ landing_uri = registration_module._generation_scoped_landing_uri(+ _activity_inputs().metadata.landing_uri,+ job_id=_activity_inputs().job_id,+ prepared_queryable_folder=_activity_inputs().metadata.prepared_queryable_folder,+ )+ landing_paths = [f"{landing_uri}/{name}.parquet" for name in ("first", "second")]++ registration_module._register_prepared_parquet_files(_activity_inputs(), conn, landing_paths)++ executed = [str(call.args[0]) for call in conn.execute.call_args_list]+ registration_queries = [query for query in executed if "ducklake_add_data_files" in query]+ parquet_glob = f"{landing_uri}/{registration_module._PARQUET_FILE_GLOB}"+ assert len(registration_queries) == 2+ assert landing_paths[0] in registration_queries[0]+ assert landing_paths[1] not in registration_queries[0]+ assert landing_paths[1] in registration_queries[1]+ assert landing_paths[0] not in registration_queries[1]+ assert not any(parquet_glob in query for query in registration_queries)+ assert sum(parquet_glob in query for query in executed) == 2++@pytest.mark.parametrize(("is_current", "newer_completed", "expected"),[