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.

feat(ducklake): add prepared import registration workflow (#74152)

Eric Duongc08881f23758
diff --git a/posthog/ducklake/README.md b/posthog/ducklake/README.md
index 1c1b73e2f27f..7e5d2f5be756 100644
--- a/posthog/ducklake/README.md
+++ b/posthog/ducklake/README.md
@@ -1,11 +1,12 @@
# DuckLake copy workflow configuration
-The DuckLake copy workflows copy data into a DuckLake-managed S3 bucket. There are two workflows:
+The DuckLake copy and registration workflows write data into a DuckLake-managed S3 bucket. There are three workflows:
1. **Data Modeling** (`ducklake-copy.data-modeling`) - copies materialized saved query outputs
2. **Data Imports** (`ducklake-copy.data-imports`) - copies external data source imports (Stripe, Hubspot, etc.)
+3. **Data Import Registration** (`ducklake-register.data-imports`) - copies and registers prepared Parquet files from completed imports
-Both workflows share the same infrastructure and configuration. Workers running these workflows must be configured explicitly; otherwise copies will fail before they even reach the first activity.
+The workflows share the same infrastructure and configuration. Workers running these workflows must be configured explicitly; otherwise copies will fail before they even reach the first activity.
## Environment variables
@@ -34,15 +35,23 @@ For local dev the defaults are:
- `DUCKLAKE_BUCKET_REGION=us-east-1`
- `DUCKLAKE_S3_ACCESS_KEY=object_storage_root_user`
- `DUCKLAKE_S3_SECRET_KEY=object_storage_root_password`
+- `DUCKGRES_HOST=localhost`
+- `DUCKGRES_PORT=15432`
+- `DUCKGRES_DATABASE=ducklake`
+- `DUCKGRES_USERNAME=posthog`
+- `DUCKGRES_PASSWORD=posthog`
## Feature flag gating
Each workflow is gated by its own feature flag (evaluated via `feature_enabled`). Create or update the appropriate flag locally to target the team you are testing with—otherwise the copy workflow will be skipped even if the rest of the configuration is correct.
-| Workflow | Feature Flag |
-| ------------- | -------------------------------------- |
-| Data Modeling | `ducklake-data-modeling-copy-workflow` |
-| Data Imports | `ducklake-data-imports-copy-workflow` |
+| Workflow | Feature Flag |
+| ------------------------ | --------------------------------------------- |
+| Data Modeling | `ducklake-data-modeling-copy-workflow` |
+| Data Imports | `ducklake-data-imports-copy-workflow` |
+| Data Import Registration | `ducklake-data-imports-registration-workflow` |
+
+The two data-import flags are independent and target the same stable DuckLake table. During rollout, enable only the intended path for a project; if both run for the same import, the last atomic table swap wins.
## Target bucket layout
@@ -54,13 +63,16 @@ Every copy is written to a deterministic schema inside DuckLake. Each workflow n
- **Table**: `<model_label>` (derived from saved query name)
- **Example**: `ducklake.posthog_data_modeling_team_123.my_saved_query`
-### Data Imports
+### Data Imports and Data Import Registration
- **Schema**: `posthog_data_imports_team_<team_id>`
- **Table**: `<source_type>_<prefix>_<normalized_name>` (prefix is user-defined on the external data source)
- **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>`
+
+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.
-Re-running a copy simply overwrites the same table. Choose the bucket so its lifecycle/replication policies fit that structure.
+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
@@ -69,7 +81,7 @@ Temporal workers must be able to:
1. Read from the existing PostHog object storage bucket where Delta tables live (already required for the modeling pipeline).
2. Read/write/delete within the DuckLake data bucket referenced by `DUCKLAKE_BUCKET`.
-For AWS S3, grant the worker role at least `s3:ListBucket`, `s3:GetObject`, `s3:PutObject`, and `s3:DeleteObject` on the DuckLake bucket/prefix (plus `s3:CreateBucket` if you want local MinIO-style auto-creation). For MinIO, reuse the same access/secret keys configured in the `DUCKLAKE_*` variables and ensure they have full access to the DuckLake bucket.
+For AWS S3, grant the worker role at least `s3:ListBucket`, `s3:GetObject`, `s3:PutObject`, and `s3:DeleteObject` on the DuckLake bucket/prefix (plus `s3:CreateBucket` for local auto-creation). Local development uses the configured SeaweedFS object store and the `DUCKLAKE_*` access keys.
## Local testing (dev)
@@ -78,7 +90,7 @@ Follow these checklists to exercise the DuckLake copy workflows on a local check
### Testing Data Modeling workflow
1. **Start the dev stack**
- Run `hogli start` (or `bin/start`) so Postgres, MinIO, Temporal, and all DuckLake defaults are up. Make sure the `ducklake-data-modeling-copy-workflow` feature flag is enabled for the team you plan to use.
+ Run `hogli start` (or `bin/start`) so Postgres, SeaweedFS, Temporal, and all DuckLake defaults are up. Make sure the `ducklake-data-modeling-copy-workflow` feature flag is enabled for the team you plan to use.
2. **Trigger a model materialization from the app**
In the PostHog UI, open Data Warehouse → Views, pick (or create) a view, open the Materialization section, enable it if needed, and click **Sync now**. This schedules the `data-modeling-run` workflow for that team/view.
@@ -116,10 +128,10 @@ Follow these checklists to exercise the DuckLake copy workflows on a local check
"
```
-### Testing Data Imports workflow
+### Testing Data Imports workflows
1. **Start the dev stack**
- Run `hogli start` (or `bin/start`) so Postgres, MinIO, Temporal, and all DuckLake defaults are up. Make sure the `ducklake-data-imports-copy-workflow` feature flag is enabled for the team you plan to use.
+ Run `hogli start` (or `bin/start`) so Postgres, Duckgres, SeaweedFS, Temporal, and all DuckLake defaults are up. Enable either `ducklake-data-imports-copy-workflow` for the existing Delta-copy path or `ducklake-data-imports-registration-workflow` for the prepared-Parquet path.
2. **Trigger a data import sync from the app**
In the PostHog UI, open Data Warehouse → Sources, connect a source (e.g., Stripe, Hubspot), select the schemas to sync, and click **Sync**. This schedules the `external-data-job` workflow.
@@ -127,8 +139,8 @@ Follow these checklists to exercise the DuckLake copy workflows on a local check
3. **Observe the external-data-job workflow**
Visit the Temporal UI at `http://localhost:8081/namespaces/default/workflows` and confirm an `external-data-job` execution appears. Wait for it to finish successfully.
-4. **Verify the DuckLake copy workflow runs**
- Once the import workflow completes it automatically starts `ducklake-copy.data-imports` as a child run. You should see it listed in the same Temporal UI; wait for the run to complete.
+4. **Verify the selected DuckLake workflow runs**
+ Once the import workflow completes it starts both independently gated child workflows. The enabled path appears as either `ducklake-copy.data-imports` or `ducklake-register.data-imports`; the disabled path exits after its gate activity.
5. **Query the new DuckLake table**
The copy activity creates a table at `ducklake.posthog_data_imports_team_<team_id>.<source_type>_<prefix>_<table_name>`. From any DuckDB shell you can inspect it:
diff --git a/posthog/temporal/ducklake/__init__.py b/posthog/temporal/ducklake/__init__.py
index d1722c86ca60..2ef2afb73276 100644
--- a/posthog/temporal/ducklake/__init__.py
+++ b/posthog/temporal/ducklake/__init__.py
@@ -15,17 +15,31 @@ from posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow import (
prepare_data_modeling_ducklake_metadata_activity,
verify_ducklake_copy_activity,
)
+from posthog.temporal.ducklake.ducklake_register_data_imports_workflow import (
+ DuckLakeRegisterDataImportsWorkflow,
+ copy_and_register_ducklake_data_imports_activity,
+ ducklake_register_data_imports_gate_activity,
+ prepare_ducklake_data_imports_registration_activity,
+)
-WORKFLOWS = [DucklakeCompactionWorkflow, DuckLakeCopyDataImportsWorkflow, DuckLakeCopyDataModelingWorkflow]
+WORKFLOWS = [
+ DucklakeCompactionWorkflow,
+ DuckLakeCopyDataImportsWorkflow,
+ DuckLakeCopyDataModelingWorkflow,
+ DuckLakeRegisterDataImportsWorkflow,
+]
ACTIVITIES = [
cleanup_data_imports_staging_activity,
cleanup_data_modeling_staging_activity,
copy_data_imports_to_ducklake_activity,
copy_data_modeling_model_to_ducklake_activity,
+ copy_and_register_ducklake_data_imports_activity,
ducklake_copy_data_imports_gate_activity,
ducklake_copy_workflow_gate_activity,
+ ducklake_register_data_imports_gate_activity,
prepare_data_imports_ducklake_metadata_activity,
prepare_data_modeling_ducklake_metadata_activity,
+ prepare_ducklake_data_imports_registration_activity,
run_ducklake_compaction,
verify_data_imports_ducklake_copy_activity,
verify_ducklake_copy_activity,
diff --git a/posthog/temporal/ducklake/ducklake_register_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_register_data_imports_workflow.py
new file mode 100644
index 000000000000..0cd6b106cc05
--- /dev/null
+++ b/posthog/temporal/ducklake/ducklake_register_data_imports_workflow.py
@@ -0,0 +1,449 @@
+import re
+import json
+import uuid
+import typing
+import datetime as dt
+import contextlib
+import dataclasses
+from collections.abc import Iterator
+
+from django.conf import settings
+from django.db import close_old_connections
+
+import psycopg
+from psycopg import sql as psql
+from structlog.contextvars import bind_contextvars
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ApplicationError
+
+from posthog.ducklake.client import make_duckgres_conninfo
+from posthog.ducklake.common import (
+ _get_org_id_for_team,
+ duckgres_data_imports_schema,
+ duckgres_data_imports_table_name,
+ get_config,
+ get_duckgres_server_by_team_org,
+ get_duckgres_server_for_organization,
+ is_dev_mode,
+)
+from posthog.ducklake.storage import connect_to_duckgres, setup_duckgres_session
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team
+from posthog.ph_client import feature_enabled_or_false
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.heartbeat_sync import HeartbeaterSync
+from posthog.temporal.common.logger import get_logger
+from posthog.temporal.ducklake.metrics import get_ducklake_register_data_imports_finished_metric
+
+from products.data_warehouse.backend.facade.api import get_s3_client
+from products.warehouse_sources.backend.facade.models import ExternalDataSchema
+
+LOGGER = get_logger(__name__)
+DUCKLAKE_DATA_IMPORTS_REGISTRATION_WORKFLOW_FLAG = "ducklake-data-imports-registration-workflow"
+DATA_IMPORTS_GENERATIONS_PREFIX = "_imports"
+
+
+class DuckLakeRegisterDataImportsGateInputs:
+ team_id: int
+
+
+class DuckLakeRegisterDataImportsInputs:
+ team_id: int
+ job_id: str
+ schema_id: uuid.UUID
+ prepared_queryable_folder: str
+
+ @property
+ def properties_to_log(self) -> dict[str, typing.Any]:
+ return {
+ "team_id": self.team_id,
+ "job_id": self.job_id,
+ "schema_id": str(self.schema_id),
+ "prepared_queryable_folder": self.prepared_queryable_folder,
+ }
+
+
+class DuckLakeRegisterDataImportsMetadata:
+ source_schema_id: str
+ prepared_queryable_folder: str
+ prepared_source_uri: str
+ landing_uri: str
+ ducklake_schema_name: str
+ ducklake_table_name: str
+
+
+class DuckLakeRegisterDataImportsActivityInputs:
+ team_id: int
+ job_id: str
+ metadata: DuckLakeRegisterDataImportsMetadata
+
+
+class _StalePreparedGenerationError(Exception):
+ pass
+
+
+async def ducklake_register_data_imports_gate_activity(inputs: DuckLakeRegisterDataImportsGateInputs) -> bool:
+ bind_contextvars(team_id=inputs.team_id)
+ logger = LOGGER.bind()
+
+ try:
+ team = await database_sync_to_async(Team.objects.only("uuid", "organization_id").get)(id=inputs.team_id)
+ except Team.DoesNotExist:
+ await logger.aerror("Team does not exist when evaluating DuckLake data imports registration gate")
+ return False
+
+ try:
+ return feature_enabled_or_false(
+ DUCKLAKE_DATA_IMPORTS_REGISTRATION_WORKFLOW_FLAG,
+ str(team.uuid),
+ groups={
+ "organization": str(team.organization_id),
+ "project": str(team.id),
+ },
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ except Exception as error:
+ await logger.awarning("Failed to evaluate DuckLake data imports registration feature flag", error=str(error))
+ capture_exception(error)
+ return False
+
+
+async def prepare_ducklake_data_imports_registration_activity(
+ inputs: DuckLakeRegisterDataImportsInputs,
+) -> DuckLakeRegisterDataImportsMetadata | None:
+ bind_contextvars(team_id=inputs.team_id)
+ logger = LOGGER.bind(schema_id=str(inputs.schema_id), job_id=inputs.job_id)
+
+ if not _is_valid_queryable_folder(inputs.prepared_queryable_folder):
+ raise ApplicationError(
+ f"Invalid prepared queryable folder '{inputs.prepared_queryable_folder}'",
+ non_retryable=True,
+ )
+
+ schema = await database_sync_to_async(ExternalDataSchema.objects.select_related("table", "source").get)(
+ id=inputs.schema_id,
+ team_id=inputs.team_id,
+ )
+ if schema.table is None or schema.table.queryable_folder != inputs.prepared_queryable_folder:
+ await logger.ainfo(
+ "Skipping stale prepared Parquet generation before registration",
+ prepared_queryable_folder=inputs.prepared_queryable_folder,
+ )
+ return None
+
+ prepared_source_uri = f"{settings.BUCKET_URL}/{schema.folder_path()}/{inputs.prepared_queryable_folder}"
+ ducklake_schema_name = await database_sync_to_async(duckgres_data_imports_schema)(inputs.team_id)
+ ducklake_table_name = duckgres_data_imports_table_name(schema)
+ landing_uri = await database_sync_to_async(_resolve_data_imports_landing_uri)(
+ team_id=inputs.team_id,
+ ducklake_schema_name=ducklake_schema_name,
+ ducklake_table_name=ducklake_table_name,
+ source_schema_id=str(inputs.schema_id),
+ job_id=inputs.job_id,
+ )
+ return DuckLakeRegisterDataImportsMetadata(
+ source_schema_id=str(schema.id),
+ prepared_queryable_folder=inputs.prepared_queryable_folder,
+ prepared_source_uri=prepared_source_uri,
+ landing_uri=landing_uri,
+ ducklake_schema_name=ducklake_schema_name,
+ ducklake_table_name=ducklake_table_name,
+ )
+
+
+def copy_and_register_ducklake_data_imports_activity(inputs: DuckLakeRegisterDataImportsActivityInputs) -> bool:
+ bind_contextvars(team_id=inputs.team_id)
+ logger = LOGGER.bind(
+ schema_id=inputs.metadata.source_schema_id,
+ job_id=inputs.job_id,
+ )
+ if not settings.TEST:
+ close_old_connections()
+
+ heartbeater = HeartbeaterSync(
+ details=("ducklake_register_data_imports", inputs.metadata.source_schema_id),
+ logger=logger,
+ )
+ with heartbeater:
+ landing_paths = _copy_prepared_parquet_files(
+ inputs.metadata.prepared_source_uri,
+ inputs.metadata.landing_uri,
+ )
+ if not _prepared_generation_is_current(inputs):
+ logger.info("Skipping stale prepared Parquet generation after object copy")
+ return False
+
+ try:
+ with _connect_to_duckgres_for_team(inputs.team_id) as conn:
+ _register_prepared_parquet_files(inputs, conn, landing_paths)
+ except _StalePreparedGenerationError:
+ logger.info("Skipping stale prepared Parquet generation before catalog swap")
+ return False
+
+ logger.info(
+ "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,
+ )
+ return True
+
+
+def _is_valid_queryable_folder(queryable_folder: str) -> bool:
+ return bool(queryable_folder) and "/" not in queryable_folder and queryable_folder not in {".", ".."}
+
+
+def _resolve_data_imports_landing_uri(
+ *,
+ team_id: int,
+ ducklake_schema_name: str,
+ ducklake_table_name: str,
+ source_schema_id: str,
+ job_id: str,
+) -> str:
+ if is_dev_mode():
+ bucket = get_config().get("DUCKLAKE_BUCKET")
+ else:
+ server = get_duckgres_server_by_team_org(team_id)
+ bucket = server.bucket if server is not None else None
+ if not bucket:
+ 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 (
+ f"s3://{bucket}/{ducklake_schema_name}/{ducklake_table_name}/"
+ f"{DATA_IMPORTS_GENERATIONS_PREFIX}/{source_schema_id}/{safe_job_id}"
+ )
+
+
+def _copy_prepared_parquet_files(source_uri: str, landing_uri: str) -> list[str]:
+ source_prefix = source_uri.removeprefix("s3://").rstrip("/")
+ landing_prefix = landing_uri.removeprefix("s3://").rstrip("/")
+ s3 = get_s3_client()
+ found = s3.find(source_prefix)
+ source_paths = list(found.keys()) if isinstance(found, dict) else list(found)
+ parquet_paths = sorted(str(path) for path in source_paths if str(path).lower().endswith(".parquet"))
+ if not parquet_paths:
+ raise ApplicationError(f"No prepared Parquet files found under {source_uri}", non_retryable=True)
+
+ landing_paths: list[str] = []
+ for source_path_value in parquet_paths:
+ source_path = source_path_value.removeprefix("s3://")
+ relative_path = source_path.removeprefix(f"{source_prefix}/")
+ if relative_path == source_path or relative_path.startswith("../"):
+ raise ApplicationError(f"Prepared file escaped source prefix: {source_path}", non_retryable=True)
+ landing_path = f"{landing_prefix}/{relative_path}"
+ s3.copy(source_path, landing_path)
+ landing_paths.append(f"s3://{landing_path}")
+
+ return landing_paths
+
+
+def _prepared_generation_is_current(inputs: DuckLakeRegisterDataImportsActivityInputs) -> bool:
+ try:
+ schema = ExternalDataSchema.objects.select_related("table").get(
+ id=inputs.metadata.source_schema_id,
+ team_id=inputs.team_id,
+ )
+ except ExternalDataSchema.DoesNotExist:
+ return False
+ return schema.table is not None and schema.table.queryable_folder == inputs.metadata.prepared_queryable_folder
+
+
+def _connect_to_duckgres_for_team(team_id: int) -> Iterator[psycopg.Connection]:
+ if is_dev_mode():
+ with psycopg.connect(make_duckgres_conninfo(team_id), autocommit=True) as conn:
+ yield conn
+ return
+
+ organization_id = _get_org_id_for_team(team_id)
+ server = get_duckgres_server_for_organization(organization_id)
+ if server is None:
+ raise ApplicationError(f"No DuckgresServer configured for team {team_id}", non_retryable=True)
+ with connect_to_duckgres(server) as conn:
+ yield conn
+
+
+def _register_prepared_parquet_files(
+ inputs: DuckLakeRegisterDataImportsActivityInputs,
+ conn: psycopg.Connection,
+ landing_paths: list[str],
+) -> None:
+ 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)
+
+ setup_duckgres_session(conn, extensions=("ducklake", "httpfs"))
+ with conn.transaction():
+ 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,
+ )
+ )
+ if partition_columns:
+ conn.execute(
+ psql.SQL("ALTER TABLE {}.{} SET PARTITIONED BY ({})").format(
+ psql.Identifier(schema_name),
+ psql.Identifier(shadow_name),
+ psql.SQL(", ").join(psql.Identifier(column) for column in partition_columns),
+ )
+ )
+ for landing_path in landing_paths:
+ conn.execute(
+ psql.SQL(
+ "CALL ducklake_add_data_files({}, {}, {}, schema => {}, "
+ "allow_missing => true, hive_partitioning => true)"
+ ).format(
+ psql.Literal("ducklake"),
+ psql.Literal(shadow_name),
+ psql.Literal(landing_path),
+ psql.Literal(schema_name),
+ )
+ )
+
+ source_row = conn.execute(
+ psql.SQL("SELECT count(*) FROM read_parquet({}, union_by_name=true, hive_partitioning=true)").format(
+ parquet_paths
+ )
+ ).fetchone()
+ registered_row = conn.execute(
+ psql.SQL("SELECT count(*) FROM {}.{}").format(
+ psql.Identifier(schema_name),
+ psql.Identifier(shadow_name),
+ )
+ ).fetchone()
+ source_count = int(source_row[0]) if source_row else 0
+ registered_count = int(registered_row[0]) if registered_row else 0
+ if source_count != registered_count:
+ raise ApplicationError(
+ "DuckLake prepared-file registration row count mismatch: "
+ f"source={source_count}, registered={registered_count}",
+ non_retryable=True,
+ )
+
+ if not _prepared_generation_is_current(inputs):
+ raise _StalePreparedGenerationError
+
+ conn.execute(
+ psql.SQL("DROP TABLE IF EXISTS {}.{}").format(
+ psql.Identifier(schema_name),
+ psql.Identifier(table_name),
+ )
+ )
+ conn.execute(
+ psql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(
+ psql.Identifier(schema_name),
+ psql.Identifier(shadow_name),
+ psql.Identifier(table_name),
+ )
+ )
+
+
+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 _hive_partition_columns(landing_uri: str, landing_paths: list[str]) -> list[str]:
+ landing_prefix = landing_uri.rstrip("/") + "/"
+ columns: list[str] = []
+ for landing_path in landing_paths:
+ relative_path = landing_path.removeprefix(landing_prefix)
+ for segment in relative_path.split("/")[:-1]:
+ column, separator, _ = segment.partition("=")
+ if separator and column and column not in columns:
+ columns.append(column)
+ return columns
+
+
[email protected](name="ducklake-register.data-imports")
+class DuckLakeRegisterDataImportsWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> DuckLakeRegisterDataImportsInputs:
+ loaded = json.loads(inputs[0])
+ schema_id = loaded["schema_id"]
+ return DuckLakeRegisterDataImportsInputs(
+ team_id=loaded["team_id"],
+ job_id=loaded["job_id"],
+ schema_id=uuid.UUID(schema_id) if isinstance(schema_id, str) else schema_id,
+ prepared_queryable_folder=loaded["prepared_queryable_folder"],
+ )
+
+ @workflow.run
+ async def run(self, inputs: DuckLakeRegisterDataImportsInputs) -> None:
+ logger = LOGGER.bind(**inputs.properties_to_log)
+ logger.info("Starting DuckLakeRegisterDataImportsWorkflow")
+
+ should_register = await workflow.execute_activity(
+ ducklake_register_data_imports_gate_activity,
+ DuckLakeRegisterDataImportsGateInputs(team_id=inputs.team_id),
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ if not should_register:
+ logger.info("DuckLake data imports registration workflow disabled by feature flag")
+ return
+
+ metadata = await workflow.execute_activity(
+ prepare_ducklake_data_imports_registration_activity,
+ inputs,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ if metadata is None:
+ logger.info("Prepared Parquet generation is stale; nothing to register")
+ return
+
+ activity_inputs = DuckLakeRegisterDataImportsActivityInputs(
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ metadata=metadata,
+ )
+ try:
+ copy_applied = await workflow.execute_activity(
+ copy_and_register_ducklake_data_imports_activity,
+ activity_inputs,
+ start_to_close_timeout=dt.timedelta(minutes=30),
+ heartbeat_timeout=dt.timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ if not copy_applied:
+ logger.info("Prepared Parquet generation became stale; registration skipped")
+ get_ducklake_register_data_imports_finished_metric(status="stale").add(1)
+ return
+
+ except Exception:
+ get_ducklake_register_data_imports_finished_metric(status="failed").add(1)
+ raise
+
+ get_ducklake_register_data_imports_finished_metric(status="completed").add(1)
diff --git a/posthog/temporal/ducklake/metrics.py b/posthog/temporal/ducklake/metrics.py
index 371e8651de0b..001d3f17ef9f 100644
--- a/posthog/temporal/ducklake/metrics.py
+++ b/posthog/temporal/ducklake/metrics.py
@@ -44,3 +44,14 @@ def get_ducklake_copy_data_imports_verification_metric(check_name: str, status:
"Number of DuckLake data imports verification checks completed.",
)
)
+
+
+def get_ducklake_register_data_imports_finished_metric(status: str) -> MetricCounter:
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"status": status})
+ .create_counter(
+ "ducklake_register_data_imports_finished",
+ "Number of DuckLake prepared data import registration workflows finished, including failures.",
+ )
+ )
diff --git a/posthog/temporal/tests/ducklake/test_ducklake_register_data_imports_workflow.py b/posthog/temporal/tests/ducklake/test_ducklake_register_data_imports_workflow.py
new file mode 100644
index 000000000000..02a887776618
--- /dev/null
+++ b/posthog/temporal/tests/ducklake/test_ducklake_register_data_imports_workflow.py
@@ -0,0 +1,260 @@
+import contextlib
+
+import pytest
+from unittest.mock import MagicMock
+
+from temporalio.exceptions import ApplicationError
+
+from posthog.ducklake import cp_teams
+from posthog.sync import database_sync_to_async
+from posthog.temporal.ducklake import ducklake_register_data_imports_workflow as registration_module
+from posthog.temporal.ducklake.ducklake_register_data_imports_workflow import (
+ DUCKLAKE_DATA_IMPORTS_REGISTRATION_WORKFLOW_FLAG,
+ DuckLakeRegisterDataImportsActivityInputs,
+ DuckLakeRegisterDataImportsGateInputs,
+ DuckLakeRegisterDataImportsInputs,
+ DuckLakeRegisterDataImportsMetadata,
+ copy_and_register_ducklake_data_imports_activity,
+ ducklake_register_data_imports_gate_activity,
+ prepare_ducklake_data_imports_registration_activity,
+)
+
+from products.warehouse_sources.backend.facade.models import (
+ DataWarehouseCredential,
+ DataWarehouseTable,
+ ExternalDataSchema,
+ ExternalDataSource,
+)
+
+
[email protected](autouse=True)
+def _cp_no_rows():
+ from unittest.mock import patch
+
+ cp_teams.clear_cache()
+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[]):
+ yield
+ cp_teams.clear_cache()
+
+
[email protected]("flag_enabled", [True, False])
+async def test_registration_gate_uses_independent_feature_flag(monkeypatch, ateam, flag_enabled):
+ captured: dict[str, object] = {}
+
+ def fake_feature_enabled(key, distinct_id, **kwargs):
+ captured.update(key=key, distinct_id=distinct_id, **kwargs)
+ return flag_enabled
+
+ monkeypatch.setattr(registration_module, "feature_enabled_or_false", fake_feature_enabled)
+
+ result = await ducklake_register_data_imports_gate_activity(DuckLakeRegisterDataImportsGateInputs(team_id=ateam.id))
+
+ assert result is flag_enabled
+ assert captured["key"] == DUCKLAKE_DATA_IMPORTS_REGISTRATION_WORKFLOW_FLAG
+ assert captured["distinct_id"] == str(ateam.uuid)
+ assert captured["groups"] == {
+ "organization": str(ateam.organization_id),
+ "project": str(ateam.id),
+ }
+ assert captured["only_evaluate_locally"] is True
+ assert captured["send_feature_flag_events"] is False
+
+
+async def test_prepare_registration_pins_the_import_jobs_prepared_generation(ateam):
+ credential = await database_sync_to_async(DataWarehouseCredential.objects.create)(
+ team=ateam,
+ access_key="test_key",
+ access_secret="test_secret",
+ )
+ source = await database_sync_to_async(ExternalDataSource.objects.create)(
+ team=ateam,
+ source_id="source",
+ connection_id="connection",
+ source_type="Postgres",
+ status="Running",
+ )
+ prepared_queryable_folder = "customers__query_1234567890_abcdef12"
+ table = await database_sync_to_async(DataWarehouseTable.objects.create)(
+ team=ateam,
+ name="customers",
+ format="Delta",
+ url_pattern="s3://bucket/path",
+ credential=credential,
+ external_data_source=source,
+ columns={"id": {"clickhouse": "Int64", "hogql": "IntegerDatabaseField"}},
+ queryable_folder=prepared_queryable_folder,
+ )
+ schema = await database_sync_to_async(ExternalDataSchema.objects.create)(
+ team=ateam,
+ name="customers",
+ source=source,
+ table=table,
+ )
+
+ metadata = await prepare_ducklake_data_imports_registration_activity(
+ DuckLakeRegisterDataImportsInputs(
+ team_id=ateam.id,
+ job_id="job-123",
+ schema_id=schema.id,
+ prepared_queryable_folder=prepared_queryable_folder,
+ )
+ )
+
+ assert metadata is not None
+ 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"
+ )
+ assert metadata.ducklake_schema_name == f"posthog_data_imports_team_{ateam.id}"
+ assert metadata.ducklake_table_name == "postgres_customers"
+
+
+def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monkeypatch):
+ class FakeS3:
+ def __init__(self) -> None:
+ self.copies: list[tuple[str, str]] = []
+
+ def find(self, prefix: str) -> list[str]:
+ return [
+ f"{prefix}/_ph_partition_key=2026-07/a.parquet",
+ f"{prefix}/_ph_partition_key=2026-08/b.parquet",
+ ]
+
+ def copy(self, source: str, destination: str) -> None:
+ self.copies.append((source, destination))
+
+ s3 = FakeS3()
+ monkeypatch.setattr(registration_module, "get_s3_client", lambda: s3)
+ monkeypatch.setattr(registration_module, "_prepared_generation_is_current", lambda inputs: True)
+ monkeypatch.setattr(registration_module, "is_dev_mode", lambda: True)
+ monkeypatch.setattr(registration_module, "make_duckgres_conninfo", lambda team_id: "postgresql://duckgres")
+
+ 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)
+
+ def execute(query: object) -> MagicMock:
+ query_text = str(query)
+ if "SELECT count(*) FROM read_parquet" in query_text:
+ return MagicMock(fetchone=MagicMock(return_value=(2,)))
+ if "SELECT count(*) FROM" in query_text:
+ return MagicMock(fetchone=MagicMock(return_value=(2,)))
+ return MagicMock()
+
+ conn.execute.side_effect = execute
+ connect = MagicMock(return_value=conn)
+ monkeypatch.setattr(registration_module.psycopg, "connect", connect)
+ 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))
+
+ inputs = _activity_inputs()
+ applied = copy_and_register_ducklake_data_imports_activity(inputs)
+
+ assert applied is True
+ connect.assert_called_once_with("postgresql://duckgres", autocommit=True)
+ assert s3.copies == [
+ (
+ "source/team/customers__query/_ph_partition_key=2026-07/a.parquet",
+ "ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/"
+ "_ph_partition_key=2026-07/a.parquet",
+ ),
+ (
+ "source/team/customers__query/_ph_partition_key=2026-08/b.parquet",
+ "ducklake/posthog_data_imports_team_1/postgres_customers/_imports/schema/job/"
+ "_ph_partition_key=2026-08/b.parquet",
+ ),
+ ]
+ 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_index = next(index for index, query in enumerate(executed) if "RENAME TO" in query)
+ assert len(registration_indexes) == 2
+ assert len(verification_indexes) == 2
+ assert max(registration_indexes) < min(verification_indexes)
+ assert max(verification_indexes) < drop_live_index < rename_index
+ assert any("SET PARTITIONED BY" in query for query in executed)
+
+
+def test_copy_activity_does_not_touch_catalog_for_stale_generation(monkeypatch):
+ monkeypatch.setattr(
+ registration_module,
+ "_copy_prepared_parquet_files",
+ lambda source_uri, landing_uri: [f"{landing_uri}/file.parquet"],
+ )
+ monkeypatch.setattr(registration_module, "_prepared_generation_is_current", lambda inputs: False)
+ monkeypatch.setattr(
+ registration_module,
+ "_connect_to_duckgres_for_team",
+ MagicMock(side_effect=AssertionError("stale generations must not update the catalog")),
+ )
+ heartbeater = MagicMock()
+ heartbeater.__enter__ = MagicMock(return_value=heartbeater)
+ heartbeater.__exit__ = MagicMock(return_value=False)
+ monkeypatch.setattr(registration_module, "HeartbeaterSync", MagicMock(return_value=heartbeater))
+
+ assert copy_and_register_ducklake_data_imports_activity(_activity_inputs()) is False
+
+
+def test_copy_activity_does_not_publish_a_row_count_mismatch(monkeypatch):
+ monkeypatch.setattr(
+ registration_module,
+ "_copy_prepared_parquet_files",
+ lambda source_uri, landing_uri: [f"{landing_uri}/file.parquet"],
+ )
+ 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):
+ return MagicMock(fetchone=MagicMock(return_value=next(counts)))
+ 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))
+
+ with pytest.raises(ApplicationError, match="row count mismatch"):
+ 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)
+ assert not any("RENAME TO" in query for query in executed)
+
+
+def _activity_inputs() -> DuckLakeRegisterDataImportsActivityInputs:
+ return DuckLakeRegisterDataImportsActivityInputs(
+ team_id=1,
+ job_id="job",
+ metadata=DuckLakeRegisterDataImportsMetadata(
+ source_schema_id="schema",
+ prepared_queryable_folder="customers__query",
+ prepared_source_uri="s3://source/team/customers__query",
+ 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",
+ ),
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index 80390c470490..9a668536a1e2 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
@@ -24,6 +24,10 @@ from posthog.temporal.ducklake.ducklake_copy_data_imports_workflow import (
DataImportsDuckLakeCopyInputs,
DuckLakeCopyDataImportsWorkflow,
)
+from posthog.temporal.ducklake.ducklake_register_data_imports_workflow import (
+ DuckLakeRegisterDataImportsInputs,
+ DuckLakeRegisterDataImportsWorkflow,
+)
from posthog.temporal.utils import CDPProducerWorkflowInputs, ExternalDataWorkflowInputs
from posthog.utils import get_machine_id
@@ -709,6 +713,29 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
extra={"schema_id": str(inputs.external_data_schema_id)},
)
+ prepared_queryable_folder = pipeline_result.get("prepared_queryable_folder")
+ if prepared_queryable_folder and workflow.patched("data-imports-ducklake-registration-workflow-v1"):
+ try:
+ await workflow.start_child_workflow(
+ DuckLakeRegisterDataImportsWorkflow.run,
+ DuckLakeRegisterDataImportsInputs(
+ team_id=inputs.team_id,
+ job_id=job_id,
+ 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}"
+ ),
+ task_queue=settings.DUCKLAKE_TASK_QUEUE,
+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,
+ )
+ except WorkflowAlreadyStartedError:
+ workflow.logger.warning(
+ "DuckLake prepared-file registration already running, skipping",
+ extra={"schema_id": str(inputs.external_data_schema_id), "job_id": job_id},
+ )
+
except exceptions.ActivityError as e:
if isinstance(e.cause, exceptions.ApplicationError) and e.cause.type == "WorkerShuttingDownError":
# Check if this is a WorkerShuttingDownError - implement Buffer One retry
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
index a80f9b779224..fe0388dc7475 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
@@ -338,11 +338,14 @@ class PipelineNonDLT(Generic[ResumableData]):
await self._persist_observed_columns()
- await self._post_run_operations(row_count=row_count)
+ prepared_queryable_folder = await self._post_run_operations(row_count=row_count)
await advance_xmin_state(self._resource, self._schema, self._logger)
- return {"should_trigger_cdp_producer": await self._cdp_producer.should_produce_table()}
+ result = PipelineResult(should_trigger_cdp_producer=await self._cdp_producer.should_produce_table())
+ if isinstance(prepared_queryable_folder, str):
+ result["prepared_queryable_folder"] = prepared_queryable_folder
+ return result
finally:
# Help reduce the memory footprint of each job. This is best-effort cleanup:
# `get_delta_table` does object-storage I/O, so a transient storage blip here
@@ -508,12 +511,12 @@ class PipelineNonDLT(Generic[ResumableData]):
table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
)
- async def _post_run_operations(self, row_count: int):
+ async def _post_run_operations(self, row_count: int) -> str | None:
delta_table = await self._delta_table_helper.get_delta_table()
if delta_table is None:
await self._logger.adebug("No deltalake table, not continuing with post-run ops")
- return
+ return None
await self._logger.adebug("Triggering compaction and vacuuming on delta table")
try:
@@ -596,6 +599,8 @@ class PipelineNonDLT(Generic[ResumableData]):
await self._logger.adebug("Syncing engineering analytics views")
await database_sync_to_async_pool(sync_engineering_analytics_views)(self._schema, self._source)
+ return queryable_folder
+
def _estimate_size(obj: Any) -> int:
if isinstance(obj, dict):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/typings.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/typings.py
index a0fcdabb06d0..a87b488f4503 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/typings.py
@@ -109,3 +109,4 @@ class PipelineResult(TypedDict):
should_trigger_cdp_producer: bool
consumer_manages_job_status: NotRequired[bool]
skip_post_import_activities: NotRequired[bool]
+ prepared_queryable_folder: NotRequired[str]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index 415a96427ebd..e339504793dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -53,6 +53,7 @@ from posthog.models.team.team import Team
from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownError
from posthog.temporal.ducklake import ACTIVITIES as DUCKLAKE_ACTIVITIES
from posthog.temporal.ducklake.ducklake_copy_data_imports_workflow import DuckLakeCopyDataImportsWorkflow
+from posthog.temporal.ducklake.ducklake_register_data_imports_workflow import DuckLakeRegisterDataImportsWorkflow
from posthog.temporal.utils import ExternalDataWorkflowInputs
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -644,7 +645,12 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, moc
async with Worker(
activity_environment.client,
task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,
- workflows=[ExternalDataJobWorkflow, CDPProducerJobWorkflow, DuckLakeCopyDataImportsWorkflow],
+ workflows=[
+ ExternalDataJobWorkflow,
+ CDPProducerJobWorkflow,
+ DuckLakeCopyDataImportsWorkflow,
+ DuckLakeRegisterDataImportsWorkflow,
+ ],
activities=ACTIVITIES + DUCKLAKE_ACTIVITIES, # type: ignore
workflow_runner=UnsandboxedWorkflowRunner(),
activity_executor=ThreadPoolExecutor(max_workers=50),