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): bound DuckLake registration work (#81435)

Eric Duong9d37664279fb
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.md
index d60883fd0de6..0b41934f79e4 100644
--- a/products/managed_warehouse/backend/README.md
+++ b/products/managed_warehouse/backend/README.md
@@ -78,7 +78,7 @@ Every copy is written to a deterministic schema inside DuckLake. Each workflow n
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 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.
+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. Each file registration is autocommitted so one statement cannot accumulate metadata for the entire generation. 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.
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 b781286a79d2..d2b959eeb395 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
@@ -2,10 +2,12 @@ from __future__ import annotations
import re
import json
+import time
import uuid
import typing
import hashlib
import datetime as dt
+import threading
import contextlib
import dataclasses
from collections.abc import Iterator
@@ -66,6 +68,10 @@ 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]"
+_DUCKGRES_CANCEL_MARGIN = dt.timedelta(minutes=1)
+_DUCKGRES_CANCEL_MAX_ATTEMPTS = 10
+_DUCKGRES_CANCEL_RETRY_SECONDS = 0.5
+_DUCKGRES_CANCEL_TIMEOUT_SECONDS = 5.0
_SOURCE_JOB_STATE_PATCH_ID = "ducklake-register-source-job-state-2026-08"
@@ -310,6 +316,7 @@ async def prepare_ducklake_data_imports_registration_activity(
@activity.defn
def copy_and_register_ducklake_data_imports_activity(inputs: DuckLakeRegisterDataImportsActivityInputs) -> bool:
+ activity_started_monotonic = time.monotonic()
schema_id = inputs.metadata.source_schema_id
_bind_registration_activity_context(team_id=inputs.team_id, schema_id=schema_id, job_id=inputs.job_id)
logger = LOGGER.bind(
@@ -343,7 +350,14 @@ def copy_and_register_ducklake_data_imports_activity(inputs: DuckLakeRegisterDat
try:
with _connect_to_duckgres_for_team(inputs.team_id) as conn:
- registered_rows = _register_prepared_parquet_files(inputs, conn, landing_paths)
+ cancel_delay = _duckgres_cancel_delay(activity_started_monotonic)
+ with _cancel_duckgres_query_after(conn, cancel_delay) as cancel_requested:
+ registered_rows = _register_prepared_parquet_files(
+ inputs,
+ conn,
+ landing_paths,
+ cancel_requested=cancel_requested,
+ )
except _StalePreparedGenerationError:
get_ducklake_register_data_imports_stale_metric(
team_id=inputs.team_id, schema_id=schema_id, stage="publish"
@@ -520,10 +534,75 @@ def _connect_to_duckgres_for_team(team_id: int) -> Iterator[psycopg.Connection]:
yield conn
+def _duckgres_cancel_delay(activity_started_monotonic: float) -> float | None:
+ try:
+ start_to_close_timeout = activity.info().start_to_close_timeout
+ except RuntimeError:
+ return None
+ if start_to_close_timeout is None:
+ return None
+
+ elapsed = time.monotonic() - activity_started_monotonic
+ return max(0.0, start_to_close_timeout.total_seconds() - elapsed - _DUCKGRES_CANCEL_MARGIN.total_seconds())
+
+
+def _cancel_duckgres_query_after(
+ conn: psycopg.Connection,
+ delay_seconds: float | None,
+) -> Iterator[threading.Event]:
+ cancel_requested = threading.Event()
+ if delay_seconds is None:
+ yield cancel_requested
+ return
+ if delay_seconds <= 0:
+ raise TimeoutError("Duckgres registration started too close to the Temporal activity deadline")
+
+ stop_canceling = threading.Event()
+
+ def cancel_query() -> None:
+ if stop_canceling.is_set():
+ return
+ cancel_requested.set()
+ LOGGER.warning("Canceling Duckgres query before Temporal activity timeout")
+ cancellation_failure_logged = False
+ for attempt in range(_DUCKGRES_CANCEL_MAX_ATTEMPTS):
+ if stop_canceling.is_set():
+ return
+ try:
+ conn.cancel_safe(timeout=_DUCKGRES_CANCEL_TIMEOUT_SECONDS)
+ except Exception:
+ if not cancellation_failure_logged:
+ LOGGER.exception("Failed to cancel Duckgres query before Temporal activity timeout")
+ cancellation_failure_logged = True
+ if attempt == _DUCKGRES_CANCEL_MAX_ATTEMPTS - 1:
+ LOGGER.error("Stopped retrying Duckgres query cancellation before Temporal activity timeout")
+ return
+ if stop_canceling.wait(_DUCKGRES_CANCEL_RETRY_SECONDS):
+ return
+
+ timer = threading.Timer(delay_seconds, cancel_query)
+ timer.daemon = True
+ timer.start()
+ try:
+ yield cancel_requested
+ finally:
+ stop_canceling.set()
+ timer.cancel()
+ timer.join(timeout=_DUCKGRES_CANCEL_TIMEOUT_SECONDS + 1)
+
+
+def _raise_if_duckgres_cancel_requested(cancel_requested: threading.Event | None) -> None:
+ if cancel_requested is not None and cancel_requested.is_set():
+ raise TimeoutError("Duckgres registration reached the Temporal activity deadline")
+
+
def _register_prepared_parquet_files(
inputs: DuckLakeRegisterDataImportsActivityInputs,
conn: psycopg.Connection,
landing_paths: list[str],
+ *,
+ cancel_requested: threading.Event | None = None,
) -> int:
schema_name = inputs.metadata.ducklake_schema_name
table_name = inputs.metadata.ducklake_table_name
@@ -536,12 +615,15 @@ def _register_prepared_parquet_files(
parquet_glob = psql.Literal(f"{landing_uri}/{_PARQUET_FILE_GLOB}")
partition_columns = _hive_partition_columns(landing_uri, landing_paths)
+ _raise_if_duckgres_cancel_requested(cancel_requested)
setup_duckgres_session(conn, extensions=("ducklake", "httpfs"))
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):
+ _raise_if_duckgres_cancel_requested(cancel_requested)
conn.execute(psql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(psql.Identifier(schema_name)))
+ _raise_if_duckgres_cancel_requested(cancel_requested)
conn.execute(
psql.SQL(
"CREATE TABLE {}.{} AS SELECT * FROM "
@@ -553,6 +635,7 @@ def _register_prepared_parquet_files(
)
)
if partition_columns:
+ _raise_if_duckgres_cancel_requested(cancel_requested)
conn.execute(
psql.SQL("ALTER TABLE {}.{} SET PARTITIONED BY ({})").format(
psql.Identifier(schema_name),
@@ -560,24 +643,29 @@ def _register_prepared_parquet_files(
psql.SQL(", ").join(psql.Identifier(column) for column in partition_columns),
)
)
- 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),
+ # DuckLake flushes file and column stats at statement commit, so one call per file bounds each batch.
+ for landing_path in 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),
+ psql.Literal(landing_path),
+ 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)
source_row = conn.execute(
psql.SQL("SELECT count(*) FROM read_parquet({}, union_by_name=true, hive_partitioning=true)").format(
parquet_glob
)
).fetchone()
+ _raise_if_duckgres_cancel_requested(cancel_requested)
registered_row = conn.execute(
psql.SQL("SELECT count(*) FROM {}.{}").format(
psql.Identifier(schema_name),
@@ -595,7 +683,9 @@ 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):
+ _raise_if_duckgres_cancel_requested(cancel_requested)
publish_attempted = True
# Keep this transaction limited to publication. DuckLake flushes staged file
# metadata at commit, so including registration makes the catalog commit expensive.
@@ -607,6 +697,7 @@ def _register_prepared_parquet_files(
psql.Identifier(registration_names.previous_name),
)
)
+ _raise_if_duckgres_cancel_requested(cancel_requested)
conn.execute(
psql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(
psql.Identifier(schema_name),
@@ -741,9 +832,10 @@ class DuckLakeRegisterDataImportsWorkflow(PostHogWorkflow):
copy_applied = await workflow.execute_activity(
copy_and_register_ducklake_data_imports_activity,
activity_inputs,
- start_to_close_timeout=dt.timedelta(minutes=30),
+ start_to_close_timeout=dt.timedelta(hours=1),
heartbeat_timeout=dt.timedelta(minutes=2),
- retry_policy=RetryPolicy(maximum_attempts=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:
status = "stale"
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 ed56cc200984..d08ff465bc75 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
@@ -218,6 +218,10 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke
connect = MagicMock(return_value=conn)
monkeypatch.setattr(registration_module.psycopg, "connect", connect)
monkeypatch.setattr(registration_module, "setup_duckgres_session", MagicMock())
+ cancel_timer = MagicMock()
+ cancel_timer_factory = MagicMock(return_value=cancel_timer)
+ monkeypatch.setattr(registration_module, "_duckgres_cancel_delay", MagicMock(return_value=60.0))
+ monkeypatch.setattr(registration_module.threading, "Timer", cancel_timer_factory)
heartbeat_state = {"active": False}
heartbeater = MagicMock()
heartbeater.__enter__ = MagicMock(side_effect=lambda: heartbeat_state.update(active=True))
@@ -259,16 +263,27 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke
previous_cleanup_index = next(
index for index, query in enumerate(executed) if "DROP TABLE IF EXISTS" in query and "__ph_previous_" in query
)
- assert len(registration_indexes) == 1
- registration_query = executed[registration_indexes[0]]
+ assert len(registration_indexes) == 2
+ first_path = (
+ "s3://ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/"
+ "1234567890_abcdef12/_ph_partition_key=2026-07/a.parquet"
+ )
+ second_path = (
+ "s3://ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/"
+ "1234567890_abcdef12/_ph_partition_key=2026-08/b.parquet"
+ )
+ assert first_path in executed[registration_indexes[0]]
+ assert second_path not in executed[registration_indexes[0]]
+ assert second_path in executed[registration_indexes[1]]
+ assert first_path not in executed[registration_indexes[1]]
+ assert sum(first_path in query for query in executed) == 1
+ assert sum(second_path in query for query in executed) == 1
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 sum(parquet_glob in query for query in executed) == 2
+ assert all(parquet_glob not in executed[index] for index in registration_indexes)
assert len(verification_indexes) == 2
assert len(rename_indexes) == 2
assert max(registration_indexes) < min(verification_indexes)
@@ -286,6 +301,14 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke
executed[index] for index in rename_indexes
]
conn.transaction.assert_called_once_with()
+ assert cancel_timer_factory.call_count == 1
+ assert cancel_timer_factory.call_args.args[0] == 60.0
+ assert callable(cancel_timer_factory.call_args.args[1])
+ cancel_timer.start.assert_called_once_with()
+ cancel_timer.cancel.assert_called_once_with()
+ cancel_timer.join.assert_called_once_with(timeout=registration_module._DUCKGRES_CANCEL_TIMEOUT_SECONDS + 1)
+ cancel_timer_factory.call_args.args[1]()
+ conn.cancel_safe.assert_not_called()
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")
@@ -295,6 +318,134 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke
workload_metrics.bytes.record.assert_called_once_with(300.0)
+def test_duckgres_cancel_watchdog_cancels_the_active_query(monkeypatch):
+ conn = MagicMock()
+ cancel_timer = MagicMock()
+ cancel_timer_factory = MagicMock(return_value=cancel_timer)
+ monkeypatch.setattr(registration_module.threading, "Timer", cancel_timer_factory)
+ monkeypatch.setattr(registration_module, "_DUCKGRES_CANCEL_RETRY_SECONDS", 0.01)
+ first_cancel_finished = registration_module.threading.Event()
+ conn.cancel_safe.side_effect = lambda **_: first_cancel_finished.set()
+
+ with registration_module._cancel_duckgres_query_after(conn, 30.0) as cancel_requested:
+ callback_thread = registration_module.threading.Thread(target=cancel_timer_factory.call_args.args[1])
+ callback_thread.start()
+ assert first_cancel_finished.wait(timeout=1)
+
+ callback_thread.join(timeout=1)
+ assert not callback_thread.is_alive()
+ assert cancel_requested.is_set()
+ conn.cancel_safe.assert_called_with(timeout=registration_module._DUCKGRES_CANCEL_TIMEOUT_SECONDS)
+ cancel_timer.cancel.assert_called_once_with()
+ cancel_timer.join.assert_called_once_with(timeout=registration_module._DUCKGRES_CANCEL_TIMEOUT_SECONDS + 1)
+
+
+def test_duckgres_cancel_watchdog_retries_after_an_idle_cancel(monkeypatch):
+ conn = MagicMock()
+ cancel_timer = MagicMock()
+ cancel_timer_factory = MagicMock(return_value=cancel_timer)
+ monkeypatch.setattr(registration_module.threading, "Timer", cancel_timer_factory)
+ monkeypatch.setattr(registration_module, "_DUCKGRES_CANCEL_RETRY_SECONDS", 0.01)
+ first_cancel_finished = registration_module.threading.Event()
+ query_started = registration_module.threading.Event()
+ query_canceled = registration_module.threading.Event()
+
+ def cancel_safe(*, timeout: float) -> None:
+ assert timeout == registration_module._DUCKGRES_CANCEL_TIMEOUT_SECONDS
+ if first_cancel_finished.is_set() and query_started.is_set():
+ query_canceled.set()
+ first_cancel_finished.set()
+
+ conn.cancel_safe.side_effect = cancel_safe
+
+ with registration_module._cancel_duckgres_query_after(conn, 30.0):
+ callback_thread = registration_module.threading.Thread(target=cancel_timer_factory.call_args.args[1])
+ callback_thread.start()
+ assert first_cancel_finished.wait(timeout=1)
+ query_started.set()
+ assert query_canceled.wait(timeout=1)
+
+ callback_thread.join(timeout=1)
+ assert not callback_thread.is_alive()
+ assert conn.cancel_safe.call_count >= 2
+
+
+def test_duckgres_cancel_watchdog_bounds_cancel_retries(monkeypatch):
+ conn = MagicMock()
+ cancel_timer = MagicMock()
+ cancel_timer_factory = MagicMock(return_value=cancel_timer)
+ monkeypatch.setattr(registration_module.threading, "Timer", cancel_timer_factory)
+ monkeypatch.setattr(registration_module, "_DUCKGRES_CANCEL_RETRY_SECONDS", 0.0)
+ retries_finished = registration_module.threading.Event()
+
+ def cancel_safe(*, timeout: float) -> None:
+ assert timeout == registration_module._DUCKGRES_CANCEL_TIMEOUT_SECONDS
+ if conn.cancel_safe.call_count == registration_module._DUCKGRES_CANCEL_MAX_ATTEMPTS:
+ retries_finished.set()
+
+ conn.cancel_safe.side_effect = cancel_safe
+
+ with registration_module._cancel_duckgres_query_after(conn, 30.0):
+ callback_thread = registration_module.threading.Thread(target=cancel_timer_factory.call_args.args[1])
+ callback_thread.start()
+ assert retries_finished.wait(timeout=1)
+ callback_thread.join(timeout=1)
+ assert not callback_thread.is_alive()
+
+ assert conn.cancel_safe.call_count == registration_module._DUCKGRES_CANCEL_MAX_ATTEMPTS
+
+
+def test_duckgres_cancel_delay_includes_time_spent_copying(monkeypatch):
+ activity_info = MagicMock(start_to_close_timeout=dt.timedelta(minutes=30))
+ monkeypatch.setattr(registration_module.activity, "info", MagicMock(return_value=activity_info))
+ monkeypatch.setattr(registration_module.time, "monotonic", MagicMock(return_value=400.0))
+
+ assert registration_module._duckgres_cancel_delay(100.0) == 24 * 60
+
+
+def test_duckgres_cancel_watchdog_rejects_an_exhausted_activity_budget(monkeypatch):
+ timer_factory = MagicMock()
+ monkeypatch.setattr(registration_module.threading, "Timer", timer_factory)
+
+ with pytest.raises(TimeoutError, match="too close"):
+ with registration_module._cancel_duckgres_query_after(MagicMock(), 0.0):
+ pass
+
+ timer_factory.assert_not_called()
+
+
+def test_registration_stops_between_files_after_query_cancellation(monkeypatch):
+ monkeypatch.setattr(registration_module, "setup_duckgres_session", MagicMock())
+ conn = MagicMock()
+ cancel_requested = registration_module.threading.Event()
+
+ def execute(query: object) -> MagicMock:
+ if "ducklake_add_data_files" in str(query):
+ cancel_requested.set()
+ return MagicMock()
+
+ 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,
+ )
+
+ with pytest.raises(TimeoutError, match="activity deadline"):
+ registration_module._register_prepared_parquet_files(
+ _activity_inputs(),
+ conn,
+ [f"{landing_uri}/first.parquet", f"{landing_uri}/second.parquet"],
+ cancel_requested=cancel_requested,
+ )
+
+ executed = [str(call.args[0]) for call in conn.execute.call_args_list]
+ assert sum("ducklake_add_data_files" in query for query in executed) == 1
+ 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) == 1
+ assert not any("RENAME TO" in query for query in executed)
+
+
def test_copy_activity_does_not_touch_catalog_for_stale_generation(monkeypatch):
monkeypatch.setattr(
registration_module,
@@ -495,6 +646,13 @@ async def test_workflow_records_end_to_end_duration_after_gate(monkeypatch):
metrics.duration.record.assert_called_once_with(432.0)
metrics.last_success_getter.assert_called_once_with(**metric_identifiers)
metrics.last_success.set.assert_called_once_with(finished_at.timestamp())
+ registration_call = next(
+ call
+ for call in execute_activity.await_args_list
+ if 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["retry_policy"].maximum_attempts == 1
assert _recorded_source_job_statuses(execute_activity) == [
registration_module.ManagedWarehouseSourceJobStatus.RUNNING,
registration_module.ManagedWarehouseSourceJobStatus.COMPLETED,