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): reduce DuckLake registration stalls (#80981)

Eric Duongb9a0729f733e
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.md
index c0fce2419eb9..d60883fd0de6 100644
--- a/products/managed_warehouse/backend/README.md
+++ b/products/managed_warehouse/backend/README.md
@@ -74,11 +74,11 @@ Every copy is written to a deterministic schema inside DuckLake. Each workflow n
- **Schema**: `posthog_data_imports_team_<team_id>`
- **Table**: a physical name derived from the organization's naming version
- **Example**: `ducklake.posthog_data_imports_team_123.stripe_prod_invoices`
-- **Registered files**: `s3://<ducklake-bucket>/<ducklake-schema>/<ducklake-table>/_imports/<source-schema-id>/<job-id>/<prepared-relative-path>`
+- **Registered files**: `s3://<ducklake-bucket>/<ducklake-schema>/<ducklake-table>/_imports/<source-schema-id>/<job-id>/<generation-token>/<prepared-relative-path>`
Duckgres 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, registers the destination objects with `ducklake_add_data_files`, verifies the shadow table's row count, and only then swaps it into the stable table name through the Duckgres PostgreSQL connection. Registration, verification, and the swap share one catalog transaction, so a mismatch leaves the previous table live. Each import job gets its own object prefix and child workflow ID, so a later sync does not append into the previous snapshot.
+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, registers the destination objects with `ducklake_add_data_files`, verifies the shadow table's row count, and only then swaps it into the stable table name through the Duckgres PostgreSQL connection. Registration and verification use autocommitted catalog statements. 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. Registration supplies that immutable prefix to DuckLake as one recursive glob so DuckDB can inspect the files in one parallel metadata scan.
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.
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 369090c25163..b781286a79d2 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
@@ -65,6 +65,7 @@ DUCKLAKE_DATA_IMPORTS_REGISTRATION_WORKFLOW_FLAG = "ducklake-data-imports-regist
DATA_IMPORTS_GENERATIONS_PREFIX = "_imports"
DUCKLAKE_REGISTER_STAGE_DURATION_METRIC = "ducklake_register_data_imports_stage_duration"
S3_COPY_BATCH_SIZE = 16
+_PARQUET_FILE_GLOB = "**/*.[pP][aA][rR][qQ][uU][eE][tT]"
_SOURCE_JOB_STATE_PATCH_ID = "ducklake-register-source-job-state-2026-08"
@@ -295,6 +296,7 @@ async def prepare_ducklake_data_imports_registration_activity(
ducklake_table_name=ducklake_table_name,
source_schema_id=str(inputs.schema_id),
job_id=inputs.job_id,
+ prepared_queryable_folder=inputs.prepared_queryable_folder,
)
return DuckLakeRegisterDataImportsMetadata(
source_schema_id=str(schema.id),
@@ -322,10 +324,15 @@ def copy_and_register_ducklake_data_imports_activity(inputs: DuckLakeRegisterDat
logger=logger,
)
with heartbeater:
+ landing_uri = _generation_scoped_landing_uri(
+ inputs.metadata.landing_uri,
+ job_id=inputs.job_id,
+ prepared_queryable_folder=inputs.metadata.prepared_queryable_folder,
+ )
with _stage_timer(stage="copy", team_id=inputs.team_id, schema_id=schema_id):
landing_paths, copied_bytes = _copy_prepared_parquet_files(
inputs.metadata.prepared_source_uri,
- inputs.metadata.landing_uri,
+ landing_uri,
)
if not _prepared_generation_is_current(inputs):
get_ducklake_register_data_imports_stale_metric(
@@ -358,7 +365,7 @@ def copy_and_register_ducklake_data_imports_activity(inputs: DuckLakeRegisterDat
"Copied, verified, and registered prepared Parquet files in DuckLake",
ducklake_table=f"{inputs.metadata.ducklake_schema_name}.{inputs.metadata.ducklake_table_name}",
file_count=len(landing_paths),
- landing_uri=inputs.metadata.landing_uri,
+ landing_uri=landing_uri,
)
return True
@@ -411,6 +418,7 @@ def _resolve_data_imports_landing_uri(
ducklake_table_name: str,
source_schema_id: str,
job_id: str,
+ prepared_queryable_folder: str,
) -> str:
if is_dev_mode():
bucket = get_config().get("DUCKLAKE_BUCKET")
@@ -421,10 +429,33 @@ def _resolve_data_imports_landing_uri(
raise ApplicationError(f"No S3 bucket configured for team {team_id}", non_retryable=True)
safe_job_id = re.sub(r"[^A-Za-z0-9_-]", "_", str(job_id))
- return (
+ job_landing_uri = (
f"s3://{bucket}/{ducklake_schema_name}/{ducklake_table_name}/"
f"{DATA_IMPORTS_GENERATIONS_PREFIX}/{source_schema_id}/{safe_job_id}"
)
+ return _generation_scoped_landing_uri(
+ job_landing_uri,
+ job_id=job_id,
+ prepared_queryable_folder=prepared_queryable_folder,
+ )
+
+
+def _generation_scoped_landing_uri(
+ landing_uri: str,
+ *,
+ job_id: str,
+ prepared_queryable_folder: str,
+) -> str:
+ normalized_uri = landing_uri.rstrip("/")
+ safe_job_id = re.sub(r"[^A-Za-z0-9_-]", "_", str(job_id))
+ generation_token = _generation_token(prepared_queryable_folder)
+ generation_suffix = f"/{safe_job_id}/{generation_token}"
+ if normalized_uri.endswith(generation_suffix):
+ return normalized_uri
+ if normalized_uri.endswith(f"/{safe_job_id}"):
+ # Activity inputs can outlive worker deployments, so accept a recorded job-scoped URI.
+ return f"{normalized_uri}/{generation_token}"
+ raise ApplicationError("DuckLake landing URI does not match the registration job", non_retryable=True)
def _copy_prepared_parquet_files(source_uri: str, landing_uri: str) -> tuple[list[str], int]:
@@ -496,35 +527,36 @@ def _register_prepared_parquet_files(
) -> int:
schema_name = inputs.metadata.ducklake_schema_name
table_name = inputs.metadata.ducklake_table_name
- shadow_name = _data_imports_shadow_table_name(inputs)
- parquet_paths = psql.SQL("[{}]").format(psql.SQL(", ").join(psql.Literal(path) for path in landing_paths))
- partition_columns = _hive_partition_columns(inputs.metadata.landing_uri, landing_paths)
+ registration_names = _new_registration_table_names()
+ landing_uri = _generation_scoped_landing_uri(
+ inputs.metadata.landing_uri,
+ job_id=inputs.job_id,
+ prepared_queryable_folder=inputs.metadata.prepared_queryable_folder,
+ )
+ parquet_glob = psql.Literal(f"{landing_uri}/{_PARQUET_FILE_GLOB}")
+ partition_columns = _hive_partition_columns(landing_uri, landing_paths)
setup_duckgres_session(conn, extensions=("ducklake", "httpfs"))
- with conn.transaction():
+ shadow_is_published = False
+ publish_attempted = False
+ try:
with _stage_timer(stage="register", team_id=inputs.team_id, schema_id=inputs.metadata.source_schema_id):
conn.execute(psql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(psql.Identifier(schema_name)))
- conn.execute(
- psql.SQL("DROP TABLE IF EXISTS {}.{}").format(
- psql.Identifier(schema_name),
- psql.Identifier(shadow_name),
- )
- )
conn.execute(
psql.SQL(
"CREATE TABLE {}.{} AS SELECT * FROM "
"read_parquet({}, union_by_name=true, hive_partitioning=true) LIMIT 0"
).format(
psql.Identifier(schema_name),
- psql.Identifier(shadow_name),
- parquet_paths,
+ psql.Identifier(registration_names.shadow_name),
+ parquet_glob,
)
)
if partition_columns:
conn.execute(
psql.SQL("ALTER TABLE {}.{} SET PARTITIONED BY ({})").format(
psql.Identifier(schema_name),
- psql.Identifier(shadow_name),
+ psql.Identifier(registration_names.shadow_name),
psql.SQL(", ").join(psql.Identifier(column) for column in partition_columns),
)
)
@@ -534,8 +566,8 @@ def _register_prepared_parquet_files(
"allow_missing => true, hive_partitioning => true)"
).format(
psql.Literal("ducklake"),
- psql.Literal(shadow_name),
- parquet_paths,
+ psql.Literal(registration_names.shadow_name),
+ parquet_glob,
psql.Literal(schema_name),
)
)
@@ -543,13 +575,13 @@ def _register_prepared_parquet_files(
with _stage_timer(stage="verify", team_id=inputs.team_id, schema_id=inputs.metadata.source_schema_id):
source_row = conn.execute(
psql.SQL("SELECT count(*) FROM read_parquet({}, union_by_name=true, hive_partitioning=true)").format(
- parquet_paths
+ parquet_glob
)
).fetchone()
registered_row = conn.execute(
psql.SQL("SELECT count(*) FROM {}.{}").format(
psql.Identifier(schema_name),
- psql.Identifier(shadow_name),
+ psql.Identifier(registration_names.shadow_name),
)
).fetchone()
source_count = int(source_row[0]) if source_row else 0
@@ -564,19 +596,25 @@ 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:
if _prepared_generation_is_current(inputs):
- conn.execute(
- psql.SQL("DROP TABLE IF EXISTS {}.{}").format(
- psql.Identifier(schema_name),
- psql.Identifier(table_name),
+ publish_attempted = True
+ # Keep this transaction limited to publication. DuckLake flushes staged file
+ # metadata at commit, so including registration makes the catalog commit expensive.
+ with conn.transaction():
+ conn.execute(
+ psql.SQL("ALTER TABLE IF EXISTS {}.{} RENAME TO {}").format(
+ psql.Identifier(schema_name),
+ psql.Identifier(table_name),
+ psql.Identifier(registration_names.previous_name),
+ )
)
- )
- conn.execute(
- psql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(
- psql.Identifier(schema_name),
- psql.Identifier(shadow_name),
- psql.Identifier(table_name),
+ conn.execute(
+ psql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(
+ psql.Identifier(schema_name),
+ psql.Identifier(registration_names.shadow_name),
+ psql.Identifier(table_name),
+ )
)
- )
+ shadow_is_published = True
else:
timer.set_status("STALE")
generation_is_stale = True
@@ -584,13 +622,43 @@ def _register_prepared_parquet_files(
if generation_is_stale:
raise _StalePreparedGenerationError
- return registered_count
+ return registered_count
+ finally:
+ cleanup_names = [registration_names.previous_name] if publish_attempted else []
+ if not shadow_is_published:
+ cleanup_names.insert(0, registration_names.shadow_name)
+ _cleanup_registration_tables(conn, schema_name, cleanup_names)
+
+
[email protected](frozen=True, kw_only=True)
+class _RegistrationTableNames:
+ shadow_name: str
+ previous_name: str
-def _data_imports_shadow_table_name(inputs: DuckLakeRegisterDataImportsActivityInputs) -> str:
- schema_fragment = re.sub(r"[^A-Za-z0-9]", "", inputs.metadata.source_schema_id)[:8]
- job_fragment = re.sub(r"[^A-Za-z0-9]", "", inputs.job_id)[:8]
- return f"__ph_register_{schema_fragment}_{job_fragment}"
+def _new_registration_table_names() -> _RegistrationTableNames:
+ attempt_token = uuid.uuid4().hex
+ return _RegistrationTableNames(
+ shadow_name=f"__ph_register_{attempt_token}",
+ previous_name=f"__ph_previous_{attempt_token}",
+ )
+
+
+def _cleanup_registration_tables(conn: psycopg.Connection, schema_name: str, table_names: list[str]) -> None:
+ for table_name in table_names:
+ try:
+ conn.execute(
+ psql.SQL("DROP TABLE IF EXISTS {}.{}").format(
+ psql.Identifier(schema_name),
+ psql.Identifier(table_name),
+ )
+ )
+ except Exception:
+ LOGGER.warning(
+ "Failed to clean up DuckLake registration table",
+ table_name=f"{schema_name}.{table_name}",
+ exc_info=True,
+ )
def _hive_partition_columns(landing_uri: str, landing_paths: list[str]) -> list[str]:
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 0ed9060df2a5..ed56cc200984 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
@@ -1,6 +1,7 @@
import uuid
import datetime as dt
import contextlib
+from collections.abc import Iterator
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -136,12 +137,33 @@ async def test_prepare_registration_pins_the_import_jobs_prepared_generation(ate
folder_path = await database_sync_to_async(schema.folder_path)()
assert metadata.prepared_source_uri.endswith(f"/{folder_path}/{prepared_queryable_folder}")
assert metadata.landing_uri == (
- f"s3://ducklake-dev/posthog_data_imports_team_{ateam.id}/postgres_customers/_imports/{schema.id}/job-123"
+ f"s3://ducklake-dev/posthog_data_imports_team_{ateam.id}/postgres_customers/"
+ f"_imports/{schema.id}/job-123/1234567890_abcdef12"
)
assert metadata.ducklake_schema_name == f"posthog_data_imports_team_{ateam.id}"
assert metadata.ducklake_table_name == "postgres_customers"
+ [
+ (
+ "job_scoped",
+ "s3://ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job",
+ ),
+ (
+ "generation_scoped",
+ "s3://ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/1234567890_abcdef12",
+ ),
+ ]
+)
+def test_landing_uri_normalizes_to_prepared_generation(_name: str, landing_uri: str) -> None:
+ assert registration_module._generation_scoped_landing_uri(
+ landing_uri,
+ job_id="job",
+ prepared_queryable_folder="customers__query_1234567890_abcdef12",
+ ) == ("s3://ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/1234567890_abcdef12")
+
+
def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monkeypatch):
class FakeS3:
def __init__(self) -> None:
@@ -166,11 +188,26 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke
conn = MagicMock()
conn.__enter__ = MagicMock(return_value=conn)
conn.__exit__ = MagicMock(return_value=False)
- conn.transaction.return_value.__enter__ = MagicMock()
- conn.transaction.return_value.__exit__ = MagicMock(return_value=False)
+ active_transaction: object | None = None
+ transaction_tokens: list[object] = []
+ executed_with_transactions: list[tuple[str, object | None]] = []
+
+ @contextlib.contextmanager
+ def transaction() -> Iterator[None]:
+ nonlocal active_transaction
+ transaction_token = object()
+ transaction_tokens.append(transaction_token)
+ active_transaction = transaction_token
+ try:
+ yield
+ finally:
+ active_transaction = None
+
+ conn.transaction.side_effect = transaction
def execute(query: object) -> MagicMock:
query_text = str(query)
+ executed_with_transactions.append((query_text, active_transaction))
if "SELECT count(*) FROM read_parquet" in query_text:
return MagicMock(fetchone=MagicMock(return_value=(2,)))
if "SELECT count(*) FROM" in query_text:
@@ -203,14 +240,14 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke
assert s3.copy_calls == [
(
[
- "source/team/customers__query/_ph_partition_key=2026-07/a.parquet",
- "source/team/customers__query/_ph_partition_key=2026-08/b.parquet",
+ "source/team/customers__query_1234567890_abcdef12/_ph_partition_key=2026-07/a.parquet",
+ "source/team/customers__query_1234567890_abcdef12/_ph_partition_key=2026-08/b.parquet",
],
[
"ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/"
- "_ph_partition_key=2026-07/a.parquet",
+ "1234567890_abcdef12/_ph_partition_key=2026-07/a.parquet",
"ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/"
- "_ph_partition_key=2026-08/b.parquet",
+ "1234567890_abcdef12/_ph_partition_key=2026-08/b.parquet",
],
S3_COPY_BATCH_SIZE,
)
@@ -218,17 +255,37 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke
executed = [str(call.args[0]) for call in conn.execute.call_args_list]
registration_indexes = [index for index, query in enumerate(executed) if "ducklake_add_data_files" in query]
verification_indexes = [index for index, query in enumerate(executed) if "SELECT count(*) FROM" in query]
- drop_live_index = next(
- index for index, query in enumerate(executed) if "DROP TABLE IF EXISTS" in query and "customers" in query
+ rename_indexes = [index for index, query in enumerate(executed) if "RENAME TO" in query]
+ previous_cleanup_index = next(
+ index for index, query in enumerate(executed) if "DROP TABLE IF EXISTS" in query and "__ph_previous_" in query
)
- rename_index = next(index for index, query in enumerate(executed) if "RENAME TO" in query)
assert len(registration_indexes) == 1
registration_query = executed[registration_indexes[0]]
- assert "_ph_partition_key=2026-07/a.parquet" in registration_query
- assert "_ph_partition_key=2026-08/b.parquet" in registration_query
+ parquet_glob = (
+ "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("_ph_partition_key=2026-07/a.parquet" in query for query in executed)
+ assert not any("_ph_partition_key=2026-08/b.parquet" in query for query in executed)
assert len(verification_indexes) == 2
+ assert len(rename_indexes) == 2
assert max(registration_indexes) < min(verification_indexes)
- assert max(verification_indexes) < drop_live_index < rename_index
+ assert max(verification_indexes) < min(rename_indexes)
+ assert max(rename_indexes) < previous_cleanup_index
+ assert "ALTER TABLE IF EXISTS" in executed[rename_indexes[0]]
+ assert "postgres_customers" in executed[rename_indexes[0]]
+ assert "__ph_previous_" in executed[rename_indexes[0]]
+ assert executed[rename_indexes[0]].index("postgres_customers") < executed[rename_indexes[0]].index("__ph_previous_")
+ assert "__ph_register_" in executed[rename_indexes[1]]
+ assert "postgres_customers" in executed[rename_indexes[1]]
+ assert executed[rename_indexes[1]].index("__ph_register_") < executed[rename_indexes[1]].index("postgres_customers")
+ assert len(transaction_tokens) == 1
+ assert [query for query, token in executed_with_transactions if token is transaction_tokens[0]] == [
+ executed[index] for index in rename_indexes
+ ]
+ conn.transaction.assert_called_once_with()
assert any("SET PARTITIONED BY" in query for query in executed)
workload_metrics.files_getter.assert_called_once_with(team_id=1, schema_id="schema")
workload_metrics.rows_getter.assert_called_once_with(team_id=1, schema_id="schema")
@@ -267,7 +324,7 @@ def test_copy_activity_does_not_touch_catalog_for_stale_generation(monkeypatch):
workload_metrics.bytes.record.assert_not_called()
-def test_copy_activity_does_not_publish_a_row_count_mismatch(monkeypatch):
+def test_copy_activity_does_not_publish_a_row_count_mismatch_when_cleanup_fails(monkeypatch):
monkeypatch.setattr(
registration_module,
"_copy_prepared_parquet_files",
@@ -275,13 +332,14 @@ def test_copy_activity_does_not_publish_a_row_count_mismatch(monkeypatch):
)
monkeypatch.setattr(registration_module, "_prepared_generation_is_current", lambda inputs: True)
conn = MagicMock()
- conn.transaction.return_value.__enter__ = MagicMock()
- conn.transaction.return_value.__exit__ = MagicMock(return_value=False)
counts = iter([(10,), (9,)])
def execute(query: object) -> MagicMock:
- if "SELECT count(*) FROM" in str(query):
+ query_text = str(query)
+ if "SELECT count(*) FROM" in query_text:
return MagicMock(fetchone=MagicMock(return_value=next(counts)))
+ if "DROP TABLE IF EXISTS" in query_text and "__ph_register_" in query_text:
+ raise RuntimeError("cleanup failed")
return MagicMock()
conn.execute.side_effect = execute
@@ -300,10 +358,104 @@ def test_copy_activity_does_not_publish_a_row_count_mismatch(monkeypatch):
copy_and_register_ducklake_data_imports_activity(_activity_inputs())
executed = [str(call.args[0]) for call in conn.execute.call_args_list]
- assert not any("DROP TABLE IF EXISTS" in query and "customers" in query for query in executed)
+ conn.transaction.assert_not_called()
+ 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)
+def test_copy_activity_cleans_shadow_when_generation_becomes_stale_before_publish(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)
+ conn = MagicMock()
+
+ def execute(query: object) -> MagicMock:
+ if "SELECT count(*) FROM" in str(query):
+ return MagicMock(fetchone=MagicMock(return_value=(10,)))
+ return MagicMock()
+
+ conn.execute.side_effect = execute
+ monkeypatch.setattr(
+ registration_module,
+ "_connect_to_duckgres_for_team",
+ 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)
+
+ 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 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")
+ stale_counter.add.assert_called_once_with(1)
+
+
+def test_registration_tables_are_owned_by_one_activity_attempt(monkeypatch):
+ attempt_ids = iter([uuid.UUID(int=1), uuid.UUID(int=2)])
+ monkeypatch.setattr(registration_module.uuid, "uuid4", lambda: next(attempt_ids))
+
+ first = registration_module._new_registration_table_names()
+ second = registration_module._new_registration_table_names()
+
+ assert {first.shadow_name, first.previous_name}.isdisjoint({second.shadow_name, second.previous_name})
+ assert first.shadow_name == f"__ph_register_{uuid.UUID(int=1).hex}"
+ assert first.previous_name == f"__ph_previous_{uuid.UUID(int=1).hex}"
+ assert all(
+ len(name) <= 63 for name in (first.shadow_name, first.previous_name, second.shadow_name, second.previous_name)
+ )
+
+
+def test_unknown_publish_commit_error_survives_temporary_table_cleanup(monkeypatch):
+ monkeypatch.setattr(registration_module, "_prepared_generation_is_current", lambda inputs: True)
+ monkeypatch.setattr(registration_module, "setup_duckgres_session", MagicMock())
+ conn = MagicMock()
+ commit_error = RuntimeError("commit acknowledgement lost")
+
+ @contextlib.contextmanager
+ def transaction() -> Iterator[None]:
+ yield
+ raise commit_error
+
+ conn.transaction.side_effect = transaction
+
+ def execute(query: object) -> MagicMock:
+ query_text = str(query)
+ if "SELECT count(*) FROM" in query_text:
+ return MagicMock(fetchone=MagicMock(return_value=(10,)))
+ if "DROP TABLE IF EXISTS" in query_text:
+ raise RuntimeError("cleanup unavailable")
+ return MagicMock()
+
+ conn.execute.side_effect = execute
+
+ with pytest.raises(RuntimeError) as error:
+ registration_module._register_prepared_parquet_files(
+ _activity_inputs(),
+ conn,
+ [f"{_activity_inputs().metadata.landing_uri}/file.parquet"],
+ )
+
+ assert error.value is commit_error
+ executed = [str(call.args[0]) for call in conn.execute.call_args_list]
+ assert len([query for query in executed if "RENAME TO" in query]) == 2
+ assert sum("DROP TABLE IF EXISTS" in query and "__ph_register_" in query for query in executed) == 1
+ assert sum("DROP TABLE IF EXISTS" in query and "__ph_previous_" in query for query in executed) == 1
+
+
@pytest.mark.asyncio
async def test_workflow_does_not_record_duration_when_disabled(monkeypatch):
execute_activity = AsyncMock(return_value=False)
@@ -526,8 +678,8 @@ def _activity_inputs() -> DuckLakeRegisterDataImportsActivityInputs:
job_id="job",
metadata=DuckLakeRegisterDataImportsMetadata(
source_schema_id="schema",
- prepared_queryable_folder="customers__query",
- prepared_source_uri="s3://source/team/customers__query",
+ prepared_queryable_folder="customers__query_1234567890_abcdef12",
+ prepared_source_uri="s3://source/team/customers__query_1234567890_abcdef12",
landing_uri="s3://ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job",
ducklake_schema_name="posthog_data_imports_team_1",
ducklake_table_name="postgres_customers",