: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(dags): work around ducklake_add_data_files partition index bug (#67168)
Jakob Homane8734d0e770c
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex cb2565fc9477..a0c6c460cc91 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -30,13 +30,16 @@ Partition Strategy:"""import os+import reimport mathimport time+import randomimport calendarimport dataclassesfrom collections.abc import Callable+from contextlib import closingfrom datetime import date, datetime, timedelta-from typing import Any+from typing import Any, Literalfrom django.utils import timezone@@ -1537,6 +1540,393 @@ def _glob_run_files(conn: psycopg.Connection[Any], s3_glob: str) -> list[str]:return [row[0] for row in rows]+# ---------------------------------------------------------------------------+# DuckLake ducklake_file_partition_value post-write fix-up+# ---------------------------------------------------------------------------+# Workaround for a DuckLake bug in ducklake_add_data_files(): when a partition+# spec applies multiple transforms to one source column (events: year/month/day+# on `timestamp`; persons: year/month on `_timestamp`), every ducklake_file_partition_value row lands at+# the HIGHEST partition_key_index instead of being spread across the spec's+# columns. Tier-3 compaction then fails with "Files have different hive+# partition path", and partition pruning silently misses files.+#+# Bug writeup: see PR #67168 (the workaround landing this fix-up).+# Buggy code: ducklake src/functions/ducklake_add_data_files.cpp — see the+# `field_partition_key_map` map keyed bare `field_id.index` and+# the loop in `MapPartitionColumns` (line numbers will rot).+#+# Failure semantics: this fix-up raises RuntimeError on any inconsistency+# (catalog unreachable, spec drift, post-condition fail). _DuckgresSession.run+# only retries _connection_dropped exceptions, so a ducklake_file_partition_value failure is terminal+# for the partition — Dagster asset-level retry recovers, not the duckgres+# replay loop. Failures are convergent if retried because DELETE-then-INSERT+# of the same paths produces the same end state.++_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR = "DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENABLED"++# Catalog Postgres connect timeout. NOT shared with DUCKGRES_CONNECT_TIMEOUT —+# duckgres needs minutes for a cold-start worker; plain Postgres connects in+# under a second.+_DUCKLAKE_FILE_PARTITION_VALUE_CATALOG_CONNECT_TIMEOUT = 10++# Bound for the per-batch fix-up: DML + post-condition (the advisory lock+# acquisition is OUTSIDE the txn — see _acquire_*_session_advisory_lock).+_DUCKLAKE_FILE_PARTITION_VALUE_STATEMENT_TIMEOUT = "60s"+# Bound for any single row-lock wait inside the txn (defense in depth — the+# session advisory lock already serializes us against other maintenance ops).+_DUCKLAKE_FILE_PARTITION_VALUE_LOCK_TIMEOUT = "5s"++# pg_try_advisory_lock retry (session-scoped): bounded so a hung maintainer+# can't block a backfill step forever. Sleeps happen OUTSIDE any open txn.+_DUCKLAKE_FILE_PARTITION_VALUE_LOCK_RETRY_ATTEMPTS = 6+_DUCKLAKE_FILE_PARTITION_VALUE_LOCK_RETRY_BASE_SECONDS = 1.0+_DUCKLAKE_FILE_PARTITION_VALUE_LOCK_RETRY_MAX_SECONDS = 8.0++# Per-table partition spec: (partition_key_index, transform name). Transform+# names mirror the hive segment names in the S3 paths produced by the dagster+# exports AND the live catalog (ducklake_partition_column.transform). Asserted+# at runtime against the live catalog before any DML — drift fails loud.+_DUCKLAKE_FILE_PARTITION_VALUE_SPEC: dict[str, tuple[tuple[int, str], ...]] = {+ "events": ((0, "year"), (1, "month"), (2, "day")),+ "persons": ((0, "year"), (1, "month")),+}++# Pre-flight: every registered path must carry the spec's hive segments. Fail+# loud before any catalog DML — a NULL partition_value insert would produce a+# third class of catalog rot worse than the bug itself.+_DUCKLAKE_FILE_PARTITION_VALUE_PATH_REGEXES: dict[str, re.Pattern[str]] = {+ # Persons "full" export writes year=0/month=0 (export_persons_full_to_duckling_s3),+ # so accept any digit width on both tables.+ "events": re.compile(r"/year=\d+/month=\d+/day=\d+/[^/]+\.parquet$"),+ "persons": re.compile(r"/year=\d+/month=\d+/[^/]+\.parquet$"),+}+++def _ducklake_file_partition_value_fixup_enabled() -> bool:+ return os.environ.get(_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR, "true").lower() in ("1", "true", "yes", "on")+++def _open_catalog_conn(target: DucklingTarget) -> psycopg.Connection[Any]:+ server = get_duckgres_server_for_organization(target.organization_id)+ if server is None or not server.catalog_host:+ raise RuntimeError(+ f"DuckgresServer with catalog_* fields not found for organization_id={target.organization_id}; "+ f"set {_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR}=false to skip the "+ f"ducklake_file_partition_value fix-up (loses bug coverage)."+ )+ return psycopg.connect(+ host=server.catalog_host,+ port=server.catalog_port,+ dbname=server.catalog_database,+ user=server.catalog_username,+ password=server.catalog_password,+ autocommit=False,+ connect_timeout=_DUCKLAKE_FILE_PARTITION_VALUE_CATALOG_CONNECT_TIMEOUT,+ )+++def _acquire_ducklake_file_partition_value_session_advisory_lock(conn: Any) -> None:+ # Bounded retry on the session-scoped pg_try_advisory_lock so a stuck+ # maintainer can't hang a backfill step indefinitely (pg_advisory_lock would+ # block forever). Session-scoped — not xact-scoped — so the retry backoffs+ # happen OUTSIDE any open Postgres transaction; sleeping inside an open txn+ # would leave the connection idle-in-transaction, which blocks vacuum and+ # accumulates xid age. Caller must release via the matching `_release_*`+ # helper, and must have set conn.autocommit=True before calling.+ for attempt in range(_DUCKLAKE_FILE_PARTITION_VALUE_LOCK_RETRY_ATTEMPTS):+ with conn.cursor() as cur:+ cur.execute("SELECT pg_try_advisory_lock(hashtext('millpond-ducklake-maintenance')::bigint)")+ row = cur.fetchone()+ if row is None:+ raise RuntimeError("pg_try_advisory_lock returned no row — Postgres protocol invariant violated")+ if row[0]:+ return+ backoff = min(+ _DUCKLAKE_FILE_PARTITION_VALUE_LOCK_RETRY_MAX_SECONDS,+ _DUCKLAKE_FILE_PARTITION_VALUE_LOCK_RETRY_BASE_SECONDS * (2**attempt),+ )+ time.sleep(backoff * (0.5 + random.random()))+ raise RuntimeError(+ f"ducklake_file_partition_value fix-up: could not acquire millpond-ducklake-maintenance advisory lock "+ f"after {_DUCKLAKE_FILE_PARTITION_VALUE_LOCK_RETRY_ATTEMPTS} attempts"+ )+++def _release_ducklake_file_partition_value_session_advisory_lock(conn: Any) -> None:+ # Best-effort: if the connection is already gone, Postgres releases the+ # session-scoped lock on disconnect anyway. Caller must have set+ # conn.autocommit=True before calling so the unlock SELECT doesn't+ # implicitly start a transaction. We deliberately don't read the unlock+ # return value — `false` (didn't hold the lock) would mean the connection+ # is about to drop it anyway via `closing(...)`, so the extra roundtrip+ # is noise.+ try:+ with conn.cursor() as cur:+ cur.execute("SELECT pg_advisory_unlock(hashtext('millpond-ducklake-maintenance')::bigint)")+ except (psycopg.Error, OSError) as exc:+ # Narrowed to the catalog/transport error classes that the unlock SELECT+ # can actually raise. Anything else (programming bug, etc.) propagates.+ logger.warning(+ "duckling_ducklake_file_partition_value_fixup_release_failed",+ error=str(exc),+ error_type=type(exc).__name__,+ )+++def _assert_live_spec_matches(+ cur: Any,+ table_kind: Literal["events", "persons"],+ table_name: str,+ table_id: int,+ partition_id: int,+) -> None:+ # The fix-up bakes _DUCKLAKE_FILE_PARTITION_VALUE_SPEC into the SQL it emits. If the live catalog spec+ # drifts (someone runs ALTER ... SET PARTITIONED BY, or a future writer+ # version reshapes things), we'd silently mis-index rows. Cheap one-SELECT+ # defense against that whole class. table_kind ("events"/"persons") keys+ # the spec; table_name is the actual catalog name and may carry a per-team+ # suffix (events_<suffix> / persons_<suffix>) — the spec is the same for+ # every suffix variant since the partition layout doesn't change.+ cur.execute(+ """+ SELECT partition_key_index, transform+ FROM public.ducklake_partition_column+ WHERE partition_id = %s AND table_id = %s+ ORDER BY partition_key_index+ """,+ (partition_id, table_id),+ )+ actual = tuple((int(idx), str(transform)) for idx, transform in cur.fetchall())+ expected = _DUCKLAKE_FILE_PARTITION_VALUE_SPEC[table_kind]+ if actual != expected:+ raise RuntimeError(+ f"ducklake_file_partition_value fix-up: live catalog spec for posthog.{table_name} "+ f"(kind={table_kind}, partition_id={partition_id}) is {actual}; expected {expected}. "+ f"Update _DUCKLAKE_FILE_PARTITION_VALUE_SPEC and redeploy before re-enabling the fix-up."+ )+++def _fixup_partition_values_for_added_files(+ context: AssetExecutionContext,+ target: DucklingTarget,+ table_kind: Literal["events", "persons"],+ table_name: str,+ file_paths: list[str],+) -> None:+ # Repair ducklake_file_partition_value rows for files just registered via ducklake_add_data_files().+ # table_kind is the logical kind ("events" or "persons") used to look up the+ # spec + path regex; table_name is the actual catalog table the files were+ # registered into and may carry a per-team suffix (events_<suffix> /+ # persons_<suffix>) per DuckgresServerTeam.table_suffix. The dagster+ # registration path writes files for the suffixed table while keeping the+ # S3 prefix (backfill/events/.../) tied to the kind, not the suffix.+ # Raises RuntimeError on any inconsistency; see module-level block for the+ # failure-semantics contract. Convergent and idempotent.+ if not file_paths:+ return++ spec = _DUCKLAKE_FILE_PARTITION_VALUE_SPEC.get(table_kind)+ path_regex = _DUCKLAKE_FILE_PARTITION_VALUE_PATH_REGEXES.get(table_kind)+ if spec is None or path_regex is None:+ raise ValueError(f"_DUCKLAKE_FILE_PARTITION_VALUE_SPEC has no entry for table_kind={table_kind!r}")++ unparseable = [p for p in file_paths if not path_regex.search(p)]+ if unparseable:+ sample = ", ".join(unparseable[:3])+ raise ValueError(+ f"ducklake_file_partition_value fix-up: {len(unparseable)} of {len(file_paths)} "+ f"{table_kind} (in {table_name}) path(s) do not match the expected hive layout (sample: {sample})"+ )++ expected_index_set = [idx for idx, _ in spec]++ # closing(...) actually closes the connection on exit; psycopg3's Connection+ # context manager only commits/rolls back the open txn. We acquire the+ # session advisory lock OUTSIDE the main txn (autocommit=True during+ # acquisition) so retry backoffs don't sit idle-in-transaction; switch to+ # autocommit=False to drive the BEGIN→COMMIT (clean) or BEGIN→ROLLBACK+ # (exception) via the inner `with conn:`; finally, switch back to+ # autocommit=True to release the session lock (best-effort — PG releases+ # it on disconnect anyway, so the `closing(...)` exit is the backstop).+ with closing(_open_catalog_conn(target)) as catalog_conn:+ catalog_conn.autocommit = True+ _acquire_ducklake_file_partition_value_session_advisory_lock(catalog_conn)+ try:+ catalog_conn.autocommit = False+ with catalog_conn, catalog_conn.cursor() as cur:+ # Bound any single statement so a misbehaving server can't hang+ # the step. SET LOCAL is scoped to this txn — no global side effect.+ cur.execute(+ psql.SQL("SET LOCAL statement_timeout = {}").format(+ psql.Literal(_DUCKLAKE_FILE_PARTITION_VALUE_STATEMENT_TIMEOUT)+ )+ )+ cur.execute(+ psql.SQL("SET LOCAL lock_timeout = {}").format(+ psql.Literal(_DUCKLAKE_FILE_PARTITION_VALUE_LOCK_TIMEOUT)+ )+ )++ cur.execute(+ """+ SELECT t.table_id, pi.partition_id+ FROM public.ducklake_table t+ JOIN public.ducklake_partition_info pi+ ON pi.table_id = t.table_id AND pi.end_snapshot IS NULL+ WHERE t.schema_name = 'posthog'+ AND t.table_name = %s+ AND t.end_snapshot IS NULL+ """,+ (table_name,),+ )+ rows = cur.fetchall()+ if len(rows) != 1:+ raise RuntimeError(+ f"ducklake_file_partition_value fix-up: expected exactly one live partition_info "+ f"for posthog.{table_name}, got {len(rows)}"+ )+ table_id, partition_id = rows[0]++ _assert_live_spec_matches(cur, table_kind, table_name, table_id, partition_id)++ # Single-statement DELETE + INSERT so no reader sees zero ducklake_file_partition_value rows.+ # DELETE is scoped by table_id AND data_file_id (defense in depth).+ # The INSERT runs unconditionally over `to_repair`. Do NOT add a+ # defensive `WHERE EXISTS (... deleted)` or scalar-subquery+ # reference — that filters out target files whose DELETE returned+ # 0 rows (e.g., a file that arrived with no fpv rows at all),+ # leaving them stuck. `deleted` is intentionally unreferenced:+ # per PG docs §7.8.2, data-modifying CTEs in WITH execute exactly+ # once "always to completion, independently of whether the+ # primary query reads all (or indeed any) of their output."+ insert_branches = psql.SQL(" UNION ALL ").join(+ psql.SQL(+ "SELECT t.data_file_id, {tid}, {idx}, "+ "(substring(t.path from {hive_re}))::INT::TEXT "+ "FROM targets t"+ ).format(+ tid=psql.Literal(table_id),+ idx=psql.Literal(key_index),+ hive_re=psql.Literal(f"{col_name}=([0-9]+)"),+ )+ for key_index, col_name in spec+ )+ stmt = psql.SQL(+ """+ WITH targets AS (+ SELECT data_file_id, path+ FROM public.ducklake_data_file+ WHERE table_id = {tid}+ AND end_snapshot IS NULL+ AND partition_id = {pid}+ AND path = ANY(%s)+ ),+ deleted AS (+ DELETE FROM public.ducklake_file_partition_value+ WHERE table_id = {tid}+ AND data_file_id IN (SELECT data_file_id FROM targets)+ RETURNING data_file_id+ )+ INSERT INTO public.ducklake_file_partition_value+ (data_file_id, table_id, partition_key_index, partition_value)+ {inserts}+ """+ ).format(+ tid=psql.Literal(table_id),+ pid=psql.Literal(partition_id),+ inserts=insert_branches,+ )+ # file_paths bound via %s (not psql.Literal of a list) so the+ # statement text stays small and statement-cache-friendly even for+ # large batches. Keep file_paths a list — psycopg3 maps list[str]+ # to PG text[]; a tuple would map to a record instead.+ cur.execute(stmt, (list(file_paths),))++ # Post-condition: every file's actual partition_key_index set equals+ # the expected set, and no NULL partition_value rows landed. The+ # set-equality catches the bug pattern (multiple rows at the+ # highest index) that a naive count check would miss.+ cur.execute(+ psql.SQL(+ """+ WITH file_partition_value_state AS (+ SELECT df.data_file_id,+ COALESCE(+ array_agg(file_partition_value.partition_key_index+ ORDER BY file_partition_value.partition_key_index)+ FILTER (WHERE file_partition_value.partition_key_index IS NOT NULL),+ '{{}}'::int[]+ ) AS indexes,+ COUNT(*) FILTER (WHERE file_partition_value.partition_value IS NULL) AS nulls+ FROM public.ducklake_data_file df+ LEFT JOIN public.ducklake_file_partition_value file_partition_value+ ON file_partition_value.data_file_id = df.data_file_id+ AND file_partition_value.table_id = {tid}+ WHERE df.table_id = {tid}+ AND df.end_snapshot IS NULL+ AND df.path = ANY(%s)+ GROUP BY df.data_file_id+ )+ SELECT+ COUNT(*) FILTER (WHERE indexes IS DISTINCT FROM %s::int[]) AS wrong_indexes,+ COUNT(*) FILTER (WHERE nulls > 0) AS null_values,+ COUNT(*) AS total+ FROM file_partition_value_state+ """+ ).format(tid=psql.Literal(table_id)),+ (list(file_paths), expected_index_set),+ )+ post_condition_row = cur.fetchone()+ if post_condition_row is None:+ raise RuntimeError(+ "post-condition aggregate returned no row — Postgres protocol invariant violated"+ )+ wrong_indexes, null_values, total = post_condition_row++ if wrong_indexes != 0 or null_values != 0 or total != len(file_paths):+ # Raise inside the `with catalog_conn` block so the context+ # manager rolls back; no explicit rollback needed. logger.error+ # (not .exception) since we're not inside an except block — no+ # live exception to capture a traceback from.+ logger.error(+ "duckling_ducklake_file_partition_value_fixup_post_condition_failed",+ table_kind=table_kind,+ table_name=table_name,+ organization_id=target.organization_id,+ team_id=target.team_id,+ wrong_indexes=wrong_indexes,+ null_values=null_values,+ actual_total=total,+ expected_total=len(file_paths),+ )+ raise RuntimeError(+ f"ducklake_file_partition_value fix-up post-condition failed for {table_name}: "+ f"wrong_indexes={wrong_indexes}, null_values={null_values}, "+ f"total={total}, expected_total={len(file_paths)}"+ )+ finally:+ # Release the session-scoped lock. Skip if the conn has been closed+ # mid-flight (e.g., transport drop during DML) — toggling autocommit+ # on a closed conn raises InterfaceError, which would mask the+ # original exception. PG releases session locks on disconnect+ # anyway, so there's nothing to do.+ if not catalog_conn.closed:+ catalog_conn.autocommit = True+ _release_ducklake_file_partition_value_session_advisory_lock(catalog_conn)++ context.log.info(+ f"ducklake_file_partition_value fix-up: rebuilt partition values for {len(file_paths)} {table_name} file(s)"+ )+ logger.info(+ "duckling_ducklake_file_partition_value_fixup_succeeded",+ table_kind=table_kind,+ table_name=table_name,+ organization_id=target.organization_id,+ team_id=target.team_id,+ files_rewritten=len(file_paths),+ )++def register_files_with_duckling(context: AssetExecutionContext,target: DucklingTarget,@@ -1599,6 +1989,9 @@ def register_files_with_duckling(psql.Literal(s3_path),))++ if _ducklake_file_partition_value_fixup_enabled():+ _fixup_partition_values_for_added_files(context, target, "events", target.events_table, files)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.@@ -1866,6 +2259,9 @@ def register_persons_files_with_duckling(psql.Literal(s3_path),))++ if _ducklake_file_partition_value_fixup_enabled():+ _fixup_partition_values_for_added_files(context, target, "persons", target.persons_table, files)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.diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex e13265321cc0..2aa4f9aa9a2d 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -11,6 +11,7 @@ from parameterized import parameterizedfrom posthog.dags.common import JobOwnersfrom posthog.dags.events_backfill_to_duckling import (+ _DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR,DUCKLAKE_ALIAS,DUCKLING_BACKFILL_CONCURRENCY_TAG,EARLIEST_BACKFILL_DATE,@@ -31,8 +32,10 @@ from posthog.dags.events_backfill_to_duckling import (_connection_dropped,_duckgres_backfill_options,_DuckgresSession,+ _ducklake_file_partition_value_fixup_enabled,_estimate_export_row_count,_execute_export_with_retry,+ _fixup_partition_values_for_added_files,_get_cluster,_glob_run_files,_is_transient_s3_error,@@ -58,6 +61,18 @@ from posthog.dags.events_backfill_to_duckling import ()[email protected](autouse=True)+def _disable_ducklake_file_partition_value_fixup_by_default():+ # The ducklake_file_partition_value fix-up is gated by DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENABLED, which defaults on+ # in production. Most tests in this file use mock connections that can't+ # actually run the fix-up; default to off here and let the ducklake_file_partition_value-specific+ # tests override with their own @patch(..., return_value=True).+ with patch(+ "posthog.dags.events_backfill_to_duckling._ducklake_file_partition_value_fixup_enabled", return_value=False+ ):+ yield++class TestDucklingBackfillAlertRouting:@parameterized.expand([@@ -1579,6 +1594,355 @@ class TestRegisterFilesWithDuckling:_glob_run_files(conn, "s3://bkt/x/run1_*.parquet")+_EVENTS_SPEC_ROWS = [(0, "year"), (1, "month"), (2, "day")]+_PERSONS_SPEC_ROWS = [(0, "year"), (1, "month")]+++def _make_catalog_conn_mock(+ *,+ post_condition_row: tuple[int, int, int],+ spec_rows: list[tuple[int, str]] | None = None,+ partition_info_rows: list[tuple[int, int]] | None = None,+ lock_acquired: bool = True,+):+ """Builds a MagicMock catalog conn + cur that returns scripted values for the+ sequence of fetches _fixup_partition_values_for_added_files makes. Order:+ fetchone() → advisory lock result+ fetchall() → partition_info_rows+ fetchall() → spec_rows (live partition_column spec)+ fetchone() → post_condition_row++ post_condition_row is required: defaulting it to (0, 0, 0) would silently+ trip the post-condition's `total != len(file_paths)` branch in any test+ that passes a non-empty file list — a footgun for future tests.+ """+ cur = MagicMock()+ cur.fetchone.side_effect = [(lock_acquired,), post_condition_row]+ cur.fetchall.side_effect = [+ partition_info_rows or [(760, 761)],+ spec_rows or _EVENTS_SPEC_ROWS,+ ]+ cur.__enter__.return_value = cur+ cur.__exit__.return_value = None++ conn = MagicMock()+ conn.cursor.return_value = cur+ conn.__enter__.return_value = conn+ conn.__exit__.return_value = None+ # `closed` defaults to a truthy MagicMock; explicitly False so the finally+ # block's `if not conn.closed` guard runs the unlock path.+ conn.closed = False+ return conn, cur+++class TestDucklakeFilePartitionValueFixupFlag:+ @parameterized.expand(+ [+ ("unset", None, True),+ ("true", "true", True),+ ("True_mixedcase", "True", True),+ ("one", "1", True),+ ("yes", "yes", True),+ ("on", "on", True),+ ("false", "false", False),+ ("zero", "0", False),+ ("no", "no", False),+ ("garbage", "garbage", False),+ ("empty", "", False),+ ]+ )+ def test_flag_parsing(self, _label, env_value, expected):+ original = os.environ.get(_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR)+ if env_value is None:+ os.environ.pop(_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR, None)+ else:+ os.environ[_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR] = env_value+ try:+ assert _ducklake_file_partition_value_fixup_enabled() is expected+ finally:+ if original is None:+ os.environ.pop(_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR, None)+ else:+ os.environ[_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR] = original+++class TestDucklakeFilePartitionValueFixupHelper:+ @pytest.fixture+ def target(self):+ return DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")++ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_empty_file_list_is_noop(self, mock_open_conn, target):+ _fixup_partition_values_for_added_files(MagicMock(), target, "events", "events", [])+ mock_open_conn.assert_not_called()++ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_unknown_table_kind_raises(self, mock_open_conn, target):+ # table_kind is Literal["events", "persons"] so a bad value triggers a+ # mypy error too; the type: ignore is the test-only way to exercise the+ # runtime guard. The runtime guard exists as belt-and-suspenders for+ # any caller that bypasses static typing.+ with pytest.raises(ValueError, match="_DUCKLAKE_FILE_PARTITION_VALUE_SPEC has no entry"):+ _fixup_partition_values_for_added_files(+ MagicMock(),+ target,+ "unknown_kind", # type: ignore[arg-type]+ "unknown_table",+ ["s3://bkt/whatever/year=2026/month=06/day=17/run1.parquet"],+ )+ mock_open_conn.assert_not_called()++ @parameterized.expand(+ [+ ("missing_year", "events", "s3://bkt/backfill/events/2/month=06/day=17/run1.parquet"),+ ("missing_day_events", "events", "s3://bkt/backfill/events/2/year=2026/month=06/run1.parquet"),+ ("missing_month_persons", "persons", "s3://bkt/backfill/persons/2/year=2026/run1.parquet"),+ ("nonparquet_suffix", "events", "s3://bkt/backfill/events/2/year=2026/month=06/day=17/run1.txt"),+ ("lake_relative", "events", "ducklake-abcdef.parquet"),+ ]+ )+ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_pre_flight_rejects_malformed_paths(self, _label, kind, bad_path, mock_open_conn):+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ with pytest.raises(ValueError, match="do not match the expected hive layout"):+ _fixup_partition_values_for_added_files(MagicMock(), target, kind, kind, [bad_path])+ mock_open_conn.assert_not_called()++ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_persons_full_export_path_accepted(self, mock_open_conn, target):+ # Persons "full" export writes year=0/month=0; the regex must accept it.+ # We let _open_catalog_conn raise so the test asserts regex-passed-but-then-stopped.+ mock_open_conn.side_effect = RuntimeError("regex passed")+ with pytest.raises(RuntimeError, match="regex passed"):+ _fixup_partition_values_for_added_files(+ MagicMock(),+ target,+ "persons",+ "persons",+ ["s3://bkt/backfill/persons/2/year=0/month=0/run1_0.parquet"],+ )+ mock_open_conn.assert_called_once_with(target)++ @parameterized.expand(+ [+ ("events_suffixed", "events", "events_acme"),+ ("persons_suffixed", "persons", "persons_acme"),+ ]+ )+ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_suffixed_table_name_uses_actual_name_in_catalog_lookup(+ self, _label, kind, actual_table_name, mock_open_conn+ ):+ # When DuckgresServerTeam.table_suffix is set, the dagster registration+ # path writes to events_<suffix> / persons_<suffix>. The fix-up must+ # look up THAT table in the catalog, not the bare kind name. Verified+ # by inspecting the cur.execute call binding the table_name param.+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ ext = "/day=17/run1_0.parquet" if kind == "events" else "/run1_0.parquet"+ files = [f"s3://bkt/backfill/{kind}/2/year=2026/month=06{ext}"]+ spec_rows = _EVENTS_SPEC_ROWS if kind == "events" else _PERSONS_SPEC_ROWS+ conn, cur = _make_catalog_conn_mock(post_condition_row=(0, 0, len(files)), spec_rows=spec_rows)+ mock_open_conn.return_value = conn++ _fixup_partition_values_for_added_files(MagicMock(), target, kind, actual_table_name, files)++ # The partition_info SELECT is parameter-bound with (table_name,); pin+ # that we're querying for the suffixed name, not the bare kind.+ partition_info_calls = [c for c in cur.execute.call_args_list if "ducklake_partition_info" in str(c.args[0])]+ assert len(partition_info_calls) == 1+ assert partition_info_calls[0].args[1] == (actual_table_name,)+++class TestDucklakeFilePartitionValueFixupCatalogInteraction:+ @pytest.fixture+ def target(self):+ return DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")++ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_session_bounded_and_lock_taken_before_any_dml(self, mock_open_conn, target):+ files = ["s3://bkt/backfill/events/2/year=2026/month=06/day=17/run1_0.parquet"]+ conn, cur = _make_catalog_conn_mock(post_condition_row=(0, 0, len(files)))+ mock_open_conn.return_value = conn++ _fixup_partition_values_for_added_files(MagicMock(), target, "events", "events", files)++ executed_sql = [str(call.args[0]) for call in cur.execute.call_args_list]+ # Session advisory lock is acquired OUTSIDE the txn (the very first SQL)+ # so retry backoffs don't sit idle-in-transaction. SET LOCAL bounds come+ # immediately after, inside the txn, before any DML.+ assert "pg_try_advisory_lock" in executed_sql[0]+ assert "SET LOCAL statement_timeout" in executed_sql[1]+ assert "SET LOCAL lock_timeout" in executed_sql[2]+ # Nothing touches the file_partition_value table before the lock is held.+ assert not any("file_partition_value" in s for s in executed_sql[:3])+ # Lock is released at the end (best-effort, via finally).+ assert "pg_advisory_unlock" in executed_sql[-1]++ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_runtime_spec_mismatch_raises(self, mock_open_conn, target):+ files = ["s3://bkt/backfill/events/2/year=2026/month=06/day=17/run1_0.parquet"]+ # Live catalog returns only (year, month) for an events table that expects+ # (year, month, day) — the fix-up must fail before any DML.+ # post_condition_row never reached (spec mismatch raises earlier); pass a dummy.+ conn, cur = _make_catalog_conn_mock(spec_rows=[(0, "year"), (1, "month")], post_condition_row=(0, 0, 0))+ mock_open_conn.return_value = conn++ with pytest.raises(RuntimeError, match="live catalog spec for posthog.events"):+ _fixup_partition_values_for_added_files(MagicMock(), target, "events", "events", files)++ executed_sql = [str(call.args[0]) for call in cur.execute.call_args_list]+ assert not any("DELETE FROM" in s for s in executed_sql)+ assert not any("INSERT INTO" in s for s in executed_sql)++ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_post_condition_failure_raises(self, mock_open_conn, target):+ files = ["s3://bkt/backfill/events/2/year=2026/month=06/day=17/run1_0.parquet"]+ # Post-condition returns 1 wrong-indexes row → must raise.+ conn, _cur = _make_catalog_conn_mock(post_condition_row=(1, 0, 1))+ mock_open_conn.return_value = conn++ with pytest.raises(RuntimeError, match="post-condition failed"):+ _fixup_partition_values_for_added_files(MagicMock(), target, "events", "events", files)++ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_unique_partition_info_required(self, mock_open_conn, target):+ files = ["s3://bkt/backfill/events/2/year=2026/month=06/day=17/run1_0.parquet"]+ # Two live partition_info rows for the same table → ambiguous → fail loud.+ # post_condition_row never reached (partition_info-cardinality check raises earlier).+ conn, _cur = _make_catalog_conn_mock(partition_info_rows=[(760, 761), (760, 999)], post_condition_row=(0, 0, 0))+ mock_open_conn.return_value = conn++ with pytest.raises(RuntimeError, match="expected exactly one live partition_info"):+ _fixup_partition_values_for_added_files(MagicMock(), target, "events", "events", files)++ @patch("posthog.dags.events_backfill_to_duckling.time.sleep", lambda _: None)+ @patch("posthog.dags.events_backfill_to_duckling._open_catalog_conn")+ def test_advisory_lock_exhaustion_raises(self, mock_open_conn, target):+ files = ["s3://bkt/backfill/events/2/year=2026/month=06/day=17/run1_0.parquet"]+ # Lock acquisition never succeeds within the retry budget.+ cur = MagicMock()+ cur.fetchone.side_effect = [(False,)] * 100 # plenty for the retry loop+ cur.__enter__.return_value = cur+ cur.__exit__.return_value = None+ conn = MagicMock()+ conn.cursor.return_value = cur+ conn.__enter__.return_value = conn+ conn.__exit__.return_value = None+ mock_open_conn.return_value = conn++ with pytest.raises(RuntimeError, match="could not acquire .* advisory lock"):+ _fixup_partition_values_for_added_files(MagicMock(), target, "events", "events", files)+++class TestRegisterTriggersFixup:+ @parameterized.expand(+ [+ ("events", register_files_with_duckling, "events"),+ ("persons", register_persons_files_with_duckling, "persons"),+ ]+ )+ @patch("posthog.dags.events_backfill_to_duckling._fixup_partition_values_for_added_files")+ @patch("posthog.dags.events_backfill_to_duckling._ducklake_file_partition_value_fixup_enabled", return_value=True)+ def test_fixup_called_with_registered_paths_when_enabled(+ self, _label, register_fn, kind, _mock_enabled, mock_fixup+ ):+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ files = [f"s3://bkt/backfill/{kind}/2/year=2026/month=06/day=17/run1_{i}.parquet" for i in range(3)]+ conn, _cur = _mock_glob_conn(files)+ config = DucklingBackfillConfig()++ register_fn(MagicMock(), target, "s3://bkt/.../run1_*.parquet", config, conn)++ assert mock_fixup.call_count == 1+ # Positional signature: (context, target, table_kind, table_name, file_paths).+ # Pin the non-context args; context is a MagicMock so we don't compare it.+ passed_target, passed_kind, passed_table_name, passed_files = mock_fixup.call_args.args[1:]+ assert passed_target == target+ assert passed_kind == kind+ # Unsuffixed: actual table name equals the kind (target defaults events_table="events").+ assert passed_table_name == kind+ assert passed_files == files++ @parameterized.expand(+ [+ (+ "events_suffixed",+ register_files_with_duckling,+ "events",+ "events_acme",+ {"events_table": "events_acme"},+ ),+ (+ "persons_suffixed",+ register_persons_files_with_duckling,+ "persons",+ "persons_acme",+ {"persons_table": "persons_acme"},+ ),+ ]+ )+ @patch("posthog.dags.events_backfill_to_duckling._fixup_partition_values_for_added_files")+ @patch("posthog.dags.events_backfill_to_duckling._ducklake_file_partition_value_fixup_enabled", return_value=True)+ def test_fixup_passes_suffixed_table_name(+ self, _label, register_fn, kind, expected_table_name, target_overrides, _mock_enabled, mock_fixup+ ):+ # When DuckgresServerTeam.table_suffix is set, target.{events,persons}_table+ # carries the suffixed name. The fix-up trigger must pass that actual+ # name through so the catalog lookup targets the right table.+ target = DucklingTarget(+ team_id=2,+ organization_id="org-1",+ bucket="bkt",+ bucket_region="us-east-1",+ **target_overrides,+ )+ files = [f"s3://bkt/backfill/{kind}/2/year=2026/month=06/day=17/run1_0.parquet"]+ conn, _cur = _mock_glob_conn(files)+ config = DucklingBackfillConfig()++ register_fn(MagicMock(), target, "s3://bkt/.../run1_*.parquet", config, conn)++ passed_kind, passed_table_name = mock_fixup.call_args.args[2:4]+ assert passed_kind == kind+ assert passed_table_name == expected_table_name++ @parameterized.expand(+ [+ ("events", register_files_with_duckling),+ ("persons", register_persons_files_with_duckling),+ ]+ )+ @patch("posthog.dags.events_backfill_to_duckling._fixup_partition_values_for_added_files")+ @patch("posthog.dags.events_backfill_to_duckling._ducklake_file_partition_value_fixup_enabled", return_value=False)+ def test_fixup_skipped_when_flag_disabled(self, _label, register_fn, _mock_enabled, mock_fixup):+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ files = ["s3://bkt/backfill/events/2/year=2026/month=06/day=17/run1_0.parquet"]+ conn, _cur = _mock_glob_conn(files)+ config = DucklingBackfillConfig()++ register_fn(MagicMock(), target, "s3://bkt/.../run1_*.parquet", config, conn)++ mock_fixup.assert_not_called()++ @parameterized.expand(+ [+ ("events", register_files_with_duckling),+ ("persons", register_persons_files_with_duckling),+ ]+ )+ @patch("posthog.dags.events_backfill_to_duckling._fixup_partition_values_for_added_files")+ @patch("posthog.dags.events_backfill_to_duckling._ducklake_file_partition_value_fixup_enabled", return_value=True)+ def test_fixup_skipped_when_no_files_registered(self, _label, register_fn, _mock_enabled, mock_fixup):+ # Empty glob → no ducklake_add_data_files calls → no fixup either.+ target = DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")+ conn, _cur = _mock_glob_conn([])+ config = DucklingBackfillConfig()++ register_fn(MagicMock(), target, "s3://bkt/.../run1_*.parquet", config, conn)++ mock_fixup.assert_not_called()++# Column SELECT used to synthesize events Parquet files for the round-trip test.def _events_rows_select(n_rows, uuid_prefix, ts):return f"""