Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(dags): resolve ducklake schema via ducklake_schema join in fpv fix-up (#67615)

James Greenhill9b2501722599
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index fc9e1d674e2c..abcc6207fe0d 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -1777,9 +1777,11 @@ def _fixup_partition_values_for_added_files(
"""
SELECT t.table_id, pi.partition_id
FROM public.ducklake_table t
+ JOIN public.ducklake_schema s
+ ON s.schema_id = t.schema_id AND s.end_snapshot IS NULL
JOIN public.ducklake_partition_info pi
ON pi.table_id = t.table_id AND pi.end_snapshot IS NULL
- WHERE t.schema_name = 'posthog'
+ WHERE s.schema_name = 'posthog'
AND t.table_name = %s
AND t.end_snapshot IS NULL
""",
@@ -1861,7 +1863,7 @@ def _fixup_partition_values_for_added_files(
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[]
+ '{{}}'::bigint[]
) AS indexes,
COUNT(*) FILTER (WHERE file_partition_value.partition_value IS NULL) AS nulls
FROM public.ducklake_data_file df
@@ -1874,7 +1876,7 @@ def _fixup_partition_values_for_added_files(
GROUP BY df.data_file_id
)
SELECT
- COUNT(*) FILTER (WHERE indexes IS DISTINCT FROM %s::int[]) AS wrong_indexes,
+ COUNT(*) FILTER (WHERE indexes IS DISTINCT FROM %s::bigint[]) AS wrong_indexes,
COUNT(*) FILTER (WHERE nulls > 0) AS null_values,
COUNT(*) AS total
FROM file_partition_value_state
diff --git a/posthog/dags/tests/test_events_backfill_to_duckling.py b/posthog/dags/tests/test_events_backfill_to_duckling.py
index 86775753f0c8..a48b01b88166 100644
--- a/posthog/dags/tests/test_events_backfill_to_duckling.py
+++ b/posthog/dags/tests/test_events_backfill_to_duckling.py
@@ -1,10 +1,24 @@
+import re
+import uuid
+from collections.abc import Iterator
+from contextlib import closing
from dataclasses import dataclass
+from typing import Any
+import pytest
from unittest.mock import patch
+from django.db import connection as django_connection
+
+import psycopg
+from dagster import build_asset_context
from parameterized import parameterized
-from posthog.dags.events_backfill_to_duckling import _resolve_duckling_target
+from posthog.dags.events_backfill_to_duckling import (
+ DucklingTarget,
+ _fixup_partition_values_for_added_files,
+ _resolve_duckling_target,
+)
@dataclass
@@ -64,7 +78,162 @@ class TestResolveDucklingTarget:
]
)
def test_raises_when_nothing_can_name_the_bucket(self, _name: str, server: "_FakeRow | None") -> None:
- import pytest
-
with pytest.raises(ValueError, match="No S3 bucket resolvable"):
self._resolve(server=server, cp_bucket=None)
+
+
+# Verbatim from the DuckLake specification (docs/stable/specification/tables/overview.html),
+# limited to the tables the ducklake_file_partition_value fix-up touches. The fix-up's SQL is
+# validated against this real DDL — a query referencing a column the spec doesn't define
+# (the UndefinedColumn class of bug) fails here instead of in production.
+_DUCKLAKE_CATALOG_DDL = [
+ "CREATE TABLE public.ducklake_schema (schema_id BIGINT PRIMARY KEY, schema_uuid UUID, begin_snapshot BIGINT, end_snapshot BIGINT, schema_name VARCHAR, path VARCHAR, path_is_relative BOOLEAN)",
+ "CREATE TABLE public.ducklake_table (table_id BIGINT, table_uuid UUID, begin_snapshot BIGINT, end_snapshot BIGINT, schema_id BIGINT, table_name VARCHAR, path VARCHAR, path_is_relative BOOLEAN)",
+ "CREATE TABLE public.ducklake_partition_info (partition_id BIGINT, table_id BIGINT, begin_snapshot BIGINT, end_snapshot BIGINT)",
+ 'CREATE TABLE public.ducklake_partition_column (partition_id BIGINT, table_id BIGINT, partition_key_index BIGINT, column_id BIGINT, "transform" VARCHAR)',
+ "CREATE TABLE public.ducklake_data_file (data_file_id BIGINT PRIMARY KEY, table_id BIGINT, begin_snapshot BIGINT, end_snapshot BIGINT, file_order BIGINT, path VARCHAR, path_is_relative BOOLEAN, file_format VARCHAR, record_count BIGINT, file_size_bytes BIGINT, footer_size BIGINT, row_id_start BIGINT, partition_id BIGINT, encryption_key VARCHAR, mapping_id BIGINT, partial_max BIGINT)",
+ "CREATE TABLE public.ducklake_file_partition_value (data_file_id BIGINT, table_id BIGINT, partition_key_index BIGINT, partition_value VARCHAR)",
+]
+
+_DUCKLAKE_CATALOG_TABLES = [
+ match.group(1)
+ for stmt in _DUCKLAKE_CATALOG_DDL
+ for match in [re.search(r"CREATE TABLE (public\.\w+)", stmt)]
+ if match
+]
+
+
+def _connect_test_db() -> psycopg.Connection[Any]:
+ settings_dict = django_connection.settings_dict
+ return psycopg.connect(
+ host=settings_dict["HOST"] or "localhost",
+ port=int(settings_dict["PORT"] or 5432),
+ dbname=settings_dict["NAME"],
+ user=settings_dict["USER"],
+ password=settings_dict["PASSWORD"],
+ autocommit=True,
+ )
+
+
+def _drop_catalog_tables(conn: psycopg.Connection[Any]) -> None:
+ with conn.cursor() as cur:
+ cur.execute(f"DROP TABLE IF EXISTS {', '.join(_DUCKLAKE_CATALOG_TABLES)}")
+
+
+def ducklake_catalog(django_db_setup: None) -> Iterator[psycopg.Connection[Any]]:
+ with closing(_connect_test_db()) as conn:
+ # Pre-drop: leftovers from an interrupted run survive --reuse-db.
+ _drop_catalog_tables(conn)
+ with conn.cursor() as cur:
+ for stmt in _DUCKLAKE_CATALOG_DDL:
+ cur.execute(stmt)
+ try:
+ yield conn
+ finally:
+ _drop_catalog_tables(conn)
+
+
+class TestFixupPartitionValuesForAddedFiles:
+ TABLE_ID = 10
+ PARTITION_ID = 100
+
+ def _seed_catalog(self, conn: psycopg.Connection[Any]) -> None:
+ with conn.cursor() as cur:
+ # A dropped-and-recreated 'posthog' schema: only the live row may resolve.
+ cur.executemany(
+ "INSERT INTO public.ducklake_schema VALUES (%s, %s, %s, %s, %s, %s, %s)",
+ [
+ (2, uuid.uuid4(), 1, 5, "posthog", "posthog/", True),
+ (1, uuid.uuid4(), 5, None, "posthog", "posthog/", True),
+ ],
+ )
+ cur.execute(
+ "INSERT INTO public.ducklake_table VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
+ (self.TABLE_ID, uuid.uuid4(), 1, None, 1, "events", "events/", True),
+ )
+ # A superseded partition_info generation next to the live one.
+ cur.executemany(
+ "INSERT INTO public.ducklake_partition_info VALUES (%s, %s, %s, %s)",
+ [(99, self.TABLE_ID, 1, 5), (self.PARTITION_ID, self.TABLE_ID, 5, None)],
+ )
+ cur.executemany(
+ "INSERT INTO public.ducklake_partition_column VALUES (%s, %s, %s, %s, %s)",
+ [
+ (self.PARTITION_ID, self.TABLE_ID, 0, 7, "year"),
+ (self.PARTITION_ID, self.TABLE_ID, 1, 7, "month"),
+ (self.PARTITION_ID, self.TABLE_ID, 2, 7, "day"),
+ ],
+ )
+ cur.executemany(
+ "INSERT INTO public.ducklake_data_file "
+ "(data_file_id, table_id, begin_snapshot, end_snapshot, path, path_is_relative, partition_id) "
+ "VALUES (%s, %s, %s, %s, %s, %s, %s)",
+ [
+ (1000, self.TABLE_ID, 5, None, self._path(day=5), True, self.PARTITION_ID),
+ (1001, self.TABLE_ID, 5, None, self._path(day=6), True, self.PARTITION_ID),
+ (1002, self.TABLE_ID, 5, None, self._path(day=7), True, self.PARTITION_ID),
+ ],
+ )
+ # File 1000 carries the upstream bug's signature (every value piled onto the
+ # highest key index); file 1001 has no rows at all; file 1002 is untargeted
+ # and correct — it must survive the fix-up untouched.
+ cur.executemany(
+ "INSERT INTO public.ducklake_file_partition_value VALUES (%s, %s, %s, %s)",
+ [
+ (1000, self.TABLE_ID, 2, "2025"),
+ (1000, self.TABLE_ID, 2, "1"),
+ (1000, self.TABLE_ID, 2, "5"),
+ (1002, self.TABLE_ID, 0, "2025"),
+ (1002, self.TABLE_ID, 1, "1"),
+ (1002, self.TABLE_ID, 2, "7"),
+ ],
+ )
+
+ @staticmethod
+ def _path(day: int) -> str:
+ return f"backfill/events/2/year=2025/month=01/day={day:02d}/part-00.parquet"
+
+ @staticmethod
+ def _partition_values(conn: psycopg.Connection[Any]) -> set[tuple[int, int, int, str]]:
+ with conn.cursor() as cur:
+ cur.execute(
+ "SELECT data_file_id, table_id, partition_key_index, partition_value "
+ "FROM public.ducklake_file_partition_value"
+ )
+ return {tuple(row) for row in cur.fetchall()}
+
+ def _run_fixup(self, file_paths: list[str]) -> None:
+ target = DucklingTarget(
+ team_id=2,
+ organization_id="org-1",
+ bucket="test-bucket",
+ bucket_region="us-east-1",
+ )
+ with patch(
+ "posthog.dags.events_backfill_to_duckling._open_catalog_conn",
+ side_effect=lambda _target: _connect_test_db(),
+ ):
+ _fixup_partition_values_for_added_files(build_asset_context(), target, "events", "events", file_paths)
+
+ def test_rebuilds_partition_values_from_paths(self, ducklake_catalog: psycopg.Connection[Any]) -> None:
+ self._seed_catalog(ducklake_catalog)
+
+ self._run_fixup([self._path(day=5), self._path(day=6)])
+
+ expected = {
+ (1000, self.TABLE_ID, 0, "2025"),
+ (1000, self.TABLE_ID, 1, "1"),
+ (1000, self.TABLE_ID, 2, "5"),
+ (1001, self.TABLE_ID, 0, "2025"),
+ (1001, self.TABLE_ID, 1, "1"),
+ (1001, self.TABLE_ID, 2, "6"),
+ (1002, self.TABLE_ID, 0, "2025"),
+ (1002, self.TABLE_ID, 1, "1"),
+ (1002, self.TABLE_ID, 2, "7"),
+ }
+ assert self._partition_values(ducklake_catalog) == expected
+
+ # Re-running over the same paths must converge to the same state (retry contract).
+ self._run_fixup([self._path(day=5), self._path(day=6)])
+ assert self._partition_values(ducklake_catalog) == expected