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.

chore(dags): remove iceberg double-write from duckling backfill (#62255)

James Greenhilla965b6f22fda
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index 5e72235d73d7..00086ebf6250 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -28,14 +28,6 @@ Partition Strategy:
DynamicPartitionsDefinition with composite keys: {team_id}_{date}
- team_id maps to duckling via DuckLakeCatalog
- date is the partition date (YYYY-MM-DD)
-
-Iceberg dual-write:
- Teams in ICEBERG_BACKFILL_TEAM_IDS additionally dual-write each exported
- Parquet file into their Iceberg (Lakekeeper) catalog alongside DuckLake.
- Iceberg has no add_data_files equivalent, so the duckgres worker re-reads the
- Parquet from S3 and writes Iceberg data + metadata via INSERT ... SELECT. The
- Iceberg path is best-effort: any failure is logged but never aborts the
- DuckLake backfill, which remains the source of truth for every team.
"""
import os
@@ -88,23 +80,6 @@ logger = structlog.get_logger(__name__)
# so the DAG can hardcode it everywhere instead of threading a config value.
DUCKLAKE_ALIAS = "ducklake"
-# Catalog alias duckgres uses when an org has the Iceberg (Lakekeeper) backend
-# enabled — see duckgres server/iceberg/migration.go CatalogName. Attached only
-# when Iceberg is enabled for the org's warehouse, so all Iceberg work here is
-# best-effort: failures are logged and never abort the DuckLake backfill.
-ICEBERG_ALIAS = "iceberg"
-
-# Teams that additionally dual-write their backfill into Iceberg alongside
-# DuckLake. Hardcoded allowlist for dogfooding the Iceberg path; DuckLake
-# remains the source of truth for every team, including these.
-ICEBERG_BACKFILL_TEAM_IDS = {2}
-
-
-def iceberg_enabled_for_team(team_id: int) -> bool:
- """Whether this team should dual-write its backfill into Iceberg."""
- return team_id in ICEBERG_BACKFILL_TEAM_IDS
-
-
# Duckgres connection timeouts: connect_timeout bounds the TCP+TLS handshake;
# statement_timeout bounds query execution to prevent hung Dagster workers.
# A backfill connection may have to wait for duckgres to spin up a fresh worker
@@ -134,34 +109,26 @@ DUCKGRES_WORKER_PROFILE_ENABLED = os.environ.get("DUCKGRES_WORKER_PROFILE_ENABLE
"yes",
"on",
)
-# Colocated worker sizes. Iceberg-allowlisted orgs dual-write via an
-# INSERT ... SELECT read_parquet over a full event-day (memory-heavy), so they
-# get a larger colocated pod than the metadata-only DuckLake register path.
+# Colocated worker size for the metadata-only DuckLake register path.
DUCKGRES_BACKFILL_COLOCATE_CPU = "4"
DUCKGRES_BACKFILL_COLOCATE_MEMORY = "16Gi"
-DUCKGRES_ICEBERG_BACKFILL_COLOCATE_CPU = "8"
-DUCKGRES_ICEBERG_BACKFILL_COLOCATE_MEMORY = "48Gi"
-def _duckgres_backfill_options(team_id: int) -> str:
+def _duckgres_backfill_options() -> str:
"""libpq startup `options` for a backfill connection.
Always bounds statement execution; when the worker-profile feature is
- enabled, additionally requests a small colocated worker shape (larger for
- Iceberg-allowlisted orgs). Returns a single space-joined `-c key=value` string
- — psycopg forwards it as the startup `options` parameter, which duckgres
- parses to size/schedule the worker.
+ enabled, additionally requests a small colocated worker shape. Returns a
+ single space-joined `-c key=value` string — psycopg forwards it as the
+ startup `options` parameter, which duckgres parses to size/schedule the
+ worker.
"""
opts = [f"-c statement_timeout={DUCKGRES_STATEMENT_TIMEOUT_MS}"]
if DUCKGRES_WORKER_PROFILE_ENABLED:
- if iceberg_enabled_for_team(team_id):
- cpu, memory = DUCKGRES_ICEBERG_BACKFILL_COLOCATE_CPU, DUCKGRES_ICEBERG_BACKFILL_COLOCATE_MEMORY
- else:
- cpu, memory = DUCKGRES_BACKFILL_COLOCATE_CPU, DUCKGRES_BACKFILL_COLOCATE_MEMORY
opts += [
"-c duckgres.colocate=true",
- f"-c duckgres.worker_cpu={cpu}",
- f"-c duckgres.worker_memory={memory}",
+ f"-c duckgres.worker_cpu={DUCKGRES_BACKFILL_COLOCATE_CPU}",
+ f"-c duckgres.worker_memory={DUCKGRES_BACKFILL_COLOCATE_MEMORY}",
]
return " ".join(opts)
@@ -225,7 +192,7 @@ def _connect_duckgres(catalog: DuckLakeCatalog) -> psycopg.Connection[Any]:
conninfo,
autocommit=True,
connect_timeout=DUCKGRES_CONNECT_TIMEOUT,
- options=_duckgres_backfill_options(catalog.team_id),
+ options=_duckgres_backfill_options(),
)
@@ -316,35 +283,6 @@ EXPECTED_DUCKLAKE_PERSONS_COLUMNS = {
"_inserted_at",
}
-# Iceberg has no unsigned integer types, so the persons table mirrors
-# PERSONS_TABLE_DDL but stores person_version as BIGINT instead of UBIGINT.
-# The UInt64 values exported from ClickHouse fit comfortably in a signed
-# 64-bit column in practice (versions are small monotonic counters).
-ICEBERG_PERSONS_TABLE_DDL = """
-CREATE TABLE IF NOT EXISTS {catalog}.posthog.persons (
- team_id BIGINT,
- distinct_id VARCHAR,
- id VARCHAR,
- properties VARCHAR,
- created_at TIMESTAMPTZ,
- is_identified BOOLEAN,
- person_distinct_id_version BIGINT,
- person_version BIGINT,
- _timestamp TIMESTAMPTZ,
- _inserted_at TIMESTAMPTZ
-)
-"""
-
-# Iceberg partition specs. Each uses a SINGLE Iceberg temporal transform per
-# source column — NOT the multi-level year/month/day spec the DuckLake tables
-# use. Lakekeeper rejects declaring several temporal transforms on one source
-# column as redundant ("Cannot add redundant partition with source id … and
-# transform `time`"), and a single day()/month() transform already encodes the
-# full date for partition pruning. DuckDB's Iceberg INSERT path supports these
-# transforms as of 1.5.3 (verified against the live Lakekeeper catalog).
-ICEBERG_EVENTS_PARTITION_EXPR = "day(timestamp)"
-ICEBERG_PERSONS_PARTITION_EXPR = "month(_timestamp)"
-
duckling_events_partitions_def = DynamicPartitionsDefinition(name="duckling_events_backfill")
duckling_persons_partitions_def = DynamicPartitionsDefinition(name="duckling_persons_backfill")
@@ -1363,222 +1301,6 @@ def register_persons_file_with_duckling(
return True
-def drop_iceberg_table(
- context: AssetExecutionContext,
- conn: psycopg.Connection[Any],
- table: str,
-) -> None:
- """Best-effort DROP of the Iceberg table, mirroring delete_tables for DuckLake.
-
- Used when config.delete_tables wipes the DuckLake table so the Iceberg copy
- is reset to match instead of having dual-write append on top of stale rows.
- Failures are logged and swallowed — the Iceberg path must never abort the
- DuckLake backfill (e.g. when the catalog isn't attached for this org).
- """
- _validate_identifier(table)
- try:
- conn.execute(f"DROP TABLE IF EXISTS {ICEBERG_ALIAS}.posthog.{table}")
- context.log.info(f"Dropped Iceberg table {ICEBERG_ALIAS}.posthog.{table} (delete_tables=True)")
- except Exception as exc:
- context.log.warning(f"Best-effort Iceberg DROP of {table} failed (continuing): {exc}")
- logger.warning(
- "duckling_iceberg_drop_table_failed",
- table=table,
- error=str(exc),
- error_type=type(exc).__name__,
- )
-
-
-def _set_iceberg_table_partitioning(
- context: AssetExecutionContext,
- conn: psycopg.Connection[Any],
- table: str,
- partition_expr: str,
-) -> None:
- """Best-effort partition-evolve an existing Iceberg table.
-
- `CREATE TABLE IF NOT EXISTS ... PARTITIONED BY` only partitions a *fresh*
- table; a table created unpartitioned by an earlier deploy keeps its old
- spec. `ALTER TABLE ... SET PARTITIONED BY` evolves it so new data files use
- the new spec (existing files keep theirs — standard Iceberg partition
- evolution). Lakekeeper rejects re-declaring the same spec as "redundant", so
- that specific error is treated as success (the table is already partitioned
- the way we want). Any other failure is logged and swallowed — partitioning
- must never abort the best-effort dual-write.
- """
- _validate_identifier(table)
- try:
- conn.execute(f"ALTER TABLE {ICEBERG_ALIAS}.posthog.{table} SET PARTITIONED BY ({partition_expr})")
- except Exception as exc:
- # Lakekeeper rejects re-declaring an identical spec as redundant; that
- # means the table already carries the partitioning we want.
- if "redundant" in str(exc).lower():
- return
- context.log.warning(f"Best-effort Iceberg partition-evolve of {table} failed (continuing): {exc}")
- logger.warning(
- "duckling_iceberg_set_partitioning_failed",
- table=table,
- partition_expr=partition_expr,
- error=str(exc),
- error_type=type(exc).__name__,
- )
-
-
-def ensure_iceberg_table_exists(
- context: AssetExecutionContext,
- conn: psycopg.Connection[Any],
- table: str,
- ddl: str,
- team_id: int | None = None,
- partition_expr: str | None = None,
-) -> bool:
- """Create the Iceberg schema + table for dual-write, if missing.
-
- Returns True if the Iceberg catalog is usable for this run, False if the
- catalog isn't attached or table creation failed — in which case the caller
- skips Iceberg writes for the run without failing the DuckLake backfill.
-
- The `iceberg` catalog is only attached when the org's warehouse has the
- Iceberg backend enabled (see lakekeeper-iceberg-catalog runbook in duckgres).
-
- When `partition_expr` is set the table is partitioned by a single Iceberg
- temporal transform (e.g. `day(timestamp)`), and existing unpartitioned
- tables are evolved in place via ALTER. DuckDB's Iceberg INSERT path supports
- these transforms as of 1.5.3 (verified against the live Lakekeeper catalog).
- A single transform per source column is used deliberately — Lakekeeper
- rejects the multi-level `year/month/day` spec DuckLake uses as redundant, and
- `day()`/`month()` already encode the full date for partition pruning.
- """
- _validate_identifier(table)
- try:
- conn.execute(f"CREATE SCHEMA IF NOT EXISTS {ICEBERG_ALIAS}.posthog")
- create_sql = ddl.format(catalog=ICEBERG_ALIAS)
- if partition_expr:
- # Append the partition clause to the column-list DDL. Partitions a
- # fresh table; a no-op if the table already exists (handled by the
- # ALTER below).
- create_sql = f"{create_sql.rstrip().rstrip(';')}\nPARTITIONED BY ({partition_expr})"
- conn.execute(create_sql)
- if partition_expr:
- _set_iceberg_table_partitioning(context, conn, table, partition_expr)
- return True
- except Exception as exc:
- context.log.warning(
- f"Iceberg dual-write disabled for this run (team_id={team_id}) — could not ensure "
- f"{ICEBERG_ALIAS}.posthog.{table}: {exc}. Is the Iceberg backend enabled for this org's warehouse?"
- )
- logger.warning(
- "duckling_iceberg_ensure_table_failed",
- table=table,
- team_id=team_id,
- error=str(exc),
- error_type=type(exc).__name__,
- )
- return False
-
-
-def write_partition_to_iceberg(
- context: AssetExecutionContext,
- conn: psycopg.Connection[Any],
- table: str,
- s3_path: str,
- team_id: int,
- timestamp_column: str,
- partition_date: datetime | None,
-) -> bool:
- """Dual-write one exported Parquet file into the team's Iceberg table.
-
- Iceberg has no `ducklake_add_data_files` equivalent — the only write path is
- `INSERT ... SELECT`, so the duckgres worker re-reads the Parquet from S3 and
- writes Iceberg data + metadata itself. `BY NAME` matches on column name so we
- don't depend on column ordering.
-
- `hive_partitioning=false` is required: the S3 keys carry year=/month=/day=
- (events) or year=/month= (persons) parts, and read_parquet would otherwise
- synthesize those as columns. `BY NAME` then fails to map them into a table
- that has no such columns ("does not have a column with name day"). The
- real data columns already live in the Parquet (ClickHouse exports with
- use_hive_partitioning=0).
-
- Idempotency is best-effort: we attempt a partition-scoped DELETE first, but
- DuckDB's Iceberg extension may not support DELETE, so a failure there is
- logged and the INSERT proceeds. Re-running a partition can therefore leave
- duplicate rows in Iceberg. DuckLake (which does support DELETE) remains the
- source of truth.
-
- For full persons exports (partition_date is None) the DELETE targets all of
- the team's rows.
-
- Returns True if the INSERT succeeded, False otherwise (never raises — the
- DuckLake backfill must not fail because of an Iceberg write).
- """
- _validate_identifier(table)
- _validate_identifier(timestamp_column)
-
- # Best-effort partition cleanup for idempotent re-runs. Use psql.Identifier
- # for the catalog/table/column the same way the INSERT below does, so the
- # whole function composes SQL one way.
- try:
- if partition_date is None:
- delete_sql = psql.SQL("DELETE FROM {}.posthog.{} WHERE team_id = {}").format(
- psql.Identifier(ICEBERG_ALIAS),
- psql.Identifier(table),
- psql.Literal(team_id),
- )
- else:
- date_str = partition_date.strftime("%Y-%m-%d")
- next_date_str = (partition_date + timedelta(days=1)).strftime("%Y-%m-%d")
- delete_sql = psql.SQL("DELETE FROM {}.posthog.{} WHERE team_id = {} AND {} >= {} AND {} < {}").format(
- psql.Identifier(ICEBERG_ALIAS),
- psql.Identifier(table),
- psql.Literal(team_id),
- psql.Identifier(timestamp_column),
- psql.Literal(date_str),
- psql.Identifier(timestamp_column),
- psql.Literal(next_date_str),
- )
- conn.execute(delete_sql)
- except Exception as exc:
- context.log.warning(
- f"Iceberg partition delete skipped for {table} team_id={team_id} "
- f"(DELETE may be unsupported) — re-run may duplicate rows: {exc}"
- )
- logger.warning(
- "duckling_iceberg_delete_skipped",
- table=table,
- team_id=team_id,
- partition_date=partition_date.strftime("%Y-%m-%d") if partition_date else None,
- error=str(exc),
- error_type=type(exc).__name__,
- )
-
- try:
- conn.execute(
- psql.SQL(
- "INSERT INTO {}.posthog.{} BY NAME SELECT * FROM read_parquet({}, hive_partitioning=false)"
- ).format(
- psql.Identifier(ICEBERG_ALIAS),
- psql.Identifier(table),
- psql.Literal(s3_path),
- )
- )
- except Exception as exc:
- context.log.warning(f"Iceberg dual-write failed for {table} team_id={team_id} from {s3_path}: {exc}")
- logger.warning(
- "duckling_iceberg_write_failed",
- table=table,
- team_id=team_id,
- s3_path=s3_path,
- error=str(exc),
- error_type=type(exc).__name__,
- )
- return False
-
- context.log.info(f"Iceberg dual-write succeeded for {table} team_id={team_id} from {s3_path}")
- logger.info("duckling_iceberg_write_success", table=table, team_id=team_id, s3_path=s3_path)
- return True
-
-
@asset(
partitions_def=duckling_events_partitions_def,
name="duckling_events_backfill",
@@ -1628,7 +1350,6 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
# 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)
conn: psycopg.Connection[Any] | None = _connect_duckgres(catalog) if should_use_duckgres else None
- iceberg_enabled = False
try:
if conn is not None:
# Delete events table if requested (dangerous - loses all data)
@@ -1644,9 +1365,6 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
bucket=catalog.bucket,
)
raise
- # Keep Iceberg in sync with the DuckLake wipe (best-effort)
- if iceberg_enabled_for_team(team_id):
- drop_iceberg_table(context, conn, "events")
# Create events table if it doesn't exist
if config.create_tables_if_missing:
@@ -1658,18 +1376,6 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
context.log.info("Validating duckling schema compatibility...")
validate_duckling_schema(context, catalog, conn)
- # Dual-write to Iceberg for allowlisted teams (best-effort, non-fatal)
- if iceberg_enabled_for_team(team_id):
- context.log.info(f"Iceberg dual-write enabled for team_id={team_id}; ensuring Iceberg events table...")
- iceberg_enabled = ensure_iceberg_table_exists(
- context,
- conn,
- "events",
- EVENTS_TABLE_DDL,
- team_id=team_id,
- partition_expr=ICEBERG_EVENTS_PARTITION_EXPR,
- )
-
# Prepare ClickHouse settings
merged_settings = DEFAULT_CLICKHOUSE_SETTINGS.copy()
merged_settings.update(settings_with_log_comment(context))
@@ -1684,7 +1390,6 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
# Process each date in the partition
total_exported = 0
total_registered = 0
- total_iceberg = 0
s3_paths: list[str] = []
for partition_date in dates:
@@ -1720,11 +1425,6 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
s3_paths.append(s3_path)
if conn is not None and register_file_with_duckling(context, catalog, s3_path, config, conn):
total_registered += 1
- if iceberg_enabled and conn is not None:
- if write_partition_to_iceberg(
- context, conn, "events", s3_path, team_id, "timestamp", partition_date
- ):
- total_iceberg += 1
context.add_output_metadata(
{
@@ -1733,7 +1433,6 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac
"dates_processed": len(dates),
"files_exported": total_exported,
"files_registered": total_registered,
- "files_iceberg_written": total_iceberg,
"bucket": catalog.bucket,
}
)
@@ -1814,7 +1513,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
# 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)
conn: psycopg.Connection[Any] | None = _connect_duckgres(catalog) if should_use_duckgres else None
- iceberg_enabled = False
try:
if conn is not None:
# Delete persons table if requested (dangerous - loses all data)
@@ -1830,9 +1528,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
bucket=catalog.bucket,
)
raise
- # Keep Iceberg in sync with the DuckLake wipe (best-effort)
- if iceberg_enabled_for_team(team_id):
- drop_iceberg_table(context, conn, "persons")
# Create persons table if it doesn't exist
if config.create_tables_if_missing:
@@ -1843,18 +1538,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
context.log.info("Validating duckling persons schema compatibility...")
validate_duckling_persons_schema(context, catalog, conn)
- # Dual-write to Iceberg for allowlisted teams (best-effort, non-fatal)
- if iceberg_enabled_for_team(team_id):
- context.log.info(f"Iceberg dual-write enabled for team_id={team_id}; ensuring Iceberg persons table...")
- iceberg_enabled = ensure_iceberg_table_exists(
- context,
- conn,
- "persons",
- ICEBERG_PERSONS_TABLE_DDL,
- team_id=team_id,
- partition_expr=ICEBERG_PERSONS_PARTITION_EXPR,
- )
-
merged_settings = DEFAULT_CLICKHOUSE_SETTINGS.copy()
merged_settings.update(settings_with_log_comment(context))
if config.clickhouse_settings:
@@ -1893,14 +1576,9 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
files_exported = 1 if s3_path else 0
files_registered = 0
- files_iceberg_written = 0
if s3_path and conn is not None:
if register_persons_file_with_duckling(context, catalog, s3_path, config, conn):
files_registered = 1
- if iceberg_enabled and write_partition_to_iceberg(
- context, conn, "persons", s3_path, team_id, "_timestamp", None
- ):
- files_iceberg_written = 1
context.add_output_metadata(
{
@@ -1909,7 +1587,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
"export_mode": "full",
"files_exported": files_exported,
"files_registered": files_registered,
- "files_iceberg_written": files_iceberg_written,
"bucket": catalog.bucket,
}
)
@@ -1929,7 +1606,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
# DAILY EXPORT MODE - process each date in the partition
total_exported = 0
total_registered = 0
- total_iceberg = 0
for partition_date in dates:
date_str = partition_date.strftime("%Y-%m-%d")
@@ -1964,11 +1640,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
context, catalog, s3_path, config, conn
):
total_registered += 1
- if iceberg_enabled and conn is not None:
- if write_partition_to_iceberg(
- context, conn, "persons", s3_path, team_id, "_timestamp", partition_date
- ):
- total_iceberg += 1
context.add_output_metadata(
{
@@ -1978,7 +1649,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
"dates_processed": len(dates),
"files_exported": total_exported,
"files_registered": total_registered,
- "files_iceberg_written": total_iceberg,
"bucket": catalog.bucket,
}
)
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.py
index 7aa4dd2a7141..f91dba30410a 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -16,28 +16,19 @@ from posthog.dags.events_backfill_to_duckling import (
EVENTS_TABLE_DDL,
EXPECTED_DUCKLAKE_COLUMNS,
EXPECTED_DUCKLAKE_PERSONS_COLUMNS,
- ICEBERG_BACKFILL_TEAM_IDS,
- ICEBERG_EVENTS_PARTITION_EXPR,
- ICEBERG_PERSONS_PARTITION_EXPR,
- ICEBERG_PERSONS_TABLE_DDL,
PERSONS_COLUMNS,
PERSONS_CONCURRENCY_TAG,
PERSONS_TABLE_DDL,
_get_cluster,
- _set_iceberg_table_partitioning,
_set_table_partitioning,
_validate_identifier,
- drop_iceberg_table,
duckling_events_full_backfill_sensor,
- ensure_iceberg_table_exists,
get_months_in_range,
get_s3_url_for_clickhouse,
- iceberg_enabled_for_team,
is_full_export_partition,
parse_partition_key,
parse_partition_key_dates,
table_exists,
- write_partition_to_iceberg,
)
@@ -202,129 +193,6 @@ class TestPersonsDDL:
conn.close()
-class TestIcebergDualWrite:
- @parameterized.expand([(2, True), (1, False), (12345, False), (0, False)])
- def test_iceberg_enabled_for_team(self, team_id, expected):
- assert iceberg_enabled_for_team(team_id) is expected
-
- def test_iceberg_backfill_team_ids_is_dogfood_only(self):
- assert ICEBERG_BACKFILL_TEAM_IDS == {2}
-
- def test_iceberg_persons_ddl_is_valid_sql_with_signed_version(self):
- conn = duckdb.connect()
- conn.execute("CREATE SCHEMA IF NOT EXISTS memory.posthog")
- conn.execute(ICEBERG_PERSONS_TABLE_DDL.format(catalog="memory"))
-
- result = conn.execute("DESCRIBE memory.posthog.persons").fetchall()
- column_names = {row[0] for row in result}
- types_by_name = {row[0]: row[1] for row in result}
-
- assert column_names == EXPECTED_DUCKLAKE_PERSONS_COLUMNS
- # Iceberg has no unsigned types — person_version must be signed BIGINT, not UBIGINT.
- assert types_by_name["person_version"] == "BIGINT"
- conn.close()
-
- def test_iceberg_persons_ddl_is_idempotent(self):
- conn = duckdb.connect()
- conn.execute("CREATE SCHEMA IF NOT EXISTS memory.posthog")
- ddl = ICEBERG_PERSONS_TABLE_DDL.format(catalog="memory")
- conn.execute(ddl)
- conn.execute(ddl)
- conn.close()
-
- def test_ensure_iceberg_table_returns_false_when_catalog_unavailable(self):
- # When the iceberg catalog isn't attached, CREATE SCHEMA raises — the
- # helper must swallow it and disable Iceberg for the run, not fail.
- conn = MagicMock()
- conn.execute.side_effect = Exception("Catalog with name iceberg does not exist")
- assert ensure_iceberg_table_exists(MagicMock(), conn, "events", EVENTS_TABLE_DDL) is False
-
- def test_ensure_iceberg_table_returns_true_on_success(self):
- conn = MagicMock()
- assert ensure_iceberg_table_exists(MagicMock(), conn, "events", EVENTS_TABLE_DDL) is True
-
- def test_ensure_iceberg_table_unpartitioned_without_expr(self):
- conn = MagicMock()
- ensure_iceberg_table_exists(MagicMock(), conn, "events", EVENTS_TABLE_DDL)
- executed = " ".join(str(c.args[0]) for c in conn.execute.call_args_list)
- assert "PARTITIONED BY" not in executed
-
- def test_ensure_iceberg_table_appends_partition_clause(self):
- conn = MagicMock()
- assert (
- ensure_iceberg_table_exists(
- MagicMock(), conn, "events", EVENTS_TABLE_DDL, partition_expr=ICEBERG_EVENTS_PARTITION_EXPR
- )
- is True
- )
- executed = " ".join(str(c.args[0]) for c in conn.execute.call_args_list)
- # Fresh tables are partitioned in the CREATE; existing tables are evolved via ALTER.
- assert f"PARTITIONED BY ({ICEBERG_EVENTS_PARTITION_EXPR})" in executed
- assert "ALTER TABLE" in executed and "SET PARTITIONED BY" in executed
-
- def test_iceberg_partition_exprs_are_single_temporal_transform(self):
- # Lakekeeper rejects multiple temporal transforms on one source column as
- # redundant, so each spec must be a single day()/month() transform — not
- # the multi-level year/month/day spec DuckLake uses.
- assert ICEBERG_EVENTS_PARTITION_EXPR == "day(timestamp)"
- assert ICEBERG_PERSONS_PARTITION_EXPR == "month(_timestamp)"
- for expr in (ICEBERG_EVENTS_PARTITION_EXPR, ICEBERG_PERSONS_PARTITION_EXPR):
- assert "," not in expr
-
- def test_set_iceberg_partitioning_treats_redundant_as_success(self):
- # Lakekeeper reports re-declaring an identical spec as "redundant"; that
- # means the table is already partitioned the way we want — not an error.
- conn = MagicMock()
- conn.execute.side_effect = Exception("Cannot add redundant partition with source id 2 and transform `time`")
- _set_iceberg_table_partitioning(MagicMock(), conn, "events", "day(timestamp)") # must not raise
-
- def test_set_iceberg_partitioning_is_non_fatal(self):
- conn = MagicMock()
- conn.execute.side_effect = Exception("some other partitioning failure")
- _set_iceberg_table_partitioning(MagicMock(), conn, "events", "day(timestamp)") # must not raise
-
- def test_set_iceberg_partitioning_rejects_invalid_table(self):
- with pytest.raises(ValueError) as exc_info:
- _set_iceberg_table_partitioning(MagicMock(), MagicMock(), "events; DROP", "day(timestamp)")
- assert "Invalid SQL identifier" in str(exc_info.value)
-
- def test_write_partition_rejects_invalid_table(self):
- with pytest.raises(ValueError) as exc_info:
- write_partition_to_iceberg(
- MagicMock(), MagicMock(), "events; DROP TABLE", "s3://b/f.parquet", 2, "timestamp", None
- )
- assert "Invalid SQL identifier" in str(exc_info.value)
-
- @parameterized.expand(
- [
- ("daily_partition", datetime(2024, 1, 15)),
- ("full_export_no_date", None),
- ]
- )
- def test_write_partition_is_non_fatal_on_insert_failure(self, _name, partition_date):
- # A failed Iceberg INSERT must never bubble up — DuckLake is the source
- # of truth and its backfill must complete regardless. Covers both the
- # daily partition-scoped DELETE and the full-export delete-by-team path.
- conn = MagicMock()
- conn.execute.side_effect = Exception("iceberg insert blew up")
- result = write_partition_to_iceberg(
- MagicMock(), conn, "events", "s3://b/f.parquet", 2, "timestamp", partition_date
- )
- assert result is False
-
- def test_drop_iceberg_table_rejects_invalid_table(self):
- with pytest.raises(ValueError) as exc_info:
- drop_iceberg_table(MagicMock(), MagicMock(), "events; DROP")
- assert "Invalid SQL identifier" in str(exc_info.value)
-
- def test_drop_iceberg_table_is_non_fatal(self):
- # delete_tables wipes DuckLake; the Iceberg drop is best-effort and must
- # not raise even when the catalog isn't attached for this org.
- conn = MagicMock()
- conn.execute.side_effect = Exception("Catalog with name iceberg does not exist")
- drop_iceberg_table(MagicMock(), conn, "events") # must not raise
-
-
class TestParsePartitionKeyDates:
@patch("posthog.dags.events_backfill_to_duckling.timezone")
def test_daily_format_returns_single_date(self, mock_timezone):
@@ -847,69 +715,6 @@ class TestDuckLakeAddDataFilesPartitioning:
)
-class TestIcebergInsertByNameHivePartitioning:
- """Regression tests for the Iceberg dual-write INSERT ... BY NAME.
-
- read_parquet() auto-detects the Hive year=/month=/day= keys in the S3 path
- and synthesizes year/month/day columns. INSERT ... BY NAME then tries to map
- those into the events table, which has no such columns, producing a binder
- error. Disabling hive_partitioning keeps read_parquet to the real data
- columns. These reuse TestDuckLakeAddDataFilesPartitioning's catalog fixture.
- """
-
- ducklake_env = TestDuckLakeAddDataFilesPartitioning.ducklake_env
-
- def _hive_partitioned_parquet(self, parquet_dir):
- dest = os.path.join(parquet_dir, "2", "year=2026", "month=03", "day=30")
- os.makedirs(dest, exist_ok=True)
- path = os.path.join(dest, "run.parquet")
- os.link(os.path.join(parquet_dir, "events.parquet"), path)
- return path
-
- def test_insert_by_name_default_hive_partitioning_fails(self, ducklake_env):
- # Reproduces the production error: BY NAME can't map the inferred day column.
- conn, parquet_dir = ducklake_env
- path = self._hive_partitioned_parquet(parquet_dir)
- with pytest.raises(duckdb.BinderException, match='column with name "day"'):
- conn.execute(f"INSERT INTO test_lake.posthog.events BY NAME SELECT * FROM read_parquet('{path}')")
-
- def test_insert_by_name_hive_partitioning_false_succeeds(self, ducklake_env):
- conn, parquet_dir = ducklake_env
- path = self._hive_partitioned_parquet(parquet_dir)
- conn.execute(
- f"INSERT INTO test_lake.posthog.events BY NAME "
- f"SELECT * FROM read_parquet('{path}', hive_partitioning=false)"
- )
- result = conn.execute("SELECT count(*) FROM test_lake.posthog.events").fetchone()
- assert result[0] == 1
-
- def test_write_partition_emits_hive_partitioning_false(self):
- # Guards the production code path itself (the tests above only exercise
- # hand-written SQL): write_partition_to_iceberg must emit a read_parquet
- # that disables Hive inference, or BY NAME breaks on the path's
- # year/month/day keys again.
- executed: list[str] = []
- conn = MagicMock()
- conn.execute.side_effect = lambda stmt, *a, **k: executed.append(
- stmt.as_string(None) if hasattr(stmt, "as_string") else str(stmt)
- )
-
- result = write_partition_to_iceberg(
- MagicMock(),
- conn,
- "events",
- "s3://bucket/backfill/events/2/year=2026/month=05/day=31/run.parquet",
- 2,
- "timestamp",
- datetime(2026, 5, 31),
- )
-
- assert result is True
- insert_sql = next(s for s in executed if "read_parquet" in s)
- assert "BY NAME" in insert_sql
- assert "hive_partitioning=false" in insert_sql
-
-
class TestDucklingConcurrencyTags:
# The combined events+persons cap is enforced on the shared key in the charts
# Dagster deployment settings. If either backfill drops the shared tag, the