: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
fix(duckling): split events/persons backfill into right-sized parquet files (#64983)
James Greenhillc7c17a7123c3
diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.mdindex 639f79a84d8d..279f1886e08e 100644--- a/posthog/dags/README_DUCKLINGS.md+++ b/posthog/dags/README_DUCKLINGS.md@@ -137,7 +137,7 @@ The job logs warnings if the duckling table schema differs from expected columns### Orphaned files in S3-Failed runs may leave orphaned Parquet files in S3. These files are harmless - each run writes to a unique path based on the run ID, and the `cleanup_existing_partition_data` option ensures DuckLake data is cleaned up via DELETE before re-processing. Do NOT delete S3 files that may have been registered with DuckLake, as this causes catalog corruption.+Failed or re-run partitions may leave orphaned Parquet files in S3. These files are harmless - each run writes its files under a unique `{run_id}_` prefix, registration globs only that run's files, and the `cleanup_existing_partition_data` option clears the partition's DuckLake rows via DELETE before re-registering. A re-run therefore registers exactly its own fan-out (no duplicates, none missed); a prior run's physical files are simply no longer in the catalog. Do NOT delete S3 files that may have been registered with DuckLake, as this causes catalog corruption.### Table creation race condition@@ -152,7 +152,17 @@ If multiple partitions for the same team run concurrently, they may race to crea## S3 Path Structure+Each export fans a partition out across many right-sized Parquet files (one per+ClickHouse `PARTITION BY` bucket) instead of one giant per-day object, so reads get+parallelism and per-file scans stay cheap. The fan-out is **computed per export** from+a cheap `count()` estimate — `ceil(row_count / target_rows_per_file)`, clamped to+`[1, max_s3_file_fanout]` — so a tens-of-millions-of-rows team-day spreads across many+~GB-scale files while a tiny team-day stays a single file. Both knobs are tunable per+run via `DucklingBackfillConfig` (`target_rows_per_file`, `max_s3_file_fanout`). The+`{_partition_id}` is the bucket id (`0 … fanout-1`); registration globs+`{run_id}_*.parquet` to enumerate every file a run produced.+```text-s3://{bucket}/backfill/events/{team_id}/{year}/{month}/{day}/{run_id}.parquet-s3://{bucket}/backfill/persons/{team_id}/{year}/{month}/{day}/{run_id}.parquet+s3://{bucket}/backfill/events/{team_id}/year={year}/month={month}/day={day}/{run_id}_{_partition_id}.parquet+s3://{bucket}/backfill/persons/{team_id}/year={year}/month={month}/{run_id}_{_partition_id}.parquet```diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex e789a5591070..c3440d2d7585 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -31,6 +31,7 @@ Partition Strategy:import osimport json+import mathimport timeimport calendarimport dataclasses@@ -257,12 +258,23 @@ def _connect_duckgres(target: DucklingTarget) -> psycopg.Connection[Any]:target.team_id,organization_id=target.organization_id,)- return psycopg.connect(+ conn = psycopg.connect(conninfo,autocommit=True,connect_timeout=DUCKGRES_CONNECT_TIMEOUT,options=_duckgres_backfill_options(),)+ # Pin the session to UTC. The ranged partition DELETEs compare the TIMESTAMPTZ catalog+ # columns against bare 'YYYY-MM-DD' strings, a cast that uses the session TimeZone; with+ # ICU loaded that defaults to system-local, which would shift the half-open [day,+ # next_day) window off the UTC day the ClickHouse export wrote and strand/over-delete+ # rows at day boundaries. Best-effort: never fail a connection over this — a server that+ # doesn't expose the setting just keeps its prior (UTC-on-our-containers) behavior.+ try:+ conn.execute("SET TimeZone='UTC'")+ except Exception as exc:+ logger.warning("duckling_set_timezone_failed", error=str(exc), error_type=type(exc).__name__)+ return conn_CONNECTION_DROPPED_SQLSTATES = {@@ -473,6 +485,47 @@ EXPECTED_DUCKLAKE_EVENTS_COLUMNS = {BACKFILL_EVENTS_S3_PREFIX = "backfill/events"BACKFILL_PERSONS_S3_PREFIX = "backfill/persons"+# Fan a single export out across many right-sized Parquet files instead of one+# monster object. ClickHouse PARTITION BY with a {_partition_id} placeholder in the+# S3 path emits one file per bucket, so an export becomes ~fanout files. The+# year/month/day Hive layout (and DuckLake's matching SET PARTITIONED BY) is+# unchanged — only the number of files inside each day= directory grows, which is+# what gives reads parallelism and keeps per-file scans cheap. Bucketing on a hash+# of distinct_id spreads rows evenly and keeps each file independently scannable.+#+# The fan-out is computed PER EXPORT from a cheap row-count estimate, not fixed:+# team-day volumes span many orders of magnitude (a top team's day is tens of+# millions of rows; a small team's is a handful), so one constant would either+# leave huge days as monster files or shatter tiny days into a swarm of near-empty+# objects. We target ~TARGET_ROWS_PER_FILE rows per file and clamp to+# [1, MAX_S3_FILE_FANOUT]. Row count (not bytes) is the signal because it's the+# dominant driver of file size and the only one ClickHouse estimates cheaply from+# the primary key without scanning the wide columns; wide-row teams can be tuned via+# the per-run config. At ~4KB/event-row, 1M rows lands a file near ~4GB.+#+# MAX_S3_FILE_FANOUT is bounded by WRITER MEMORY, not file count: ClickHouse's+# PartitionedSink keeps one Parquet writer open per active bucket for the whole+# INSERT (a footer is written only at stream close), and a uniform hash key activates+# all N buckets at once. Each writer buffers at most one in-progress row group, so+# peak ≈ N × output_format_parquet_row_group_size_bytes (× parallel-encoding+# overhead). With that byte cap pinned to 128 MiB (see PARQUET_WRITER_SETTINGS),+# 256 × 128 MiB ≈ 32 GiB stays comfortably under the 100 GiB max_memory_usage ceiling.+# N may exceed ClickHouse's max_partitions_per_insert_block (default 100) safely —+# that limit gates MergeTree part creation, not the s3() PartitionedSink.+TARGET_ROWS_PER_FILE = 1_000_000+MAX_S3_FILE_FANOUT = 256++# Parquet writer settings shared by every export. The byte cap is the load-bearing one:+# it bounds each open partition writer's in-progress row group, so aggregate writer+# memory scales as fan-out × this value (see MAX_S3_FILE_FANOUT). For wide event rows it+# is also the binding row-group flush trigger (the row pin below only binds for the+# narrower persons rows, which flush on rows first). 128 MiB row groups stay large enough+# for efficient DuckLake/DuckDB reads while keeping high-fan-out writes within budget.+PARQUET_WRITER_SETTINGS: dict[str, Any] = {+ "output_format_parquet_row_group_size_bytes": 128 * 1024 * 1024, # 128 MiB — bounds per-partition writer memory+ "output_format_parquet_row_group_size": 250_000, # secondary cap; binds for narrow persons rows+}+# Shared concurrency key across events + persons backfills. Each duckling# connection spins up a duckgres worker, and the per-org worker pool is capped# (maxWorkers in the duckgres chart) and shared with product queries — so the@@ -590,6 +643,14 @@ class DucklingBackfillConfig(Config):create_tables_if_missing: bool = Truedelete_tables: bool = False # Danger: drops and recreates tables, losing all datadry_run: bool = False+ # Dynamic S3 fan-out: each export is split into ~ceil(row_count / target_rows_per_file)+ # Parquet files, clamped to [1, max_s3_file_fanout]. Huge team-days produce many+ # right-sized files; tiny ones stay a single file. The fan-out also drives writer+ # memory (peak ≈ fan-out × per-partition row-group buffer; see PARQUET_WRITER_SETTINGS),+ # so for teams with unusually wide rows, lowering target_rows_per_file both keeps files+ # in range AND raises fan-out — pair it with a lower max_s3_file_fanout if memory is tight.+ target_rows_per_file: int = TARGET_ROWS_PER_FILE+ max_s3_file_fanout: int = MAX_S3_FILE_FANOUTdef parse_partition_key(key: str) -> tuple[int, str]:@@ -1047,6 +1108,42 @@ def validate_duckling_persons_schema()+def _compute_fanout(row_count: int, target_rows_per_file: int, max_fanout: int) -> int:+ """Pick how many Parquet files to split an export into.++ Sizes the fan-out to the export's actual volume: one file per ~target_rows_per_file+ rows, clamped to [1, max_fanout]. A near-empty export collapses to a single file; a+ tens-of-millions-of-rows day spreads across many right-sized files.++ Pure arithmetic — no ClickHouse I/O, so no retry decorator (the count that feeds it+ is retried in _estimate_export_row_count).++ Fails closed to a single file on an empty export or a non-positive config (these are+ user-tunable, so a 0 target must not divide-by-zero the backfill).+ """+ if row_count <= 0 or target_rows_per_file <= 0 or max_fanout <= 0:+ return 1+ return max(1, min(math.ceil(row_count / target_rows_per_file), max_fanout))+++@retry(+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential(multiplier=1, min=4, max=60),+ retry=retry_if_exception_type((ClickHouseError, OSError, TimeoutError)),+ reraise=True,+)+def _estimate_export_row_count(client: Client, count_sql: str, settings: dict[str, Any]) -> int:+ """Cheap row-count estimate used to size the export fan-out.++ `count()` over a team-day reads only the primary-key marks (team_id is the leading+ key), so it does not scan the wide event/person columns the export itself streams.+ Retried like the export itself — it's the only other ClickHouse call on the path, and+ a transient failure here shouldn't fail the whole partition before the INSERT runs.+ """+ result = client.execute(count_sql, settings=settings)+ return int(result[0][0]) if result and result[0] else 0++@retry(stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),wait=wait_exponential(multiplier=1, min=4, max=60),@@ -1221,42 +1318,61 @@ def export_events_to_duckling_s3() -> str | None:"""Export events for a team/date to the duckling's S3 bucket.+ The day is fanned out across a volume-sized number of Parquet files via ClickHouse+ PARTITION BY rather than one giant per-day object (see _compute_fanout).+ClickHouse uses its EC2 instance role for S3 access. The duckling bucket policyexplicitly allows the ClickHouse EC2 role, so no explicit credentials are needed.Returns:- S3 path that was written, or None if dry_run.+ S3 glob matching every file this run produced for the day, or None if dry_run."""year = date.strftime("%Y")month = date.strftime("%m")day = date.strftime("%d")date_str = date.strftime("%Y-%m-%d")- # Path without s3:// scheme for the HTTPS URL- path_without_scheme = f"{BACKFILL_EVENTS_S3_PREFIX}/{team_id}/year={year}/month={month}/day={day}/{run_id}.parquet"+ day_dir = f"{BACKFILL_EVENTS_S3_PREFIX}/{team_id}/year={year}/month={month}/day={day}"++ # {_partition_id} is substituted by ClickHouse per PARTITION BY bucket, so one+ # INSERT emits {run_id}_0.parquet … {run_id}_{N-1}.parquet. The run_id prefix+ # keeps each run's files isolated: a re-run writes a fresh set, and registration+ # globs only this run's files (see register_files_with_duckling), so a replay can+ # never re-register a prior run's objects. Prior runs' physical files are left in+ # place — they're orphaned from the catalog by the DELETE-before-register step and+ # are harmless; deleting registered S3 files would corrupt the catalog.+ partition_path = f"{day_dir}/{run_id}_{{_partition_id}}.parquet"+ file_glob = f"{day_dir}/{run_id}_*.parquet"# ClickHouse needs HTTPS URL format for cross-account S3 access- s3_url = get_s3_url_for_clickhouse(target.bucket, target.bucket_region, path_without_scheme)+ s3_url = get_s3_url_for_clickhouse(target.bucket, target.bucket_region, partition_path)- # S3 path with scheme for DuckLake registration- s3_path = f"s3://{target.bucket}/{path_without_scheme}"+ # S3 glob with scheme that registration enumerates to find every produced file+ s3_glob = f"s3://{target.bucket}/{file_glob}"where_clause = f"team_id = {team_id} AND toDate(timestamp) = '{date_str}'"- # Event rows are wide (large properties/person_properties JSON), and the Parquet- # writer buffers a full row group per encoding thread before flushing — this is where- # the export OOMs (ParquetBlockOutputFormat in the stack trace), not the scan. Peak- # memory is ~ row_group_size * bytes_per_row * threads, so the 1M-row default builds- # multi-GB groups that blow the limit under parallel encoding. 250k rows lands each- # group in Parquet's recommended byte range (~hundreds of MB) while keeping read- # efficiency near the default; the raised ceiling is headroom on top.+ # Event rows are wide (large properties/person_properties JSON). With PARTITION BY,+ # writer memory is dominated by the per-partition row-group buffers (one open writer+ # per active bucket), so we cap the row group by bytes via PARQUET_WRITER_SETTINGS;+ # the 100 GiB ceiling is headroom on top. See the PARQUET_WRITER_SETTINGS /+ # MAX_S3_FILE_FANOUT comments for the fan-out × buffer memory model.export_settings = settings.copy()- export_settings.update(- {- "max_memory_usage": 100 * 1024 * 1024 * 1024, # 100GB, matching the full-persons export- "output_format_parquet_row_group_size": 250_000, # down from the 1M default- }- )+ export_settings.update(PARQUET_WRITER_SETTINGS)+ export_settings["max_memory_usage"] = 100 * 1024 * 1024 * 1024 # 100GB, matching the full-persons export++ info = f"team_id={team_id}, date={date_str}"++ if config.dry_run:+ context.log.info(+ f"[DRY RUN] Would estimate row count for {info} and fan the export across up to "+ f"{config.max_s3_file_fanout} files (~{config.target_rows_per_file} rows/file) to {s3_glob}"+ )+ return None++ # Size the fan-out to this team-day's actual volume.+ row_count = _estimate_export_row_count(client, f"SELECT count() FROM events WHERE {where_clause}", settings)+ fanout = _compute_fanout(row_count, config.target_rows_per_file, config.max_s3_file_fanout)# ClickHouse uses its EC2 instance role - no credentials needed# The duckling bucket policy allows the ClickHouse EC2 role@@ -1265,6 +1381,7 @@ def export_events_to_duckling_s3('{s3_url}','Parquet')+ PARTITION BY toString(cityHash64(distinct_id) % {fanout})SELECT{EVENTS_COLUMNS}FROM events@@ -1272,89 +1389,116 @@ def export_events_to_duckling_s3(SETTINGS s3_truncate_on_insert=1, use_hive_partitioning=0"""- info = f"team_id={team_id}, date={date_str}"-- if config.dry_run:- context.log.info(f"[DRY RUN] Would export with SQL: {export_sql[:800]}...")- return None-- context.log.info(f"Exporting events for {info} to {s3_path}")+ context.log.info(f"Exporting events for {info} ({row_count} rows → {fanout} file(s)) to {s3_glob}")logger.info("duckling_export_start",team_id=team_id,date=date_str,- s3_path=s3_path,+ s3_glob=s3_glob,+ row_count=row_count,+ fanout=fanout,)try:_execute_export_with_retry(client, export_sql, export_settings, info)context.log.info(f"Successfully exported events for {info}")logger.info("duckling_export_success", team_id=team_id, date=date_str)- return s3_path+ return s3_globexcept Exception:context.log.exception(f"Failed to export events for {info} after {MAX_RETRY_ATTEMPTS} attempts")logger.exception("duckling_export_failed", team_id=team_id, date=date_str)raise-def register_file_with_duckling(+def _glob_run_files(conn: psycopg.Connection[Any], s3_glob: str) -> list[str]:+ """Enumerate the Parquet files a fanned-out export produced for one run.++ The export writes a variable (and possibly empty) number of files — one per+ non-empty PARTITION BY bucket — so registration discovers them by globbing the+ run's output rather than predicting names. The glob is run-scoped, so it never+ returns a prior run's objects.+ """+ with conn.cursor() as cur:+ cur.execute("SELECT file FROM glob(%s) ORDER BY file", (s3_glob,))+ return [row[0] for row in cur.fetchall()]+++def register_files_with_duckling(context: AssetExecutionContext,target: DucklingTarget,- s3_path: str,+ s3_glob: str,config: DucklingBackfillConfig,conn: psycopg.Connection[Any],-) -> bool:- """Register an exported Parquet file with the duckling's DuckLake catalog.+) -> int:+ """Register every Parquet file a fanned-out events export produced.- Cross-account S3 access is configured server-side on the duckling's duckgres- via IRSA, so the DAG only needs a pgwire connection.+ A team-day export now emits many files, so this globs the run's output and+ registers each one exactly once. Cross-account S3 access is configured+ server-side on the duckling's duckgres via IRSA, so the DAG only needs a pgwire+ connection.DuckLake transaction conflicts are retried server-side by duckgres. Connectionretries live in the caller — this helper operates on a connection it doesn't own.+ Because ducklake_add_data_files APPENDS with no dedup-by-path, the caller must+ have cleared the day's existing rows (DELETE) before calling, so a replay can't+ double-register.Args:context: Dagster asset execution context.target: The resolved duckling target (duckgres connection identity + S3 bucket).- s3_path: S3 path of the Parquet file to register.+ s3_glob: S3 glob matching every file this run produced for the day.config: Job configuration.conn: psycopg connection to the org's duckgres server.Returns:- True if registration succeeded, False otherwise.+ Number of files registered (0 if skipped, dry_run, or the day was empty)."""if config.skip_ducklake_registration:context.log.info("Skipping DuckLake registration (skip_ducklake_registration=True)")- return False+ return 0if config.dry_run:- context.log.info(f"[DRY RUN] Would register {s3_path} with DuckLake (org {target.organization_id})")- return False+ context.log.info(+ f"[DRY RUN] Would register files matching {s3_glob} with DuckLake (org {target.organization_id})"+ )+ return 0alias = DUCKLAKE_ALIAS- context.log.info(f"Registering file with DuckLake: {s3_path}")try:- conn.execute(- psql.SQL("CALL ducklake_add_data_files({}, 'events', {}, schema => 'posthog')").format(- psql.Literal(alias),- psql.Literal(s3_path),+ files = _glob_run_files(conn, s3_glob)+ if not files:+ context.log.info(f"No files produced for {s3_glob}, nothing to register")+ return 0++ context.log.info(f"Registering {len(files)} file(s) with DuckLake from {s3_glob}")+ for s3_path in files:+ conn.execute(+ psql.SQL("CALL ducklake_add_data_files({}, 'events', {}, schema => 'posthog')").format(+ psql.Literal(alias),+ psql.Literal(s3_path),+ ))- )except Exception as exc:# Connection drops are retried by the caller (_DuckgresSession.run); only# log loudly for genuine failures so a recovered drop doesn't false-alert.if not _connection_dropped(exc):- context.log.exception(f"Failed to register file {s3_path}")+ context.log.exception(f"Failed to register files matching {s3_glob}")logger.exception("duckling_file_registration_failed",- s3_path=s3_path,+ s3_glob=s3_glob,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=target.team_id)- return True+ context.log.info(f"Successfully registered {len(files)} file(s) from {s3_glob}")+ logger.info(+ "duckling_files_registered",+ s3_glob=s3_glob,+ file_count=len(files),+ team_id=target.team_id,+ )+ return len(files)def export_persons_to_duckling_s3(@@ -1377,15 +1521,43 @@ def export_persons_to_duckling_s3(latest version of each person and distinct_id mapping.Returns:- S3 path that was written, or None if dry_run.+ S3 glob matching every file this run produced, or None if dry_run."""year = date.strftime("%Y")month = date.strftime("%m")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(target.bucket, target.bucket_region, path_without_scheme)- s3_path = f"s3://{target.bucket}/{path_without_scheme}"+ period_dir = f"{BACKFILL_PERSONS_S3_PREFIX}/{team_id}/year={year}/month={month}"+ # Fanned out by PARTITION BY into {run_id}_*.parquet — see export_events_to_duckling_s3+ # for why the run_id prefix keeps replays from re-registering prior files.+ partition_path = f"{period_dir}/{run_id}_{{_partition_id}}.parquet"+ file_glob = f"{period_dir}/{run_id}_*.parquet"+ s3_url = get_s3_url_for_clickhouse(target.bucket, target.bucket_region, partition_path)+ s3_glob = f"s3://{target.bucket}/{file_glob}"++ info = f"team_id={team_id}, date={date_str}"++ if config.dry_run:+ context.log.info(+ f"[DRY RUN] Would estimate row count for persons {info} and fan the export across up to "+ f"{config.max_s3_file_fanout} files (~{config.target_rows_per_file} rows/file) to {s3_glob}"+ )+ return None++ # Size the fan-out from a cheap proxy: persons modified that day (team_id is the+ # leading primary key). Output rows are these persons' distinct_ids, so this under-counts+ # by the distinct-ids-per-person ratio (~1-2). We can't use the accurate+ # person_distinct_id2 count the full export uses: the daily filter is on person._timestamp+ # (which day a person changed), and person_distinct_id2 has no equivalent per-day column —+ # counting the actual output would mean running the FINAL'd JOIN, i.e. the export itself.+ # The under-count only nudges files slightly above target; persons days are small and the+ # max_s3_file_fanout clamp binds first.+ row_count = _estimate_export_row_count(+ client,+ f"SELECT count() FROM person WHERE team_id = {team_id} AND toDate(_timestamp) = '{date_str}' AND is_deleted = 0",+ settings,+ )+ fanout = _compute_fanout(row_count, config.target_rows_per_file, config.max_s3_file_fanout)# Join person with person_distinct_id2 to get distinct_ids# Use FINAL to handle ReplacingMergeTree deduplication@@ -1395,6 +1567,7 @@ def export_persons_to_duckling_s3('{s3_url}','Parquet')+ PARTITION BY toString(cityHash64(pd.distinct_id) % {fanout})SELECT{PERSONS_COLUMNS}FROM person AS p FINAL@@ -1407,25 +1580,25 @@ def export_persons_to_duckling_s3(SETTINGS s3_truncate_on_insert=1, use_hive_partitioning=0"""- info = f"team_id={team_id}, date={date_str}"-- if config.dry_run:- context.log.info(f"[DRY RUN] Would export persons with SQL: {export_sql[:800]}...")- return None+ # Bound per-partition writer memory like the events export (see PARQUET_WRITER_SETTINGS).+ export_settings = settings.copy()+ export_settings.update(PARQUET_WRITER_SETTINGS)- context.log.info(f"Exporting persons for {info} to {s3_path}")+ context.log.info(f"Exporting persons for {info} ({row_count} persons → {fanout} file(s)) to {s3_glob}")logger.info("duckling_persons_export_start",team_id=team_id,date=date_str,- s3_path=s3_path,+ s3_glob=s3_glob,+ row_count=row_count,+ fanout=fanout,)try:- _execute_export_with_retry(client, export_sql, settings, info)+ _execute_export_with_retry(client, export_sql, export_settings, info)context.log.info(f"Successfully exported persons for {info}")logger.info("duckling_persons_export_success", team_id=team_id, date=date_str)- return s3_path+ return s3_globexcept Exception:context.log.exception(f"Failed to export persons for {info} after {MAX_RETRY_ATTEMPTS} attempts")logger.exception("duckling_persons_export_failed", team_id=team_id, date=date_str)@@ -1448,11 +1621,15 @@ def export_persons_full_to_duckling_s3(person_distinct_id2 to include distinct_ids.Returns:- S3 path that was written, or None if dry_run.+ S3 glob matching every file this run produced, 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(target.bucket, target.bucket_region, path_without_scheme)- s3_path = f"s3://{target.bucket}/{path_without_scheme}"+ period_dir = f"{BACKFILL_PERSONS_S3_PREFIX}/{team_id}/year=0/month=0"+ # Fanned out by PARTITION BY into {run_id}_*.parquet — see export_events_to_duckling_s3+ # for why the run_id prefix keeps replays from re-registering prior files.+ partition_path = f"{period_dir}/{run_id}_{{_partition_id}}.parquet"+ file_glob = f"{period_dir}/{run_id}_*.parquet"+ s3_url = get_s3_url_for_clickhouse(target.bucket, target.bucket_region, partition_path)+ s3_glob = f"s3://{target.bucket}/{file_glob}"# Join person with person_distinct_id2 to get distinct_ids# Use FINAL to handle ReplacingMergeTree deduplication@@ -1460,6 +1637,7 @@ def export_persons_full_to_duckling_s3(# Full exports need more memory due to FINAL + JOIN on large datasets# Also enable external sorting to spill to disk if memory is still exceededfull_export_settings = settings.copy()+ full_export_settings.update(PARQUET_WRITER_SETTINGS) # bound per-partition writer memoryfull_export_settings.update({"max_memory_usage": 100 * 1024 * 1024 * 1024, # 100GB for full exports@@ -1467,11 +1645,30 @@ def export_persons_full_to_duckling_s3(})+ info = f"team_id={team_id}, full_export"++ if config.dry_run:+ context.log.info(+ f"[DRY RUN] Would estimate row count for persons {info} and fan the export across up to "+ f"{config.max_s3_file_fanout} files (~{config.target_rows_per_file} rows/file) to {s3_glob}"+ )+ return None++ # Size the fan-out from the team's distinct-id rows (≈ output rows; team_id is the+ # leading primary key). No FINAL — a slight overcount only nudges the file count up.+ row_count = _estimate_export_row_count(+ client,+ f"SELECT count() FROM person_distinct_id2 WHERE team_id = {team_id} AND is_deleted = 0",+ settings,+ )+ fanout = _compute_fanout(row_count, config.target_rows_per_file, config.max_s3_file_fanout)+export_sql = f"""INSERT INTO FUNCTION s3('{s3_url}','Parquet')+ PARTITION BY toString(cityHash64(pd.distinct_id) % {fanout})SELECT{PERSONS_COLUMNS}FROM person AS p FINAL@@ -1483,79 +1680,90 @@ def export_persons_full_to_duckling_s3(SETTINGS s3_truncate_on_insert=1, use_hive_partitioning=0"""- info = f"team_id={team_id}, full_export"-- if config.dry_run:- context.log.info(f"[DRY RUN] Would export persons (full) with SQL: {export_sql[:800]}...")- return None-- context.log.info(f"Exporting all persons for {info} to {s3_path}")+ context.log.info(f"Exporting all persons for {info} ({row_count} distinct-ids → {fanout} file(s)) to {s3_glob}")logger.info("duckling_persons_full_export_start",team_id=team_id,- s3_path=s3_path,+ s3_glob=s3_glob,+ row_count=row_count,+ fanout=fanout,)try:_execute_export_with_retry(client, export_sql, full_export_settings, info)context.log.info(f"Successfully exported all persons for {info}")logger.info("duckling_persons_full_export_success", team_id=team_id)- return s3_path+ return s3_globexcept Exception:context.log.exception(f"Failed to export persons (full) for {info} after {MAX_RETRY_ATTEMPTS} attempts")logger.exception("duckling_persons_full_export_failed", team_id=team_id)raise-def register_persons_file_with_duckling(+def register_persons_files_with_duckling(context: AssetExecutionContext,target: DucklingTarget,- s3_path: str,+ s3_glob: str,config: DucklingBackfillConfig,conn: psycopg.Connection[Any],-) -> bool:- """Register an exported persons Parquet file with the duckling's DuckLake catalog.+) -> int:+ """Register every Parquet file a fanned-out persons export produced.++ Globs the run's output and registers each file exactly once. The caller must+ have cleared the existing rows (DELETE) first so a replay can't double-register.DuckLake transaction conflicts are retried server-side by duckgres. Connectionretries live in the caller — this helper operates on a connection it doesn't own.++ Returns:+ Number of files registered (0 if skipped, dry_run, or the export was empty)."""if config.skip_ducklake_registration:context.log.info("Skipping DuckLake registration (skip_ducklake_registration=True)")- return False+ return 0if config.dry_run:- context.log.info(f"[DRY RUN] Would register {s3_path} with DuckLake (org {target.organization_id})")- return False+ context.log.info(+ f"[DRY RUN] Would register files matching {s3_glob} with DuckLake (org {target.organization_id})"+ )+ return 0alias = DUCKLAKE_ALIAS- context.log.info(f"Registering persons file with DuckLake: {s3_path}")try:- conn.execute(- psql.SQL("CALL ducklake_add_data_files({}, 'persons', {}, schema => 'posthog')").format(- psql.Literal(alias),- psql.Literal(s3_path),+ files = _glob_run_files(conn, s3_glob)+ if not files:+ context.log.info(f"No persons files produced for {s3_glob}, nothing to register")+ return 0++ context.log.info(f"Registering {len(files)} persons file(s) with DuckLake from {s3_glob}")+ for s3_path in files:+ conn.execute(+ psql.SQL("CALL ducklake_add_data_files({}, 'persons', {}, schema => 'posthog')").format(+ psql.Literal(alias),+ psql.Literal(s3_path),+ ))- )except Exception as exc:# Connection drops are retried by the caller (_DuckgresSession.run); only# log loudly for genuine failures so a recovered drop doesn't false-alert.if not _connection_dropped(exc):- context.log.exception(f"Failed to register persons file {s3_path}")+ context.log.exception(f"Failed to register persons files matching {s3_glob}")logger.exception("duckling_persons_file_registration_failed",- s3_path=s3_path,+ s3_glob=s3_glob,team_id=target.team_id,)raise- context.log.info(f"Successfully registered persons: {s3_path}")+ context.log.info(f"Successfully registered {len(files)} persons file(s) from {s3_glob}")logger.info(- "duckling_persons_file_registered",- s3_path=s3_path,+ "duckling_persons_files_registered",+ s3_glob=s3_glob,+ file_count=len(files),team_id=target.team_id,)- return True+ return len(files)@asset(@@ -1580,7 +1788,10 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBacc. Registers the Parquet file with the duckling's DuckLake catalog (via cross-account role)"""team_id, dates = parse_partition_key_dates(context.partition_key)- run_id = context.run.run_id[:8]+ # 16 hex chars (64 bits): the file prefix that scopes each run's glob. The exactly-once+ # guarantee is the ranged DELETE, not prefix uniqueness, but a wider prefix makes a+ # same-day re-run sharing a prefix (→ globbing a prior run's orphans) effectively impossible.+ run_id = context.run.run_id[:16]context.log.info(f"Starting duckling backfill for team_id={team_id}, dates={len(dates)} day(s)")logger.info(@@ -1641,9 +1852,8 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBacworkload = Workload.OFFLINE if is_cloud() else Workload.DEFAULT# Process each date in the partition- total_exported = 0+ days_exported = 0total_registered = 0- s3_paths: list[str] = []for partition_date in dates:date_str = partition_date.strftime("%Y-%m-%d")@@ -1670,41 +1880,40 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBacsettings=merged_settings,)- s3_path = cluster.any_host_by_role(+ s3_glob = cluster.any_host_by_role(fn=do_export,workload=workload,node_role=NodeRole.DATA,).result()- # Register with DuckLake if we have a file- if s3_path:- total_exported += 1- s3_paths.append(s3_path)+ # Register every file the day's fanned-out export produced+ if s3_glob:+ days_exported += 1if session is not None:- def register_events_file(+ def register_events_files(conn: psycopg.Connection[Any],- path: str = s3_path,+ glob: str = s3_glob,date: datetime = partition_date,- ) -> bool:+ ) -> int:# Idempotent replay unit: ducklake_add_data_files APPENDS with no- # dedup-by-path, so if a prior attempt committed the registration+ # dedup-by-path, so if a prior attempt committed some registrations# but the worker died before the client saw the ack, re-clear the- # day's range first (idempotent DELETE) then re-add — the net state- # is exactly this file for the day, wherever the prior attempt died.+ # day's range first (idempotent DELETE) then re-add all of this run's+ # files — the net state is exactly this run's file set for the day,+ # wherever the prior attempt died.if config.cleanup_existing_partition_data:delete_events_partition_data(context, target, team_id, date, conn=conn)- return register_file_with_duckling(context, target, path, config, conn)+ return register_files_with_duckling(context, target, glob, config, conn)- if session.run(f"register events file {date_str}", register_events_file):- total_registered += 1+ total_registered += session.run(f"register events files {date_str}", register_events_files)context.add_output_metadata({"team_id": team_id,"partition_key": context.partition_key,"dates_processed": len(dates),- "files_exported": total_exported,+ "days_exported": days_exported,"files_registered": total_registered,"bucket": target.bucket,}@@ -1712,13 +1921,13 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBaccontext.log.info(f"Completed duckling backfill for team_id={team_id}: "- f"{total_exported}/{len(dates)} days exported, {total_registered} registered"+ f"{days_exported}/{len(dates)} days exported, {total_registered} files registered")logger.info("duckling_backfill_complete",team_id=team_id,dates_processed=len(dates),- files_exported=total_exported,+ days_exported=days_exported,files_registered=total_registered,)@@ -1753,7 +1962,10 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa"""partition_key = context.partition_keyis_full = is_full_export_partition(partition_key)- run_id = context.run.run_id[:8]+ # 16 hex chars (64 bits): the file prefix that scopes each run's glob. The exactly-once+ # guarantee is the ranged DELETE, not prefix uniqueness, but a wider prefix makes a+ # same-day re-run sharing a prefix (→ globbing a prior run's orphans) effectively impossible.+ run_id = context.run.run_id[:16]if is_full:team_id = int(partition_key)@@ -1841,52 +2053,47 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBasettings=merged_settings,)- s3_path = cluster.any_host_by_role(+ s3_glob = cluster.any_host_by_role(fn=do_full_export,workload=workload,node_role=NodeRole.DATA,).result()- files_exported = 1 if s3_path else 0files_registered = 0- if s3_path and session is not None:+ if s3_glob and session is not None:- def register_full_persons_file(conn: psycopg.Connection[Any], path: str = s3_path) -> bool:+ def register_full_persons_files(conn: psycopg.Connection[Any], glob: str = s3_glob) -> int:# Idempotent replay unit (see _DuckgresSession): re-clear all of the- # team's persons (idempotent DELETE) then re-add, so a replay after a- # committed-but-unacked registration can't double-register the file.+ # team's persons (idempotent DELETE) then re-add all of this run's files,+ # so a replay after a committed-but-unacked registration can't double-register.if config.cleanup_existing_partition_data:delete_persons_partition_data(context, target, team_id, partition_date=None, conn=conn)- return register_persons_file_with_duckling(context, target, path, config, conn)+ return register_persons_files_with_duckling(context, target, glob, config, conn)- if session.run("register persons file (full)", register_full_persons_file):- files_registered = 1+ files_registered = session.run("register persons files (full)", register_full_persons_files)context.add_output_metadata({"team_id": team_id,"partition_key": partition_key,"export_mode": "full",- "files_exported": files_exported,"files_registered": files_registered,"bucket": target.bucket,})context.log.info(- f"Completed duckling persons full backfill for team_id={team_id}: "- f"{files_exported} file exported, {files_registered} registered"+ f"Completed duckling persons full backfill for team_id={team_id}: {files_registered} files registered")logger.info("duckling_persons_backfill_complete",team_id=team_id,export_mode="full",- files_exported=files_exported,files_registered=files_registered,)else:# DAILY EXPORT MODE - process each date in the partition- total_exported = 0+ days_exported = 0total_registered = 0for partition_date in dates:@@ -1916,30 +2123,30 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBasettings=merged_settings,)- s3_path = cluster.any_host_by_role(+ s3_glob = cluster.any_host_by_role(fn=do_export,workload=workload,node_role=NodeRole.DATA,).result()- if s3_path:- total_exported += 1+ if s3_glob:+ days_exported += 1if session is not None:- def register_persons_file(+ def register_persons_files(conn: psycopg.Connection[Any],- path: str = s3_path,+ glob: str = s3_glob,date: datetime = partition_date,- ) -> bool:+ ) -> int:# Idempotent replay unit (see _DuckgresSession): re-clear the- # day's range (idempotent DELETE) then re-add, so a replay after- # a committed-but-unacked registration can't double-register.+ # day's range (idempotent DELETE) then re-add all of this run's+ # files, so a replay after a committed-but-unacked registration+ # can't double-register.if config.cleanup_existing_partition_data:delete_persons_partition_data(context, target, team_id, date, conn=conn)- return register_persons_file_with_duckling(context, target, path, config, conn)+ return register_persons_files_with_duckling(context, target, glob, config, conn)- if session.run(f"register persons file {date_str}", register_persons_file):- total_registered += 1+ total_registered += session.run(f"register persons files {date_str}", register_persons_files)context.add_output_metadata({@@ -1947,7 +2154,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa"partition_key": partition_key,"export_mode": "daily","dates_processed": len(dates),- "files_exported": total_exported,+ "days_exported": days_exported,"files_registered": total_registered,"bucket": target.bucket,}@@ -1955,14 +2162,14 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBacontext.log.info(f"Completed duckling persons daily backfill for team_id={team_id}: "- f"{total_exported}/{len(dates)} days exported, {total_registered} registered"+ f"{days_exported}/{len(dates)} days exported, {total_registered} files registered")logger.info("duckling_persons_backfill_complete",team_id=team_id,export_mode="daily",dates_processed=len(dates),- files_exported=total_exported,+ days_exported=days_exported,files_registered=total_registered,)diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex 2c9353cad92b..5ad9677d5c38 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -1,5 +1,6 @@import osfrom datetime import date, datetime, timedelta+from typing import Any, castimport pytestfrom unittest.mock import MagicMock, patch@@ -9,6 +10,7 @@ import psycopgfrom parameterized import parameterizedfrom posthog.dags.events_backfill_to_duckling import (+ DUCKLAKE_ALIAS,DUCKLING_BACKFILL_CONCURRENCY_TAG,EARLIEST_BACKFILL_DATE,EVENTS_COLUMNS,@@ -16,23 +18,37 @@ from posthog.dags.events_backfill_to_duckling import (EVENTS_TABLE_DDL,EXPECTED_DUCKLAKE_EVENTS_COLUMNS,EXPECTED_DUCKLAKE_PERSONS_COLUMNS,+ MAX_S3_FILE_FANOUT,PERSONS_COLUMNS,PERSONS_CONCURRENCY_TAG,PERSONS_TABLE_DDL,+ TARGET_ROWS_PER_FILE,+ DucklingBackfillConfig,DucklingTarget,+ _compute_fanout,+ _connect_duckgres,_connection_dropped,_duckgres_backfill_options,_DuckgresSession,+ _estimate_export_row_count,+ _execute_export_with_retry,_get_cluster,+ _glob_run_files,_resolve_duckling_target,_set_table_partitioning,_validate_identifier,+ delete_events_partition_data,duckling_events_full_backfill_sensor,+ export_events_to_duckling_s3,+ export_persons_full_to_duckling_s3,+ export_persons_to_duckling_s3,get_months_in_range,get_s3_url_for_clickhouse,is_full_export_partition,parse_partition_key,parse_partition_key_dates,+ register_files_with_duckling,+ register_persons_files_with_duckling,table_exists,)@@ -820,6 +836,33 @@ class TestConnectionDropped:assert _connection_dropped(exc) is False+class TestConnectDuckgres:+ """_connect_duckgres pins the session to UTC so ranged DELETEs align with the UTC day+ the export wrote, but never fails a connection if the server can't set it."""++ @patch("posthog.dags.events_backfill_to_duckling.make_duckgres_conninfo", return_value="conninfo")+ @patch("posthog.dags.events_backfill_to_duckling.psycopg.connect")+ def test_sets_utc_timezone_on_connect(self, mock_connect, _conninfo):+ conn = MagicMock()+ mock_connect.return_value = conn++ result = _connect_duckgres(DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="r"))++ assert result is conn+ conn.execute.assert_called_once_with("SET TimeZone='UTC'")++ @patch("posthog.dags.events_backfill_to_duckling.make_duckgres_conninfo", return_value="conninfo")+ @patch("posthog.dags.events_backfill_to_duckling.psycopg.connect")+ def test_timezone_set_failure_does_not_break_connection(self, mock_connect, _conninfo):+ conn = MagicMock()+ conn.execute.side_effect = Exception("unknown setting TimeZone")+ mock_connect.return_value = conn++ # Swallowed: the connection is still returned, not dropped.+ result = _connect_duckgres(DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="r"))+ assert result is conn++class TestDuckgresSessionRetry:"""_DuckgresSession reconnects to a fresh worker on a mid-statement connectiondrop and replays the (idempotent) op, giving up only after MAX_ATTEMPTS.@@ -928,3 +971,403 @@ class TestDuckgresBackfillOptions:# reappear in the options on either path (long OLAP backfills are the point).with patch("posthog.dags.events_backfill_to_duckling.DUCKGRES_WORKER_PROFILE_ENABLED", enabled):assert "statement_timeout" not in _duckgres_backfill_options()+++def _mock_glob_conn(glob_files):+ """A psycopg-shaped mock whose glob() returns the given files."""+ conn = MagicMock()+ cur = MagicMock()+ cur.fetchall.return_value = [(f,) for f in glob_files]+ conn.cursor.return_value.__enter__.return_value = cur+ conn.cursor.return_value.__exit__.return_value = False+ return conn, cur+++def _registered_call_strings(conn):+ """Render each ducklake_add_data_files CALL to its final SQL string."""+ return [call.args[0].as_string() for call in conn.execute.call_args_list]+++class TestComputeFanout:+ """Fan-out is sized to each export's actual volume, not fixed."""++ @parameterized.expand(+ [+ ("empty", 0, 1_000_000, 256, 1),+ ("tiny", 5, 1_000_000, 256, 1),+ ("exactly_target", 1_000_000, 1_000_000, 256, 1),+ ("just_over_target", 1_000_001, 1_000_000, 256, 2),+ ("big_team_day", 72_000_000, 1_000_000, 256, 72),+ ("clamped_to_max", 10_000_000_000, 1_000_000, 256, 256),+ ("smaller_target_more_files", 10_000_000, 500_000, 256, 20),+ # Fail closed on non-positive (user-tunable) config — must not divide-by-zero.+ ("zero_target", 10_000_000, 0, 256, 1),+ ("negative_target", 10_000_000, -1, 256, 1),+ ("zero_max_fanout", 10_000_000, 1_000_000, 0, 1),+ ("negative_max_fanout", 10_000_000, 1_000_000, -5, 1),+ ]+ )+ def test_fanout(self, _label, row_count, target_rows, max_fanout, expected):+ assert _compute_fanout(row_count, target_rows, max_fanout) == expected++ def test_negative_row_count_is_single_file(self):+ assert _compute_fanout(-1, TARGET_ROWS_PER_FILE, MAX_S3_FILE_FANOUT) == 1+++class TestExportClickhouseRetries:+ """Both ClickHouse calls on the export path — the row-count estimate and the export+ itself — must retry transient failures. (Guards against the @retry decorator drifting+ onto the pure _compute_fanout arithmetic, which can never raise.)"""++ @patch("tenacity.nap.time.sleep")+ def test_row_count_estimate_retries_then_succeeds(self, _sleep):+ client = MagicMock()+ client.execute.side_effect = [TimeoutError("transient"), [(123,)]]++ assert _estimate_export_row_count(client, "SELECT count() FROM events", {}) == 123+ assert client.execute.call_count == 2++ @patch("tenacity.nap.time.sleep")+ def test_export_retries_then_succeeds(self, _sleep):+ client = MagicMock()+ client.execute.side_effect = [TimeoutError("transient"), None]++ _execute_export_with_retry(client, "INSERT INTO FUNCTION s3(...)", {}, "info")+ assert client.execute.call_count == 2++ def test_compute_fanout_is_pure(self):+ # No client, no I/O — proves the decorator isn't (re)attached to the arithmetic.+ assert _compute_fanout(10_000_000, 1_000_000, 256) == 10+++class TestExportFanOut:+ """The exports must size the fan-out to the team-day's row count, partition via+ PARTITION BY, and return a run-scoped glob that registration can enumerate."""++ @pytest.fixture+ def target(self):+ return DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")++ def _run_export(self, export_fn, target, row_count, config=None, **kwargs):+ """Run an export with a stubbed count() result; return (insert_sql, glob, client)."""+ client = MagicMock()+ # First execute is the count() estimate, second is the INSERT.+ client.execute.side_effect = [[(row_count,)], None]+ config = config or DucklingBackfillConfig(dry_run=False, skip_ducklake_registration=True)+ s3_glob = export_fn(+ context=MagicMock(),+ client=client,+ config=config,+ target=target,+ settings={},+ run_id="run1",+ **kwargs,+ )+ calls = [c.args[0] for c in client.execute.call_args_list]+ insert_sql = next(sql for sql in calls if "INSERT INTO FUNCTION" in sql)+ count_sql = next(sql for sql in calls if "count()" in sql)+ return insert_sql, count_sql, s3_glob, client++ def test_events_export_sizes_fanout_to_row_count(self, target):+ # 10M rows at the 1M-row default target → 10 files.+ insert_sql, count_sql, s3_glob, _ = self._run_export(+ export_events_to_duckling_s3, target, row_count=10_000_000, team_id=2, date=datetime(2026, 6, 17)+ )+ assert "PARTITION BY toString(cityHash64(distinct_id) % 10)" in insert_sql+ # Count is filtered to exactly the team-day being exported.+ assert "count()" in count_sql and "team_id = 2 AND toDate(timestamp) = '2026-06-17'" in count_sql+ # The S3 destination carries the {_partition_id} placeholder ClickHouse substitutes per bucket.+ assert "year=2026/month=06/day=17/run1_{_partition_id}.parquet" in insert_sql+ assert s3_glob == "s3://bkt/backfill/events/2/year=2026/month=06/day=17/run1_*.parquet"++ def test_tiny_events_day_is_single_file(self, target):+ insert_sql, _count_sql, _glob, _ = self._run_export(+ export_events_to_duckling_s3, target, row_count=42, team_id=2, date=datetime(2026, 6, 17)+ )+ # A handful of rows collapses to one bucket → one file.+ assert "PARTITION BY toString(cityHash64(distinct_id) % 1)" in insert_sql++ def test_huge_events_day_clamps_to_max_fanout(self, target):+ insert_sql, _count_sql, _glob, _ = self._run_export(+ export_events_to_duckling_s3, target, row_count=10_000_000_000, team_id=2, date=datetime(2026, 6, 17)+ )+ assert f"PARTITION BY toString(cityHash64(distinct_id) % {MAX_S3_FILE_FANOUT})" in insert_sql++ def test_config_can_tune_target_and_max(self, target):+ config = DucklingBackfillConfig(+ dry_run=False, skip_ducklake_registration=True, target_rows_per_file=2_000_000, max_s3_file_fanout=8+ )+ insert_sql, _count_sql, _glob, _ = self._run_export(+ export_events_to_duckling_s3,+ target,+ row_count=10_000_000,+ config=config,+ team_id=2,+ date=datetime(2026, 6, 17),+ )+ # 10M / 2M = 5 files (under the lowered cap of 8).+ assert "PARTITION BY toString(cityHash64(distinct_id) % 5)" in insert_sql++ def test_persons_daily_export_sizes_fanout_and_returns_glob(self, target):+ insert_sql, count_sql, s3_glob, _ = self._run_export(+ export_persons_to_duckling_s3, target, row_count=3_000_000, team_id=2, date=datetime(2026, 6, 17)+ )+ assert "PARTITION BY toString(cityHash64(pd.distinct_id) % 3)" in insert_sql+ # Pin the full predicate: dropping is_deleted/date would silently over-size the fan-out.+ assert "FROM person WHERE team_id = 2 AND toDate(_timestamp) = '2026-06-17' AND is_deleted = 0" in count_sql+ assert s3_glob == "s3://bkt/backfill/persons/2/year=2026/month=06/run1_*.parquet"++ def test_persons_full_export_sizes_fanout_and_returns_glob(self, target):+ insert_sql, count_sql, s3_glob, _ = self._run_export(+ export_persons_full_to_duckling_s3, target, row_count=5_000_000, team_id=2+ )+ assert "PARTITION BY toString(cityHash64(pd.distinct_id) % 5)" in insert_sql+ assert "FROM person_distinct_id2 WHERE team_id = 2 AND is_deleted = 0" in count_sql+ assert s3_glob == "s3://bkt/backfill/persons/2/year=0/month=0/run1_*.parquet"++ @parameterized.expand(+ [+ ("events", export_events_to_duckling_s3, {"team_id": 2, "date": datetime(2026, 6, 17)}),+ ("persons", export_persons_to_duckling_s3, {"team_id": 2, "date": datetime(2026, 6, 17)}),+ ("persons_full", export_persons_full_to_duckling_s3, {"team_id": 2}),+ ]+ )+ def test_dry_run_does_not_touch_clickhouse(self, _label, export_fn, kwargs):+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ client = MagicMock()+ config = DucklingBackfillConfig(dry_run=True)+ result = export_fn(+ context=MagicMock(), client=client, config=config, target=target, settings={}, run_id="run1", **kwargs+ )+ assert result is None+ # No count, no insert — dry run must not hit the cluster at all.+ client.execute.assert_not_called()+++class TestRegisterFilesWithDuckling:+ """Registration must enumerate every file a run produced and register each+ exactly once, while tolerating an empty fan-out."""++ @pytest.fixture+ def target(self):+ return DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")++ @parameterized.expand(+ [+ ("events", register_files_with_duckling, "events"),+ ("persons", register_persons_files_with_duckling, "persons"),+ ]+ )+ def test_registers_every_globbed_file_once(self, _label, register_fn, table, target=None):+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ files = [f"s3://bkt/backfill/{table}/2/year=2026/month=06/day=17/run1_{i}.parquet" for i in range(3)]+ conn, _cur = _mock_glob_conn(files)+ config = DucklingBackfillConfig()++ count = register_fn(MagicMock(), target, "s3://bkt/.../run1_*.parquet", config, conn)++ assert count == 3+ # One ducklake_add_data_files CALL per file, exactly once, for exactly these files.+ assert conn.execute.call_count == 3+ calls = _registered_call_strings(conn)+ assert all("ducklake_add_data_files" in c for c in calls)+ assert all(f"'{path}'" in calls[i] for i, path in enumerate(files))++ @parameterized.expand(+ [+ ("events", register_files_with_duckling),+ ("persons", register_persons_files_with_duckling),+ ]+ )+ def test_empty_glob_registers_nothing(self, _label, register_fn):+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ conn, _cur = _mock_glob_conn([])+ config = DucklingBackfillConfig()++ count = register_fn(MagicMock(), target, "s3://bkt/.../run1_*.parquet", config, conn)++ assert count == 0+ conn.execute.assert_not_called()++ @parameterized.expand(+ [+ ("skip_registration", {"skip_ducklake_registration": True}),+ ("dry_run", {"dry_run": True}),+ ]+ )+ def test_disabled_paths_register_nothing(self, _label, config_kwargs):+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ conn, _cur = _mock_glob_conn(["s3://bkt/a/run1_0.parquet"])+ config = DucklingBackfillConfig(**config_kwargs)++ count = register_files_with_duckling(MagicMock(), target, "s3://bkt/.../run1_*.parquet", config, conn)++ assert count == 0+ conn.execute.assert_not_called() # never even globs++ def test_glob_run_files_uses_parameterized_glob(self, target):+ conn, cur = _mock_glob_conn(["s3://bkt/x/run1_0.parquet", "s3://bkt/x/run1_1.parquet"])++ files = _glob_run_files(conn, "s3://bkt/x/run1_*.parquet")++ assert files == ["s3://bkt/x/run1_0.parquet", "s3://bkt/x/run1_1.parquet"]+ sql, params = cur.execute.call_args.args+ assert "glob(%s)" in sql+ assert params == ("s3://bkt/x/run1_*.parquet",)+++# Column SELECT used to synthesize events Parquet files for the round-trip test.+def _events_rows_select(n_rows, uuid_prefix, ts):+ return f"""+ SELECT+ ('{uuid_prefix}-' || i)::VARCHAR AS uuid,+ '$pageview'::VARCHAR AS event,+ '{{}}'::VARCHAR AS properties,+ '{ts}'::TIMESTAMPTZ AS timestamp,+ 2::BIGINT AS team_id,+ 2::BIGINT AS project_id,+ ('user-' || i)::VARCHAR AS distinct_id,+ ''::VARCHAR AS elements_chain,+ '{ts}'::TIMESTAMPTZ AS created_at,+ ('person-' || i)::VARCHAR AS person_id,+ '{ts}'::TIMESTAMPTZ AS person_created_at,+ '{{}}'::VARCHAR AS person_properties,+ '{{}}'::VARCHAR AS group0_properties,+ '{{}}'::VARCHAR AS group1_properties,+ '{{}}'::VARCHAR AS group2_properties,+ '{{}}'::VARCHAR AS group3_properties,+ '{{}}'::VARCHAR AS group4_properties,+ '{ts}'::TIMESTAMPTZ AS group0_created_at,+ '{ts}'::TIMESTAMPTZ AS group1_created_at,+ '{ts}'::TIMESTAMPTZ AS group2_created_at,+ '{ts}'::TIMESTAMPTZ AS group3_created_at,+ '{ts}'::TIMESTAMPTZ AS group4_created_at,+ 'full'::VARCHAR AS person_mode,+ false::BOOLEAN AS historical_migration,+ '{ts}'::TIMESTAMPTZ AS _inserted_at+ FROM range({n_rows}) AS t(i)+ """+++class _DuckdbPsycopgAdapter:+ """Adapts a raw duckdb connection to the slice of the psycopg API the production+ duckgres helpers use (`conn.cursor()` context manager, `cur.execute(sql, params)`,+ `cur.fetchall()`, `cur.rowcount`, and `conn.execute(psql.Composed)`), so the REAL+ register_files_with_duckling / _glob_run_files / delete_events_partition_data run+ against a local DuckLake catalog instead of being re-implemented in the test."""++ def __init__(self, duck: Any):+ self._duck = duck+ self._result: Any = None++ # The production code uses one connection as both connection and cursor; in this+ # single-threaded test we can be both.+ def cursor(self):+ return self++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def execute(self, query, params=None):+ # register_*_files passes a psql.Composed (render it); _glob_run_files /+ # delete_* pass a %s-parameterized string (translate to duckdb's ? binding).+ sql = query.as_string() if hasattr(query, "as_string") else query.replace("%s", "?")+ self._result = self._duck.execute(sql, list(params)) if params else self._duck.execute(sql)+ return self++ def fetchall(self):+ return self._result.fetchall()++ @property+ def rowcount(self):+ return -1 # production treats -1 as unknown → 0; the test asserts via SELECT count(*)+++class TestFannedOutLayoutRoundTrip:+ """End-to-end against a real DuckLake catalog, driving the PRODUCTION registration and+ delete helpers (via _DuckdbPsycopgAdapter): a fanned-out team-day registers as many+ files whose rows all become queryable, and a re-run with a different fan-out re-registers+ cleanly via DELETE-before-register without duplicating or counting orphans."""++ @pytest.fixture+ def lake(self, tmp_path):+ catalog_path = str(tmp_path / "test.ducklake")+ data_path = str(tmp_path / "data")+ os.makedirs(data_path)++ conn = duckdb.connect()+ conn.execute("INSTALL ducklake")+ conn.execute("LOAD ducklake")+ # Attach under the production alias so register_files_with_duckling (which uses+ # 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(+ f"ALTER TABLE {DUCKLAKE_ALIAS}.posthog.events "+ "SET PARTITIONED BY (year(timestamp), month(timestamp), day(timestamp))"+ )+ yield conn, str(tmp_path)+ conn.close()++ def _write_fanned_out_day(self, conn, root, run_id, n_files, rows_per_file):+ """Write n_files Parquet files into the day= dir, mirroring PARTITION BY output."""+ day_dir = os.path.join(root, "events", "2", "year=2026", "month=06", "day=17")+ os.makedirs(day_dir, exist_ok=True)+ for bucket in range(n_files):+ path = os.path.join(day_dir, f"{run_id}_{bucket}.parquet")+ conn.execute(+ f"COPY ({_events_rows_select(rows_per_file, f'{run_id}-{bucket}', '2026-06-17 12:00:00+00')}) "+ f"TO '{path}' (FORMAT PARQUET)"+ )+ return os.path.join(day_dir, f"{run_id}_*.parquet")++ def _count(self, conn):+ return conn.execute(f"SELECT count(*) FROM {DUCKLAKE_ALIAS}.posthog.events").fetchone()[0]++ def _register(self, conn, file_glob):+ """Drive the PRODUCTION register_files_with_duckling against the real catalog."""+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ config = DucklingBackfillConfig()+ # The adapter duck-types the psycopg.Connection slice these helpers use.+ adapter = cast("psycopg.Connection[Any]", _DuckdbPsycopgAdapter(conn))+ return register_files_with_duckling(MagicMock(), target, file_glob, config, adapter)++ def _delete_day(self, conn):+ """Drive the PRODUCTION ranged DELETE against the real catalog."""+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ adapter = cast("psycopg.Connection[Any]", _DuckdbPsycopgAdapter(conn))+ delete_events_partition_data(MagicMock(), target, 2, datetime(2026, 6, 17), conn=adapter)++ def test_many_files_register_and_all_rows_queryable(self, lake):+ conn, root = lake+ file_glob = self._write_fanned_out_day(conn, root, "run1", n_files=4, rows_per_file=10)++ registered = self._register(conn, file_glob)++ assert registered == 4 # one INSERT produced many files, all registered exactly once+ assert self._count(conn) == 40++ def test_rerun_does_not_duplicate_or_count_orphans(self, lake):+ conn, root = lake++ # First run: 4 files, 40 rows.+ glob1 = self._write_fanned_out_day(conn, root, "run1", n_files=4, rows_per_file=10)+ self._delete_day(conn)+ assert self._register(conn, glob1) == 4+ assert self._count(conn) == 40++ # Re-run with a NEW run_id AND a different fan-out (3 vs 4) writes a fresh file set.+ # The prior run's files stay on disk as orphans (different run_id prefix).+ glob2 = self._write_fanned_out_day(conn, root, "run2", n_files=3, rows_per_file=10)++ # DELETE-before-register clears the day's catalog rows, then we register only+ # this run's files (run-scoped glob never sees run1's orphans).+ self._delete_day(conn)+ assert self._register(conn, glob2) == 3++ # Exactly the re-run's rows — no duplication, orphaned run1 files not counted.+ assert self._count(conn) == 30