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(data-warehouse): provision DuckgresServer and back duckling backfill with it (#63834)

Eric Duong861f91f67aff
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index 364a6db91028..d7107526f816 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -8,14 +8,14 @@ This job targets individual customer "ducklings" - isolated DuckLake instances w
own RDS catalog and S3 bucket.
Architecture:
- DuckLakeCatalog (Django model)
- │ lookup by team_id → organization_id
+ DuckgresServer (connection) + derived S3 bucket name
+ │ team_id → organization_id → connection; bucket = posthog-duckling-{org}-{suffix}
▼
ClickHouse (events table)
│ export via s3() - bucket policy allows ClickHouse EC2 role
▼
Duckling S3 Bucket (parquet files)
- │ register via ducklake_add_data_files
+ │ register via ducklake_add_data_files (duckgres auto-attaches the catalog)
▼
Duckling RDS Catalog (PostgreSQL)
@@ -25,7 +25,7 @@ IAM Access:
Partition Strategy:
DynamicPartitionsDefinition with composite keys: {team_id}_{date}
- - team_id maps to duckling via DuckLakeCatalog
+ - team_id maps to a duckling via DuckLakeBackfill (enablement) + DuckgresServer (connection)
- date is the partition date (YYYY-MM-DD)
"""
@@ -33,6 +33,7 @@ import os
import json
import time
import calendar
+import dataclasses
from collections.abc import Callable
from datetime import date, datetime, timedelta
from typing import Any
@@ -66,8 +67,8 @@ from posthog.clickhouse.query_tagging import tags_context
from posthog.cloud_utils import is_cloud
from posthog.dags.common import JobOwners, dagster_tags, settings_with_log_comment
from posthog.ducklake.client import make_duckgres_conninfo
-from posthog.ducklake.common import get_duckgres_server_for_organization, get_ducklake_catalog_by_team_org
-from posthog.ducklake.models import DuckLakeBackfill, DuckLakeCatalog
+from posthog.ducklake.common import _get_org_id_for_team, derive_duckling_bucket
+from posthog.ducklake.models import DuckLakeBackfill
logger = structlog.get_logger(__name__)
@@ -167,6 +168,33 @@ def _get_cluster() -> ClickhouseCluster:
return get_cluster()
[email protected](frozen=True)
+class DucklingTarget:
+ """Resolved per-org duckling backfill target: connection identity + S3 storage.
+
+ Replaces DuckLakeCatalog in the backfill path — built once per run from the team's
+ organization id (which drives both the duckgres connection, via make_duckgres_conninfo,
+ and the deterministically derived S3 bucket). Duckgres owns catalog attachment, so no
+ catalog-DB connection is needed here.
+ """
+
+ team_id: int
+ organization_id: str
+ bucket: str
+ bucket_region: str
+
+
+def _resolve_duckling_target(team_id: int) -> DucklingTarget:
+ """Resolve the per-org duckling target for a backfill partition.
+
+ The organization id (team → org) drives both the connection (make_duckgres_conninfo
+ resolves the duckgres server itself) and the deterministically derived S3 bucket.
+ """
+ org_id = _get_org_id_for_team(team_id)
+ bucket, bucket_region = derive_duckling_bucket(org_id)
+ return DucklingTarget(team_id=team_id, organization_id=org_id, bucket=bucket, bucket_region=bucket_region)
+
+
@retry(
# The duckgres CP absorbs a warm-pool miss by blocking the connect itself for
# up to the outer workerQueueTimeout (5m) waiting for a colocated worker — so a
@@ -182,7 +210,7 @@ def _get_cluster() -> ClickhouseCluster:
retry=retry_if_exception_type((psycopg.OperationalError, OSError)),
reraise=True,
)
-def _connect_duckgres(catalog: DuckLakeCatalog) -> psycopg.Connection[Any]:
+def _connect_duckgres(target: DucklingTarget) -> psycopg.Connection[Any]:
"""Open a psycopg connection to the org's duckgres server.
Each org runs its own duckgres process on the duckling side; it auto-attaches
@@ -197,15 +225,9 @@ def _connect_duckgres(catalog: DuckLakeCatalog) -> psycopg.Connection[Any]:
retry the connect rather than failing the partition on the first timeout.
`psycopg.errors.ConnectionTimeout` is an `OperationalError` subclass.
"""
- if catalog.team_id is None:
- raise ValueError(
- f"DuckLakeCatalog team_id is None for org={catalog.organization_id} — "
- "cannot route to a duckgres instance without a team identifier."
- )
-
conninfo = make_duckgres_conninfo(
- catalog.team_id,
- organization_id=str(catalog.organization_id),
+ target.team_id,
+ organization_id=target.organization_id,
)
return psycopg.connect(
conninfo,
@@ -305,10 +327,10 @@ class _DuckgresSession:
MAX_ATTEMPTS = 4
- def __init__(self, context: AssetExecutionContext, catalog: DuckLakeCatalog) -> None:
+ def __init__(self, context: AssetExecutionContext, target: DucklingTarget) -> None:
self._context = context
- self._catalog = catalog
- self._conn = _connect_duckgres(catalog)
+ self._target = target
+ self._conn = _connect_duckgres(target)
@property
def conn(self) -> psycopg.Connection[Any]:
@@ -351,7 +373,7 @@ class _DuckgresSession:
self._conn.close()
except Exception:
pass
- self._conn = _connect_duckgres(self._catalog)
+ self._conn = _connect_duckgres(self._target)
def close(self) -> None:
try:
@@ -803,7 +825,7 @@ def _set_table_partitioning(
def ensure_events_table_exists(
context: AssetExecutionContext,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
conn: psycopg.Connection[Any],
) -> bool:
"""Create the events table in the duckling's DuckLake catalog if it doesn't exist.
@@ -827,7 +849,7 @@ def ensure_events_table_exists(
"events",
"year(timestamp), month(timestamp), day(timestamp)",
context,
- catalog.team_id,
+ target.team_id,
)
return False
@@ -845,20 +867,20 @@ def ensure_events_table_exists(
"events",
"year(timestamp), month(timestamp), day(timestamp)",
context,
- catalog.team_id,
+ target.team_id,
)
logger.info(
"duckling_events_table_created",
- team_id=catalog.team_id,
- bucket=catalog.bucket,
+ team_id=target.team_id,
+ bucket=target.bucket,
)
return True
def ensure_persons_table_exists(
context: AssetExecutionContext,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
conn: psycopg.Connection[Any],
) -> bool:
"""Create the persons table in the duckling's DuckLake catalog if it doesn't exist.
@@ -882,7 +904,7 @@ def ensure_persons_table_exists(
"persons",
"year(_timestamp), month(_timestamp)",
context,
- catalog.team_id,
+ target.team_id,
)
return False
@@ -900,20 +922,20 @@ def ensure_persons_table_exists(
"persons",
"year(_timestamp), month(_timestamp)",
context,
- catalog.team_id,
+ target.team_id,
)
logger.info(
"duckling_persons_table_created",
- team_id=catalog.team_id,
- bucket=catalog.bucket,
+ team_id=target.team_id,
+ bucket=target.bucket,
)
return True
def validate_duckling_schema(
context: AssetExecutionContext,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
conn: psycopg.Connection[Any],
) -> None:
"""Validate that the duckling's events table schema matches our export columns.
@@ -936,7 +958,7 @@ def validate_duckling_schema(
)
logger.warning(
"duckling_schema_mismatch",
- team_id=catalog.team_id,
+ team_id=target.team_id,
missing_columns=list(missing_in_ducklake),
)
@@ -950,7 +972,7 @@ def validate_duckling_schema(
)
logger.info(
"duckling_schema_validation_passed",
- team_id=catalog.team_id,
+ team_id=target.team_id,
ducklake_columns=len(ducklake_columns),
export_columns=len(EXPECTED_DUCKLAKE_EVENTS_COLUMNS),
)
@@ -958,7 +980,7 @@ def validate_duckling_schema(
def validate_duckling_persons_schema(
context: AssetExecutionContext,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
conn: psycopg.Connection[Any],
) -> None:
"""Validate that the duckling's persons table schema matches our export columns."""
@@ -977,7 +999,7 @@ def validate_duckling_persons_schema(
)
logger.warning(
"duckling_persons_schema_mismatch",
- team_id=catalog.team_id,
+ team_id=target.team_id,
missing_columns=list(missing_in_ducklake),
)
@@ -991,7 +1013,7 @@ def validate_duckling_persons_schema(
)
logger.info(
"duckling_persons_schema_validation_passed",
- team_id=catalog.team_id,
+ team_id=target.team_id,
ducklake_columns=len(ducklake_columns),
export_columns=len(EXPECTED_DUCKLAKE_PERSONS_COLUMNS),
)
@@ -1024,7 +1046,7 @@ def _execute_export_with_retry(
def delete_events_partition_data(
context: AssetExecutionContext,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
team_id: int,
partition_date: datetime,
conn: psycopg.Connection[Any],
@@ -1090,7 +1112,7 @@ def delete_events_partition_data(
def delete_persons_partition_data(
context: AssetExecutionContext,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
team_id: int,
partition_date: datetime | None,
conn: psycopg.Connection[Any],
@@ -1163,7 +1185,7 @@ def export_events_to_duckling_s3(
context: AssetExecutionContext,
client: Client,
config: DucklingBackfillConfig,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
team_id: int,
date: datetime,
run_id: str,
@@ -1186,10 +1208,10 @@ def export_events_to_duckling_s3(
path_without_scheme = f"{BACKFILL_EVENTS_S3_PREFIX}/{team_id}/year={year}/month={month}/day={day}/{run_id}.parquet"
# ClickHouse needs HTTPS URL format for cross-account S3 access
- s3_url = get_s3_url_for_clickhouse(catalog.bucket, catalog.bucket_region, path_without_scheme)
+ s3_url = get_s3_url_for_clickhouse(target.bucket, target.bucket_region, path_without_scheme)
# S3 path with scheme for DuckLake registration
- s3_path = f"s3://{catalog.bucket}/{path_without_scheme}"
+ s3_path = f"s3://{target.bucket}/{path_without_scheme}"
where_clause = f"team_id = {team_id} AND toDate(timestamp) = '{date_str}'"
@@ -1249,7 +1271,7 @@ def export_events_to_duckling_s3(
def register_file_with_duckling(
context: AssetExecutionContext,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
s3_path: str,
config: DucklingBackfillConfig,
conn: psycopg.Connection[Any],
@@ -1264,7 +1286,7 @@ def register_file_with_duckling(
Args:
context: Dagster asset execution context.
- catalog: The DuckLakeCatalog for this duckling.
+ target: The resolved duckling target (duckgres connection identity + S3 bucket).
s3_path: S3 path of the Parquet file to register.
config: Job configuration.
conn: psycopg connection to the org's duckgres server.
@@ -1277,7 +1299,7 @@ def register_file_with_duckling(
return False
if config.dry_run:
- context.log.info(f"[DRY RUN] Would register {s3_path} with DuckLake at {catalog.db_host}")
+ context.log.info(f"[DRY RUN] Would register {s3_path} with DuckLake (org {target.organization_id})")
return False
alias = DUCKLAKE_ALIAS
@@ -1298,12 +1320,12 @@ def register_file_with_duckling(
logger.exception(
"duckling_file_registration_failed",
s3_path=s3_path,
- team_id=catalog.team_id,
+ team_id=target.team_id,
)
raise
context.log.info(f"Successfully registered: {s3_path}")
- logger.info("duckling_file_registered", s3_path=s3_path, team_id=catalog.team_id)
+ logger.info("duckling_file_registered", s3_path=s3_path, team_id=target.team_id)
return True
@@ -1311,7 +1333,7 @@ def export_persons_to_duckling_s3(
context: AssetExecutionContext,
client: Client,
config: DucklingBackfillConfig,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
team_id: int,
date: datetime,
run_id: str,
@@ -1334,8 +1356,8 @@ def export_persons_to_duckling_s3(
date_str = date.strftime("%Y-%m-%d")
path_without_scheme = f"{BACKFILL_PERSONS_S3_PREFIX}/{team_id}/year={year}/month={month}/{run_id}.parquet"
- s3_url = get_s3_url_for_clickhouse(catalog.bucket, catalog.bucket_region, path_without_scheme)
- s3_path = f"s3://{catalog.bucket}/{path_without_scheme}"
+ s3_url = get_s3_url_for_clickhouse(target.bucket, target.bucket_region, path_without_scheme)
+ s3_path = f"s3://{target.bucket}/{path_without_scheme}"
# Join person with person_distinct_id2 to get distinct_ids
# Use FINAL to handle ReplacingMergeTree deduplication
@@ -1386,7 +1408,7 @@ def export_persons_full_to_duckling_s3(
context: AssetExecutionContext,
client: Client,
config: DucklingBackfillConfig,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
team_id: int,
run_id: str,
settings: dict[str, Any],
@@ -1401,8 +1423,8 @@ def export_persons_full_to_duckling_s3(
S3 path that was written, or None if dry_run.
"""
path_without_scheme = f"{BACKFILL_PERSONS_S3_PREFIX}/{team_id}/year=0/month=0/{run_id}.parquet"
- s3_url = get_s3_url_for_clickhouse(catalog.bucket, catalog.bucket_region, path_without_scheme)
- s3_path = f"s3://{catalog.bucket}/{path_without_scheme}"
+ s3_url = get_s3_url_for_clickhouse(target.bucket, target.bucket_region, path_without_scheme)
+ s3_path = f"s3://{target.bucket}/{path_without_scheme}"
# Join person with person_distinct_id2 to get distinct_ids
# Use FINAL to handle ReplacingMergeTree deduplication
@@ -1459,7 +1481,7 @@ def export_persons_full_to_duckling_s3(
def register_persons_file_with_duckling(
context: AssetExecutionContext,
- catalog: DuckLakeCatalog,
+ target: DucklingTarget,
s3_path: str,
config: DucklingBackfillConfig,
conn: psycopg.Connection[Any],
@@ -1474,7 +1496,7 @@ def register_persons_file_with_duckling(
return False
if config.dry_run:
- context.log.info(f"[DRY RUN] Would register {s3_path} with DuckLake at {catalog.db_host}")
+ context.log.info(f"[DRY RUN] Would register {s3_path} with DuckLake (org {target.organization_id})")
return False
alias = DUCKLAKE_ALIAS
@@ -1495,7 +1517,7 @@ def register_persons_file_with_duckling(
logger.exception(
"duckling_persons_file_registration_failed",
s3_path=s3_path,
- team_id=catalog.team_id,
+ team_id=target.team_id,
)
raise
@@ -1503,7 +1525,7 @@ def register_persons_file_with_duckling(
logger.info(
"duckling_persons_file_registered",
s3_path=s3_path,
- team_id=catalog.team_id,
+ team_id=target.team_id,
)
return True
@@ -1521,7 +1543,7 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
This asset:
1. Parses the partition key to get team_id and date(s)
- 2. Looks up the DuckLakeCatalog for the team
+ 2. Resolves the duckling target — DuckgresServer connection + derived S3 bucket
3. Creates the events table if it doesn't exist (optional, enabled by default)
4. Validates the duckling's schema compatibility (optional)
5. For each date in the partition:
@@ -1540,23 +1562,16 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
run_id=run_id,
)
- # Look up the duckling configuration
- catalog = get_ducklake_catalog_by_team_org(team_id)
- if catalog is None:
- raise ValueError(f"No DuckLakeCatalog found for team_id={team_id}")
+ # Resolve the duckling target: org id (team → org) drives both the connection and the
+ # S3 bucket, derived deterministically (mirrors the duckgres Crossplane composition).
+ target = _resolve_duckling_target(team_id)
- server = get_duckgres_server_for_organization(str(catalog.organization_id))
- if server is None:
- raise ValueError(f"No DuckgresServer found for org={catalog.organization_id} — cannot proceed with backfill.")
-
- context.log.info(
- f"Backfill ready for team_id={team_id}: duckgres={server.host}:{server.port}, bucket={catalog.bucket}"
- )
+ context.log.info(f"Backfill ready for team_id={team_id}: org={target.organization_id}, bucket={target.bucket}")
# Open one duckgres connection for all metadata operations, but skip it
# entirely when no duckgres-backed work will run (dry_run / skip_ducklake_registration).
should_use_duckgres = not (config.dry_run or config.skip_ducklake_registration)
- session = _DuckgresSession(context, catalog) if should_use_duckgres else None
+ session = _DuckgresSession(context, target) if should_use_duckgres else None
try:
if session is not None:
# Delete events table if requested (dangerous - loses all data)
@@ -1572,19 +1587,19 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
logger.exception(
"duckling_events_table_drop_failed",
team_id=team_id,
- bucket=catalog.bucket,
+ bucket=target.bucket,
)
raise
# Create events table if it doesn't exist
if config.create_tables_if_missing:
context.log.info("Ensuring events table exists in duckling catalog...")
- session.run("ensure events table", lambda c: ensure_events_table_exists(context, catalog, c))
+ session.run("ensure events table", lambda c: ensure_events_table_exists(context, target, c))
# Validate schema before starting export
if not config.skip_schema_validation:
context.log.info("Validating duckling schema compatibility...")
- session.run("validate events schema", lambda c: validate_duckling_schema(context, catalog, c))
+ session.run("validate events schema", lambda c: validate_duckling_schema(context, target, c))
# Prepare ClickHouse settings
merged_settings = DEFAULT_CLICKHOUSE_SETTINGS.copy()
@@ -1610,7 +1625,7 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
if session is not None and config.cleanup_existing_partition_data:
def delete_events_partition(conn: psycopg.Connection[Any], date: datetime = partition_date) -> None:
- delete_events_partition_data(context, catalog, team_id, date, conn=conn)
+ delete_events_partition_data(context, target, team_id, date, conn=conn)
session.run(f"delete events partition {date_str}", delete_events_partition)
@@ -1620,7 +1635,7 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
context=context,
client=client,
config=config,
- catalog=catalog,
+ target=target,
team_id=team_id,
date=date,
run_id=run_id,
@@ -1650,8 +1665,8 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
# day's range first (idempotent DELETE) then re-add — the net state
# is exactly this file for the day, wherever the prior attempt died.
if config.cleanup_existing_partition_data:
- delete_events_partition_data(context, catalog, team_id, date, conn=conn)
- return register_file_with_duckling(context, catalog, path, config, conn)
+ delete_events_partition_data(context, target, team_id, date, conn=conn)
+ return register_file_with_duckling(context, target, path, config, conn)
if session.run(f"register events file {date_str}", register_events_file):
total_registered += 1
@@ -1663,7 +1678,7 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
"dates_processed": len(dates),
"files_exported": total_exported,
"files_registered": total_registered,
- "bucket": catalog.bucket,
+ "bucket": target.bucket,
}
)
@@ -1703,7 +1718,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
Steps:
1. Parses the partition key to determine export mode (full vs daily)
- 2. Looks up the DuckLakeCatalog for the team
+ 2. Resolves the duckling target — DuckgresServer connection + derived S3 bucket
3. Creates the persons table if it doesn't exist (optional, enabled by default)
4. Validates the duckling's persons schema compatibility (optional)
5. Exports persons to S3 and registers with DuckLake
@@ -1727,22 +1742,16 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
run_id=run_id,
)
- catalog = get_ducklake_catalog_by_team_org(team_id)
- if catalog is None:
- raise ValueError(f"No DuckLakeCatalog found for team_id={team_id}")
-
- server = get_duckgres_server_for_organization(str(catalog.organization_id))
- if server is None:
- raise ValueError(f"No DuckgresServer found for org={catalog.organization_id} — cannot proceed with backfill.")
+ # Resolve the duckling target: org id (team → org) drives both the connection and the
+ # S3 bucket, derived deterministically (mirrors the duckgres Crossplane composition).
+ target = _resolve_duckling_target(team_id)
- context.log.info(
- f"Backfill ready for team_id={team_id}: duckgres={server.host}:{server.port}, bucket={catalog.bucket}"
- )
+ context.log.info(f"Backfill ready for team_id={team_id}: org={target.organization_id}, bucket={target.bucket}")
# Open one duckgres connection for all metadata operations, but skip it
# entirely when no duckgres-backed work will run (dry_run / skip_ducklake_registration).
should_use_duckgres = not (config.dry_run or config.skip_ducklake_registration)
- session = _DuckgresSession(context, catalog) if should_use_duckgres else None
+ session = _DuckgresSession(context, target) if should_use_duckgres else None
try:
if session is not None:
# Delete persons table if requested (dangerous - loses all data)
@@ -1758,18 +1767,18 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
logger.exception(
"duckling_persons_table_drop_failed",
team_id=team_id,
- bucket=catalog.bucket,
+ bucket=target.bucket,
)
raise
# Create persons table if it doesn't exist
if config.create_tables_if_missing:
context.log.info("Ensuring persons table exists in duckling catalog...")
- session.run("ensure persons table", lambda c: ensure_persons_table_exists(context, catalog, c))
+ session.run("ensure persons table", lambda c: ensure_persons_table_exists(context, target, c))
if not config.skip_schema_validation:
context.log.info("Validating duckling persons schema compatibility...")
- session.run("validate persons schema", lambda c: validate_duckling_persons_schema(context, catalog, c))
+ session.run("validate persons schema", lambda c: validate_duckling_persons_schema(context, target, c))
merged_settings = DEFAULT_CLICKHOUSE_SETTINGS.copy()
merged_settings.update(settings_with_log_comment(context))
@@ -1789,7 +1798,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
if session is not None and config.cleanup_existing_partition_data:
session.run(
"delete all persons",
- lambda c: delete_persons_partition_data(context, catalog, team_id, partition_date=None, conn=c),
+ lambda c: delete_persons_partition_data(context, target, team_id, partition_date=None, conn=c),
)
def do_full_export(client: Client) -> str | None:
@@ -1798,7 +1807,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
context=context,
client=client,
config=config,
- catalog=catalog,
+ target=target,
team_id=team_id,
run_id=run_id,
settings=merged_settings,
@@ -1819,8 +1828,8 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
# team's persons (idempotent DELETE) then re-add, so a replay after a
# committed-but-unacked registration can't double-register the file.
if config.cleanup_existing_partition_data:
- delete_persons_partition_data(context, catalog, team_id, partition_date=None, conn=conn)
- return register_persons_file_with_duckling(context, catalog, path, config, conn)
+ delete_persons_partition_data(context, target, team_id, partition_date=None, conn=conn)
+ return register_persons_file_with_duckling(context, target, path, config, conn)
if session.run("register persons file (full)", register_full_persons_file):
files_registered = 1
@@ -1832,7 +1841,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
"export_mode": "full",
"files_exported": files_exported,
"files_registered": files_registered,
- "bucket": catalog.bucket,
+ "bucket": target.bucket,
}
)
@@ -1862,7 +1871,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
def delete_persons_partition(
conn: psycopg.Connection[Any], date: datetime = partition_date
) -> None:
- delete_persons_partition_data(context, catalog, team_id, date, conn=conn)
+ delete_persons_partition_data(context, target, team_id, date, conn=conn)
session.run(f"delete persons partition {date_str}", delete_persons_partition)
@@ -1872,7 +1881,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
context=context,
client=client,
config=config,
- catalog=catalog,
+ target=target,
team_id=team_id,
date=date,
run_id=run_id,
@@ -1898,8 +1907,8 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
# day's range (idempotent DELETE) then re-add, so a replay after
# a committed-but-unacked registration can't double-register.
if config.cleanup_existing_partition_data:
- delete_persons_partition_data(context, catalog, team_id, date, conn=conn)
- return register_persons_file_with_duckling(context, catalog, path, config, conn)
+ delete_persons_partition_data(context, target, team_id, date, conn=conn)
+ return register_persons_file_with_duckling(context, target, path, config, conn)
if session.run(f"register persons file {date_str}", register_persons_file):
total_registered += 1
@@ -1912,7 +1921,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
"dates_processed": len(dates),
"files_exported": total_exported,
"files_registered": total_registered,
- "bucket": catalog.bucket,
+ "bucket": target.bucket,
}
)
@@ -1942,10 +1951,10 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
def duckling_events_daily_backfill_sensor(
context: SensorEvaluationContext,
) -> SensorResult:
- """Discover teams with DuckLakeCatalog entries and create daily backfill partitions.
+ """Discover teams with backfills enabled (DuckLakeBackfill) and create daily backfill partitions.
This sensor runs periodically to:
- 1. Find all teams with DuckLakeCatalog configurations
+ 1. Find all teams with backfills enabled (DuckLakeBackfill)
2. Create partitions for yesterday's data (if not already exists)
3. Trigger backfill runs for new partitions
4. Retry failed partitions that already exist
@@ -2223,7 +2232,7 @@ duckling_events_backfill_job = define_asset_job(
def duckling_persons_daily_backfill_sensor(
context: SensorEvaluationContext,
) -> SensorResult:
- """Discover teams with DuckLakeCatalog entries and create daily persons partitions.
+ """Discover teams with backfills enabled (DuckLakeBackfill) and create daily persons partitions.
Similar to duckling_events_daily_backfill_sensor but for persons data.
Uses _timestamp (Kafka ingestion time) for date filtering.
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.py
index 267279d5fb61..2c9353cad92b 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -19,10 +19,12 @@ from posthog.dags.events_backfill_to_duckling import (
PERSONS_COLUMNS,
PERSONS_CONCURRENCY_TAG,
PERSONS_TABLE_DDL,
+ DucklingTarget,
_connection_dropped,
_duckgres_backfill_options,
_DuckgresSession,
_get_cluster,
+ _resolve_duckling_target,
_set_table_partitioning,
_validate_identifier,
duckling_events_full_backfill_sensor,
@@ -35,6 +37,17 @@ from posthog.dags.events_backfill_to_duckling import (
)
+class TestResolveDucklingTarget:
+ @patch("posthog.dags.events_backfill_to_duckling.derive_duckling_bucket", return_value=("bkt", "us-west-2"))
+ @patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")
+ def test_builds_target_from_org_and_derived_bucket(self, mock_org: MagicMock, mock_derive: MagicMock):
+ target = _resolve_duckling_target(7)
+
+ assert target == DucklingTarget(team_id=7, organization_id="org-1", bucket="bkt", bucket_region="us-west-2")
+ mock_org.assert_called_once_with(7)
+ mock_derive.assert_called_once_with("org-1")
+
+
class TestParsePartitionKey:
@parameterized.expand(
[
diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.py
index 2664eaa305e2..626dbf68f376 100644
--- a/posthog/ducklake/common.py
+++ b/posthog/ducklake/common.py
@@ -19,11 +19,14 @@ import os
import re
import logging
from typing import TYPE_CHECKING, TypedDict
+from uuid import UUID
import duckdb
import psycopg
from psycopg import sql
+from posthog.utils import get_instance_region
+
if TYPE_CHECKING:
from posthog.ducklake.models import DuckgresServer, DuckLakeCatalog
@@ -237,6 +240,66 @@ def get_duckgres_server_for_organization(organization_id: str) -> DuckgresServer
return None
+def upsert_duckgres_server_for_org(
+ organization_id: str | UUID,
+ *,
+ host: str,
+ port: int,
+ database: str,
+ username: str,
+ password: str,
+) -> DuckgresServer:
+ """Create or update the org's DuckgresServer connection row.
+
+ Called at managed-warehouse provision time so the org is immediately backfill-ready:
+ the Dagster duckling backfill resolves its connection from this row (via
+ get_duckgres_config_for_org). Idempotent — re-provisioning updates the existing row.
+ """
+ from posthog.ducklake.models import DuckgresServer
+
+ server, _ = DuckgresServer.objects.update_or_create(
+ organization_id=organization_id,
+ defaults={
+ "host": host,
+ "port": port,
+ "database": database,
+ "username": username,
+ "password": password,
+ },
+ )
+ return server
+
+
+# Managed-warehouse S3 bucket naming. The bucket is created by the duckgres Crossplane
+# composition (charts: crossplane-config) as "posthog-duckling-{organization_id}-{suffix}",
+# where the suffix identifies the managed-warehouse environment. The mapping is fixed per
+# deployment, so we derive it from the deployment region rather than reading it back.
+DUCKGRES_BUCKET_PREFIX = "posthog-duckling"
+DUCKGRES_BUCKET_REGION = "us-east-1"
+
+
+def _duckling_env_suffix() -> str:
+ """Managed-warehouse environment suffix for the org's S3 bucket name.
+
+ Mirrors the duckgres Crossplane composition, keyed off the deployment region. EU is not
+ enabled yet, so that path is a no-op (raises rather than fabricating a bucket name);
+ everything that isn't prod-US — hosted dev/staging, local dev — maps to "dev".
+ """
+ region = (get_instance_region() or "").upper()
+ if region == "EU":
+ raise NotImplementedError("Managed warehouse is not enabled in the EU region")
+ return "prod-us" if region == "US" else "dev"
+
+
+def derive_duckling_bucket(organization_id: str) -> tuple[str, str]:
+ """Derive the org's managed-warehouse S3 bucket name and region.
+
+ Deterministic — mirrors the duckgres Crossplane composition, which names the bucket
+ "posthog-duckling-{organization_id}-{suffix}". Returns (bucket_name, region).
+ """
+ return f"{DUCKGRES_BUCKET_PREFIX}-{organization_id}-{_duckling_env_suffix()}", DUCKGRES_BUCKET_REGION
+
+
def get_duckgres_server_for_team(team_id: int) -> DuckgresServer | None:
"""Look up DuckgresServer for a team.
diff --git a/posthog/ducklake/test_common.py b/posthog/ducklake/test_common.py
index 7fc231c87bfc..62c5fa87cb20 100644
--- a/posthog/ducklake/test_common.py
+++ b/posthog/ducklake/test_common.py
@@ -4,7 +4,57 @@ from unittest.mock import MagicMock, patch
import duckdb
from parameterized import parameterized
-from posthog.ducklake.common import initialize_ducklake, is_version_mismatch, reset_ducklake_catalog
+from posthog.ducklake.common import (
+ derive_duckling_bucket,
+ initialize_ducklake,
+ is_version_mismatch,
+ reset_ducklake_catalog,
+ upsert_duckgres_server_for_org,
+)
+from posthog.ducklake.models import DuckgresServer
+from posthog.models import Organization
+
+
+class TestDeriveDucklingBucket:
+ @parameterized.expand(
+ [
+ ("prod_us", "US", "posthog-duckling-org-abc-prod-us"),
+ ("hosted_dev", "DEV", "posthog-duckling-org-abc-dev"),
+ ("local_unset", None, "posthog-duckling-org-abc-dev"),
+ ]
+ )
+ def test_derives_bucket_from_region(self, _name: str, region: str | None, expected_bucket: str):
+ # Mirrors the duckgres Crossplane composition: posthog-duckling-{org}-{suffix}.
+ with patch("posthog.ducklake.common.get_instance_region", return_value=region):
+ assert derive_duckling_bucket("org-abc") == (expected_bucket, "us-east-1")
+
+ def test_eu_is_not_enabled(self):
+ with patch("posthog.ducklake.common.get_instance_region", return_value="EU"):
+ with pytest.raises(NotImplementedError, match="EU"):
+ derive_duckling_bucket("org-1")
+
+
+class TestUpsertDuckgresServerForOrg:
+ def test_creates_then_updates_a_single_row(self):
+ org = Organization.objects.create(name="Test Org")
+
+ created = upsert_duckgres_server_for_org(
+ org.id, host="wh.dw.us.postwh.com", port=5432, database="ducklake", username="root", password="pw1"
+ )
+ assert DuckgresServer.objects.filter(organization_id=org.id).count() == 1
+ assert created.host == "wh.dw.us.postwh.com"
+ assert created.password == "pw1"
+
+ updated = upsert_duckgres_server_for_org(
+ org.id, host="wh2.dw.us.postwh.com", port=6543, database="ducklake", username="root", password="pw2"
+ )
+ assert DuckgresServer.objects.filter(organization_id=org.id).count() == 1
+ assert updated.pk == created.pk
+ assert updated.host == "wh2.dw.us.postwh.com"
+ assert updated.port == 6543
+ assert updated.password == "pw2"
+
TEST_CONFIG = {
"DUCKLAKE_RDS_HOST": "localhost",
diff --git a/products/data_warehouse/backend/api/managed_warehouse.py b/products/data_warehouse/backend/api/managed_warehouse.py
index 83c04588f468..e7955228ba4b 100644
--- a/products/data_warehouse/backend/api/managed_warehouse.py
+++ b/products/data_warehouse/backend/api/managed_warehouse.py
@@ -184,7 +184,7 @@ def provision(organization_id: UUID | str, database_name: str | None) -> Respons
name_error = validate_warehouse_name(database_name)
if name_error:
return Response({"error": name_error}, status=status.HTTP_400_BAD_REQUEST)
- return _request(
+ resp = _request(
"POST",
organization_id,
"/provision",
@@ -195,6 +195,37 @@ def provision(organization_id: UUID | str, database_name: str | None) -> Respons
"data_store": {"type": "s3bucket"},
},
)
+ if status.is_success(resp.status_code) and isinstance(resp.data, dict):
+ _persist_duckgres_server(organization_id, database_name, resp.data)
+ return resp
+
+
+def _persist_duckgres_server(organization_id: UUID | str, database_name: str | None, body: dict) -> None:
+ """Persist the org's DuckgresServer row from a successful provision response.
+
+ The Dagster duckling backfill connects via this row, so provisioning must leave it in
+ place. The connection mirrors `_present_connection` (the SNI host + "ducklake" database);
+ the password is returned only in this provision response, so it's read from `body`.
+
+ Best-effort: a persistence failure is logged but never raised, because the provision
+ password is shown to the user exactly once (here) and must not be lost to a DB hiccup —
+ the row can be reconciled later from the warehouse status.
+ """
+ # Keep ducklake.common (and its duckdb dependency) off the API import path.
+ from posthog.ducklake.common import upsert_duckgres_server_for_org # noqa: PLC0415
+
+ try:
+ connection = _present_connection({"database": database_name, "username": body.get("username", "root")})
+ upsert_duckgres_server_for_org(
+ organization_id,
+ host=connection["host"],
+ port=connection["port"],
+ database=connection["database"],
+ username=connection["username"],
+ password=body.get("password", ""),
+ )
+ except Exception:
+ logger.exception("Failed to persist DuckgresServer after provision", organization_id=str(organization_id))
def deprovision(organization_id: UUID | str) -> Response:
diff --git a/products/data_warehouse/backend/api/test/test_managed_warehouse.py b/products/data_warehouse/backend/api/test/test_managed_warehouse.py
index 11a2267db570..54bac824ce15 100644
--- a/products/data_warehouse/backend/api/test/test_managed_warehouse.py
+++ b/products/data_warehouse/backend/api/test/test_managed_warehouse.py
@@ -1,7 +1,15 @@
from uuid import uuid4
+import pytest
from unittest.mock import MagicMock, patch
+from django.test import override_settings
+
+from rest_framework.response import Response
+
+from posthog.ducklake.models import DuckgresServer
+from posthog.models import Organization
+
from products.data_warehouse.backend.api import managed_warehouse
@@ -20,3 +28,35 @@ def test_is_enabled_uses_data_warehouse_scene_flag(mock_feature_enabled: MagicMo
only_evaluate_locally=True,
send_feature_flag_events=False,
)
+
+
+@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)
+@patch("products.data_warehouse.backend.api.managed_warehouse._request")
+def test_provision_persists_duckgres_server_on_success(mock_request: MagicMock) -> None:
+ org = Organization.objects.create(name="Org")
+ mock_request.return_value = Response(
+ {"status": "provisioning started", "org": str(org.id), "username": "root", "password": "secret"},
+ status=202,
+ )
+
+ resp = managed_warehouse.provision(org.id, "my-warehouse")
+
+ assert resp.status_code == 202
+ server = DuckgresServer.objects.get(organization_id=org.id)
+ assert server.host == "my-warehouse.dw.us.postwh.com"
+ assert server.database == "ducklake"
+ assert server.username == "root"
+ assert server.password == "secret"
+
+
+@patch("products.data_warehouse.backend.api.managed_warehouse._request")
+def test_provision_does_not_persist_on_failure(mock_request: MagicMock) -> None:
+ org = Organization.objects.create(name="Org")
+ mock_request.return_value = Response({"error": "boom"}, status=500)
+
+ resp = managed_warehouse.provision(org.id, "my-warehouse")
+
+ assert resp.status_code == 500
+ assert not DuckgresServer.objects.filter(organization_id=org.id).exists()