:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): write duckling backfills to per-environment tables (#64951)
Eric Duongc3923690c563
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 4cf6f60d14d3..f2ad1ff5d86a 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -188,13 +188,32 @@ class DucklingTarget:organization_id: strbucket: strbucket_region: str+ # Default to the shared tables; _resolve_duckling_target sets these per-team from table_suffix.+ events_table: str = "events"+ persons_table: str = "persons"+++def _resolve_table_names(team_id: int) -> tuple[str, str]:+ """Resolve this team's per-environment events/persons table names.++ A team's `DuckLakeBackfill.table_suffix` (when set) isolates its data into+ dedicated `events_<suffix>` / `persons_<suffix>` tables so multiple teams sharing one+ org-scoped duckling don't merge into the shared `posthog.events` / `posthog.persons`.+ An unset suffix (legacy single-team ducklings) keeps the shared table names.+ """+ suffix = DuckLakeBackfill.objects.filter(team_id=team_id).values_list("table_suffix", flat=True).first()+ if not suffix:+ return "events", "persons"+ _validate_identifier(suffix)+ return f"events_{suffix}", f"persons_{suffix}"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 S3 bucket.+ resolves the duckgres server itself) and the S3 bucket. The table names carry the team's+ per-environment suffix (or the shared defaults).Bucket resolution order:1. The org's DuckLakeCatalog row (hand-entered, older orgs that predate the control@@ -215,11 +234,19 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:from products.data_warehouse.backend.api import managed_warehouse # noqa: PLC0415org_id = _get_org_id_for_team(team_id)+ events_table, persons_table = _resolve_table_names(team_id)catalog = get_ducklake_catalog_for_organization(org_id)if catalog is not None and catalog.bucket:bucket, bucket_region = catalog.bucket, catalog.bucket_region- return DucklingTarget(team_id=team_id, organization_id=org_id, bucket=bucket, bucket_region=bucket_region)+ return DucklingTarget(+ team_id=team_id,+ organization_id=org_id,+ bucket=bucket,+ bucket_region=bucket_region,+ events_table=events_table,+ persons_table=persons_table,+ )# Control plane first — authoritative, and rejects an org_id-mismatched status body.cp_bucket = managed_warehouse.cp_bucket_for(org_id)@@ -231,7 +258,12 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:bucket=cp_bucket,)return DucklingTarget(- team_id=team_id, organization_id=org_id, bucket=cp_bucket, bucket_region=DUCKGRES_BUCKET_REGION+ team_id=team_id,+ organization_id=org_id,+ bucket=cp_bucket,+ bucket_region=DUCKGRES_BUCKET_REGION,+ events_table=events_table,+ persons_table=persons_table,)# CP couldn't answer — fall back to the stored row if it knows a bucket.@@ -244,7 +276,14 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:organization_id=org_id,bucket=bucket,)- return DucklingTarget(team_id=team_id, organization_id=org_id, bucket=bucket, bucket_region=bucket_region)+ return DucklingTarget(+ team_id=team_id,+ organization_id=org_id,+ bucket=bucket,+ bucket_region=bucket_region,+ events_table=events_table,+ persons_table=persons_table,+ )raise ValueError(f"No S3 bucket resolvable for org {org_id}: absent from DuckLakeCatalog, the control "@@ -613,7 +652,7 @@ duckling_persons_partitions_def = DynamicPartitionsDefinition(name="duckling_per# SQL for creating the events table in DuckLake if it doesn't exist# Uses TIMESTAMPTZ because ClickHouse exports DateTime64 as TIMESTAMP WITH TIME ZONE in Parquet.EVENTS_TABLE_DDL = """-CREATE TABLE IF NOT EXISTS {catalog}.posthog.events (+CREATE TABLE IF NOT EXISTS {catalog}.posthog.{table} (uuid VARCHAR,event VARCHAR,properties VARCHAR,@@ -646,7 +685,7 @@ CREATE TABLE IF NOT EXISTS {catalog}.posthog.events (# Uses TIMESTAMPTZ because ClickHouse exports DateTime64 as TIMESTAMP WITH TIME ZONE in Parquet.# Note: person_version uses UBIGINT to match ClickHouse's UInt64 type.PERSONS_TABLE_DDL = """-CREATE TABLE IF NOT EXISTS {catalog}.posthog.persons (+CREATE TABLE IF NOT EXISTS {catalog}.posthog.{table} (team_id BIGINT,distinct_id VARCHAR,id VARCHAR,@@ -956,14 +995,15 @@ def ensure_events_table_exists(idempotent - calling SET PARTITIONED BY multiple times with the same keys succeeds."""alias = DUCKLAKE_ALIAS+ table = target.events_table- if table_exists(conn, alias, "posthog", "events"):+ if table_exists(conn, alias, "posthog", table):context.log.info("Events table already exists in duckling catalog")# Ensure partitioning is set even on existing tables (idempotent)_set_table_partitioning(conn,alias,- "events",+ table,"year(timestamp), month(timestamp), day(timestamp)",context,target.team_id,@@ -974,14 +1014,14 @@ def ensure_events_table_exists(conn.execute(f"CREATE SCHEMA IF NOT EXISTS {alias}.posthog")context.log.info("Creating events table in duckling catalog...")- conn.execute(EVENTS_TABLE_DDL.format(catalog=alias))+ conn.execute(EVENTS_TABLE_DDL.format(catalog=alias, table=table))context.log.info("Successfully created events table")# Set partitioning by year/month/day for efficient querying_set_table_partitioning(conn,alias,- "events",+ table,"year(timestamp), month(timestamp), day(timestamp)",context,target.team_id,@@ -1011,14 +1051,15 @@ def ensure_persons_table_exists(idempotent - calling SET PARTITIONED BY multiple times with the same keys succeeds."""alias = DUCKLAKE_ALIAS+ table = target.persons_table- if table_exists(conn, alias, "posthog", "persons"):+ if table_exists(conn, alias, "posthog", table):context.log.info("Persons table already exists in duckling catalog")# Ensure partitioning is set even on existing tables (idempotent)_set_table_partitioning(conn,alias,- "persons",+ table,"year(_timestamp), month(_timestamp)",context,target.team_id,@@ -1029,14 +1070,14 @@ def ensure_persons_table_exists(conn.execute(f"CREATE SCHEMA IF NOT EXISTS {alias}.posthog")context.log.info("Creating persons table in duckling catalog...")- conn.execute(PERSONS_TABLE_DDL.format(catalog=alias))+ conn.execute(PERSONS_TABLE_DDL.format(catalog=alias, table=table))context.log.info("Successfully created persons table")# Set partitioning by year/month of _timestamp for efficient querying_set_table_partitioning(conn,alias,- "persons",+ table,"year(_timestamp), month(_timestamp)",context,target.team_id,@@ -1063,7 +1104,7 @@ def validate_duckling_schema(alias = DUCKLAKE_ALIASwith conn.cursor() as cur:- cur.execute(f"DESCRIBE {alias}.posthog.events")+ cur.execute(f"DESCRIBE {alias}.posthog.{target.events_table}")ducklake_columns = {row[0] for row in cur.fetchall()}missing_in_ducklake = EXPECTED_DUCKLAKE_EVENTS_COLUMNS - ducklake_columns@@ -1104,7 +1145,7 @@ def validate_duckling_persons_schema(alias = DUCKLAKE_ALIASwith conn.cursor() as cur:- cur.execute(f"DESCRIBE {alias}.posthog.persons")+ cur.execute(f"DESCRIBE {alias}.posthog.{target.persons_table}")ducklake_columns = {row[0] for row in cur.fetchall()}missing_in_ducklake = EXPECTED_DUCKLAKE_PERSONS_COLUMNS - ducklake_columns@@ -1224,7 +1265,7 @@ def delete_events_partition_data(# to a single day's partition instead of scanning all data files.next_date_str = (partition_date + timedelta(days=1)).strftime("%Y-%m-%d")delete_sql = f"""- DELETE FROM {alias}.posthog.events+ DELETE FROM {alias}.posthog.{target.events_table}WHERE team_id = %sAND timestamp >= %sAND timestamp < %s@@ -1286,7 +1327,7 @@ def delete_persons_partition_data(delete_params: tuple[Any, ...]if partition_date is None:delete_sql = f"""- DELETE FROM {alias}.posthog.persons+ DELETE FROM {alias}.posthog.{target.persons_table}WHERE team_id = %s"""delete_params = (team_id,)@@ -1294,7 +1335,7 @@ def delete_persons_partition_data(date_str = partition_date.strftime("%Y-%m-%d")next_date_str = (partition_date + timedelta(days=1)).strftime("%Y-%m-%d")delete_sql = f"""- DELETE FROM {alias}.posthog.persons+ DELETE FROM {alias}.posthog.{target.persons_table}WHERE team_id = %sAND _timestamp >= %sAND _timestamp < %s@@ -1507,10 +1548,9 @@ def register_files_with_duckling(# column (team_id/uuid/timestamp) would only arise from an export bug, not# normal operation, and would surface as NULL-filled rows in downstream reads.conn.execute(- psql.SQL(- "CALL ducklake_add_data_files({}, 'events', {}, schema => 'posthog', allow_missing => true)"- ).format(+ psql.SQL("CALL ducklake_add_data_files({}, {}, {}, schema => 'posthog', allow_missing => true)").format(psql.Literal(alias),+ psql.Literal(target.events_table),psql.Literal(s3_path),))@@ -1775,10 +1815,9 @@ def register_persons_files_with_duckling(for s3_path in files:# See the events registration site for the allow_missing rationale.conn.execute(- psql.SQL(- "CALL ducklake_add_data_files({}, 'persons', {}, schema => 'posthog', allow_missing => true)"- ).format(+ psql.SQL("CALL ducklake_add_data_files({}, {}, {}, schema => 'posthog', allow_missing => true)").format(psql.Literal(alias),+ psql.Literal(target.persons_table),psql.Literal(s3_path),))@@ -1857,7 +1896,7 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBactry:session.run("drop events table",- lambda c: c.execute(f"DROP TABLE IF EXISTS {DUCKLAKE_ALIAS}.posthog.events"),+ lambda c: c.execute(f"DROP TABLE IF EXISTS {DUCKLAKE_ALIAS}.posthog.{target.events_table}"),)except Exception:context.log.exception(f"Failed to drop events table for team_id={team_id}")@@ -2038,7 +2077,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBatry:session.run("drop persons table",- lambda c: c.execute(f"DROP TABLE IF EXISTS {DUCKLAKE_ALIAS}.posthog.persons"),+ lambda c: c.execute(f"DROP TABLE IF EXISTS {DUCKLAKE_ALIAS}.posthog.{target.persons_table}"),)except Exception:context.log.exception(f"Failed to drop persons table for team_id={team_id}")diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex 7b5f76b79a00..73e58558004d 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -36,6 +36,7 @@ from posthog.dags.events_backfill_to_duckling import (_get_cluster,_glob_run_files,_resolve_duckling_target,+ _resolve_table_names,_set_table_partitioning,_validate_identifier,delete_events_partition_data,@@ -69,11 +70,12 @@ class TestDucklingBackfillAlertRouting:class TestResolveDucklingTarget:+ @patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons"))@patch("posthog.dags.events_backfill_to_duckling.get_duckgres_server_for_organization", return_value=None)@patch("posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=None)@patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")def test_resolves_bucket_from_control_plane(- self, mock_org: MagicMock, _mock_catalog: MagicMock, _mock_server: MagicMock+ self, mock_org: MagicMock, _mock_catalog: MagicMock, _mock_server: MagicMock, _mock_tables: MagicMock):# The control plane is the authoritative owner of the bucket name.with patch(@@ -91,9 +93,12 @@ class TestResolveDucklingTarget:mock_org.assert_called_once_with(7)mock_cp.assert_called_once_with("org-1")+ @patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons"))@patch("posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=None)@patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")- def test_control_plane_wins_over_stale_stored_server_bucket(self, _mock_org: MagicMock, _mock_catalog: MagicMock):+ def test_control_plane_wins_over_stale_stored_server_bucket(+ self, _mock_org: MagicMock, _mock_catalog: MagicMock, _mock_tables: MagicMock+ ):# A row provisioned before the naming fix carries a stale bucket; the CP value# must win so the backfill never exports to a bucket that doesn't exist.server = MagicMock(bucket="posthog-duckling-stale-prod-us", bucket_region="us-east-1")@@ -111,10 +116,11 @@ class TestResolveDucklingTarget:assert target.bucket == "posthog-duckling-org-1-mw-prod-us"+ @patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons"))@patch("posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=None)@patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")def test_falls_back_to_stored_server_when_control_plane_unavailable(- self, _mock_org: MagicMock, _mock_catalog: MagicMock+ self, _mock_org: MagicMock, _mock_catalog: MagicMock, _mock_tables: MagicMock):# CP can't answer → use the known-good stored row rather than failing the run.server = MagicMock(bucket="posthog-duckling-org-1-mw-prod-us", bucket_region="us-east-1")@@ -132,11 +138,12 @@ class TestResolveDucklingTarget:assert target.bucket == "posthog-duckling-org-1-mw-prod-us"+ @patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons"))@patch("posthog.dags.events_backfill_to_duckling.get_duckgres_server_for_organization", return_value=None)@patch("posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=None)@patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")def test_raises_when_nothing_can_name_the_bucket(- self, _mock_org: MagicMock, _mock_catalog: MagicMock, _mock_server: MagicMock+ self, _mock_org: MagicMock, _mock_catalog: MagicMock, _mock_server: MagicMock, _mock_tables: MagicMock):with patch("products.data_warehouse.backend.api.managed_warehouse.cp_bucket_for",@@ -146,6 +153,38 @@ class TestResolveDucklingTarget:_resolve_duckling_target(7)+class TestResolveTableNames:+ """Resolution of per-environment table names from a team's stored table_suffix.++ Kept DB-free (the rest of this file is): the stored suffix is mocked at the ORM boundary.+ """++ def _patch_suffix(self, suffix: str | None) -> MagicMock:+ model = MagicMock()+ model.objects.filter.return_value.values_list.return_value.first.return_value = suffix+ return model++ def test_set_suffix_yields_dedicated_tables(self):+ with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix("alpha")):+ assert _resolve_table_names(1) == ("events_alpha", "persons_alpha")++ def test_distinct_suffixes_isolate_two_teams(self):+ with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix("alpha")):+ assert _resolve_table_names(1) == ("events_alpha", "persons_alpha")+ with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix("beta")):+ assert _resolve_table_names(2) == ("events_beta", "persons_beta")++ @parameterized.expand([("none", None), ("empty", "")])+ def test_unset_suffix_falls_back_to_shared_tables(self, _name, suffix):+ with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix(suffix)):+ assert _resolve_table_names(1) == ("events", "persons")++ def test_unsafe_suffix_is_rejected(self):+ with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix("a-b; DROP")):+ with pytest.raises(ValueError):+ _resolve_table_names(1)++class TestParsePartitionKey:@parameterized.expand([@@ -263,7 +302,7 @@ class TestEventsDDL:def test_events_ddl_is_valid_sql(self):conn = duckdb.connect()conn.execute("CREATE SCHEMA IF NOT EXISTS memory.posthog")- ddl = EVENTS_TABLE_DDL.format(catalog="memory")+ ddl = EVENTS_TABLE_DDL.format(catalog="memory", table="events")conn.execute(ddl)# Verify table was created with expected columns@@ -276,18 +315,27 @@ class TestEventsDDL:def test_events_ddl_is_idempotent(self):conn = duckdb.connect()conn.execute("CREATE SCHEMA IF NOT EXISTS memory.posthog")- ddl = EVENTS_TABLE_DDL.format(catalog="memory")+ ddl = EVENTS_TABLE_DDL.format(catalog="memory", table="events")# Should not raise on second executionconn.execute(ddl)conn.execute(ddl)conn.close()+ def test_events_ddl_honors_suffixed_table_name(self):+ conn = duckdb.connect()+ conn.execute("CREATE SCHEMA IF NOT EXISTS memory.posthog")+ conn.execute(EVENTS_TABLE_DDL.format(catalog="memory", table="events_alpha"))++ result = conn.execute("DESCRIBE memory.posthog.events_alpha").fetchall()+ assert {row[0] for row in result} == EXPECTED_DUCKLAKE_EVENTS_COLUMNS+ conn.close()+class TestPersonsDDL:def test_persons_ddl_is_valid_sql(self):conn = duckdb.connect()conn.execute("CREATE SCHEMA IF NOT EXISTS memory.posthog")- ddl = PERSONS_TABLE_DDL.format(catalog="memory")+ ddl = PERSONS_TABLE_DDL.format(catalog="memory", table="persons")conn.execute(ddl)# Verify table was created with expected columns@@ -300,12 +348,21 @@ class TestPersonsDDL:def test_persons_ddl_is_idempotent(self):conn = duckdb.connect()conn.execute("CREATE SCHEMA IF NOT EXISTS memory.posthog")- ddl = PERSONS_TABLE_DDL.format(catalog="memory")+ ddl = PERSONS_TABLE_DDL.format(catalog="memory", table="persons")# Should not raise on second executionconn.execute(ddl)conn.execute(ddl)conn.close()+ def test_persons_ddl_honors_suffixed_table_name(self):+ conn = duckdb.connect()+ conn.execute("CREATE SCHEMA IF NOT EXISTS memory.posthog")+ conn.execute(PERSONS_TABLE_DDL.format(catalog="memory", table="persons_beta"))++ result = conn.execute("DESCRIBE memory.posthog.persons_beta").fetchall()+ assert {row[0] for row in result} == EXPECTED_DUCKLAKE_PERSONS_COLUMNS+ conn.close()+class TestParsePartitionKeyDates:@patch("posthog.dags.events_backfill_to_duckling.timezone")@@ -715,7 +772,7 @@ class TestDuckLakeAddDataFilesPartitioning:conn.execute("LOAD ducklake")conn.execute(f"ATTACH 'ducklake:{catalog_path}' AS test_lake (DATA_PATH '{data_path}')")conn.execute("CREATE SCHEMA IF NOT EXISTS test_lake.posthog")- conn.execute(EVENTS_TABLE_DDL.format(catalog="test_lake"))+ conn.execute(EVENTS_TABLE_DDL.format(catalog="test_lake", table="events"))conn.execute("ALTER TABLE test_lake.posthog.events ""SET PARTITIONED BY (year(timestamp), month(timestamp), day(timestamp))"@@ -1391,7 +1448,7 @@ class TestFannedOutLayoutRoundTrip:# DUCKLAKE_ALIAS internally) targets this catalog.conn.execute(f"ATTACH 'ducklake:{catalog_path}' AS {DUCKLAKE_ALIAS} (DATA_PATH '{data_path}')")conn.execute(f"CREATE SCHEMA IF NOT EXISTS {DUCKLAKE_ALIAS}.posthog")- conn.execute(EVENTS_TABLE_DDL.format(catalog=DUCKLAKE_ALIAS))+ conn.execute(EVENTS_TABLE_DDL.format(catalog=DUCKLAKE_ALIAS, table="events"))conn.execute(f"ALTER TABLE {DUCKLAKE_ALIAS}.posthog.events ""SET PARTITIONED BY (year(timestamp), month(timestamp), day(timestamp))"diff --git a/posthog/dags/tests/test_events_backfill_to_duckling.py b/posthog/dags/tests/test_events_backfill_to_duckling.pyindex ae1f601905c0..1b8d36be25eb 100644--- a/posthog/dags/tests/test_events_backfill_to_duckling.py+++ b/posthog/dags/tests/test_events_backfill_to_duckling.py@@ -30,6 +30,8 @@ class TestResolveDucklingTarget:"products.data_warehouse.backend.api.managed_warehouse.cp_bucket_for",return_value=cp_bucket,) as mock_cp,+ # The per-environment table-name lookup hits the DB; this suite stays DB-free.+ patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons")),):target = _resolve_duckling_target(team_id=123)return target, mock_cp