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(data-warehouse): stop typeform responses syncs re-walking full history (#63236)

Tom Owers58b1e7a99af1
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/posthog/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
index 3b8810e7a556..eefdd6e28125 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
@@ -82,35 +82,40 @@ def _realign_decimal_buffers(table: pa.Table) -> pa.Table:
return pa.table(new_columns, schema=table.schema)
-def _first_per_pk_table(pa_table: pa.Table, pk_columns: list[str]) -> pa.Table:
- """Return a table containing only the first row per PK tuple (in original row order).
-
- Used when closing existing "current" rows during SCD2 append: we pass a
- deduplicated table to the merge so that only one source row matches each
- target row, avoiding ambiguous multi-match merge semantics.
+def _first_per_pk_table(
+ pa_table: pa.Table, pk_columns: list[str], keep: Literal["first", "last"] = "first"
+) -> pa.Table:
+ """Return a table containing only one row per PK tuple (in original row order).
+
+ `keep` picks which occurrence survives: "first" is used when closing existing
+ "current" rows during SCD2 append; "last" is used to dedupe upsert batches, where
+ the latest occurrence of a key carries the freshest data. Either way the merge
+ receives at most one source row per key, avoiding ambiguous multi-match merge
+ semantics (and the duplicate inserts `when_not_matched_insert_all` would produce).
"""
if not pk_columns or pa_table.num_rows == 0:
return pa_table
# Strategy: tag every row with its position, group by PK, and for each PK
- # take the smallest position. That position is the first time we saw that PK.
- # Sorting those positions at the end restores the original row order.
+ # take the smallest (or largest) position — the first (or last) time we saw
+ # that PK. Sorting those positions at the end restores the original row order.
#
# We use numpy for the final sort because pyarrow's type stubs for
# `pc.sort_indices` / `Array.take` are currently broken — numpy's stubs work.
idx_col_name = "__ph_cdc_row_idx"
+ aggregate = "min" if keep == "first" else "max"
# 1. Add a row-position column: [0, 1, 2, ..., n-1]
indexed = pa_table.append_column(idx_col_name, pa.array(range(pa_table.num_rows), type=pa.int64()))
- # 2. Group by PK, keeping only the smallest position per PK (= first occurrence)
- grouped = indexed.group_by(pk_columns).aggregate([(idx_col_name, "min")])
+ # 2. Group by PK, keeping only one position per PK
+ grouped = indexed.group_by(pk_columns).aggregate([(idx_col_name, aggregate)])
# 3. Sort those positions ascending so the output mirrors the input row order
- first_indices = np.sort(grouped.column(f"{idx_col_name}_min").to_numpy())
+ kept_indices = np.sort(grouped.column(f"{idx_col_name}_{aggregate}").to_numpy())
# 4. Materialize the rows at those positions from the original table
- return pa_table.take(first_indices)
+ return pa_table.take(kept_indices)
class DeltaTableHelper:
@@ -232,6 +237,25 @@ class DeltaTableHelper:
return await asyncio.to_thread(delta_table.file_uris)
+ async def _dedupe_incremental_batch(
+ self, data: pa.Table, primary_keys: Sequence[Any], use_partitioning: bool
+ ) -> pa.Table:
+ """Drop all but the last occurrence of each PK (+ partition) tuple in a batch."""
+ dedupe_keys = [n for x in primary_keys if (n := normalize_column_name(x)) in data.column_names]
+ if not dedupe_keys:
+ return data
+ if use_partitioning:
+ dedupe_keys.append(PARTITION_KEY)
+
+ deduped = _first_per_pk_table(data, dedupe_keys, keep="last")
+ dropped = data.num_rows - deduped.num_rows
+ if dropped > 0:
+ await self._logger.awarning(
+ f"write_to_deltalake: dropped {dropped} duplicate primary-key rows "
+ f"(keys={dedupe_keys}) from a batch of {data.num_rows} before writing"
+ )
+ return deduped
+
async def write_to_deltalake(
self,
data: pa.Table,
@@ -264,6 +288,14 @@ class DeltaTableHelper:
deltalake.CommitProperties(custom_metadata=commit_metadata) if commit_metadata else None
)
+ if write_type == "incremental" and primary_keys:
+ # Sources can emit the same key twice in one batch (re-listed parents, retried
+ # pages, genuinely non-unique upstream ids). The merge treats PK (+ partition)
+ # as row identity, and duplicates on the source side either error the merge or
+ # get double-inserted by `when_not_matched_insert_all` — after which every later
+ # merge multi-matches those rows and blows up. Keep only the last occurrence.
+ data = await self._dedupe_incremental_batch(data, primary_keys, use_partitioning)
+
if write_type == "incremental" and delta_table is not None and not self._is_first_sync:
if not primary_keys or len(primary_keys) == 0:
raise Exception("Primary key required for incremental syncs")
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py b/posthog/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
index 69c3e495d7c1..eaf90ad8f5ab 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
@@ -15,6 +15,7 @@ from parameterized import parameterized
from posthog.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY
from posthog.temporal.data_imports.pipelines.pipeline.delta_table_helper import (
DeltaTableHelper,
+ _first_per_pk_table,
_realign_decimal_buffers,
)
from posthog.temporal.data_imports.pipelines.pipeline.utils import evolve_pyarrow_schema
@@ -372,6 +373,70 @@ class TestLegacyDltTableReconciliation:
assert set(final.column("id").to_pylist()) == {1, 2, 3}
+class TestIncrementalBatchDeduplication:
+ """Duplicate PKs in a source batch must never reach the Delta write.
+
+ `when_not_matched_insert_all` inserts every unmatched source row, so a batch with a
+ repeated PK seeds duplicate rows in the table; every later merge then multi-matches
+ those rows and the join blows up (the OOM loop seen with sources whose primary keys
+ aren't actually unique).
+ """
+
+ @parameterized.expand(
+ [
+ ("keep_first", "first", ["a1", "b1"]),
+ ("keep_last", "last", ["a2", "b1"]),
+ ]
+ )
+ def test_first_per_pk_table_keep_modes(self, _name, keep, expected_names):
+ table = pa.table({"id": [1, 1, 2], "name": ["a1", "a2", "b1"]})
+
+ result = _first_per_pk_table(table, ["id"], keep=keep).sort_by("id")
+
+ assert result.column("id").to_pylist() == [1, 2]
+ assert result.column("name").to_pylist() == expected_names
+
+ @pytest.mark.asyncio
+ async def test_incremental_merge_dedupes_duplicate_source_rows(self, tmp_path: Path) -> None:
+ delta_path = str(tmp_path / "table")
+ deltalake.write_deltalake(delta_path, pa.table({"id": [1], "name": ["old"]}))
+
+ helper = _make_local_helper(delta_path)
+ # id=2 appears twice in one batch — without dedup both copies get inserted.
+ batch = pa.table({"id": [1, 2, 2], "name": ["updated", "first_copy", "second_copy"]})
+
+ result = await helper.write_to_deltalake(
+ data=batch,
+ write_type="incremental",
+ should_overwrite_table=False,
+ primary_keys=["id"],
+ )
+
+ final = result.to_pyarrow_table().sort_by("id")
+ assert final.column("id").to_pylist() == [1, 2]
+ # The last occurrence of a duplicated key carries the freshest data.
+ assert final.column("name").to_pylist() == ["updated", "second_copy"]
+ cast(AsyncMock, helper._logger.awarning).assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_first_sync_append_dedupes_duplicate_source_rows(self, tmp_path: Path) -> None:
+ delta_path = str(tmp_path / "table")
+
+ helper = _make_local_helper(delta_path)
+ batch = pa.table({"id": [1, 1], "name": ["first_copy", "second_copy"]})
+
+ result = await helper.write_to_deltalake(
+ data=batch,
+ write_type="incremental",
+ should_overwrite_table=False,
+ primary_keys=["id"],
+ )
+
+ final = result.to_pyarrow_table()
+ assert final.column("id").to_pylist() == [1]
+ assert final.column("name").to_pylist() == ["second_copy"]
+
+
class TestRealignDecimalBuffers:
"""delta-rs aborts the worker on 8-byte-aligned Decimal128 buffers; we realign them
to pyarrow's 64-byte allocator before any Delta write. See delta-io/delta-rs#3884."""
diff --git a/posthog/temporal/data_imports/sources/typeform/settings.py b/posthog/temporal/data_imports/sources/typeform/settings.py
index 72553da30e8d..89621afc8f94 100644
--- a/posthog/temporal/data_imports/sources/typeform/settings.py
+++ b/posthog/temporal/data_imports/sources/typeform/settings.py
@@ -56,9 +56,14 @@ TYPEFORM_ENDPOINTS: dict[str, TypeformEndpointConfig] = {
incremental_fields=[SUBMITTED_AT_INCREMENTAL],
default_incremental_field="submitted_at",
partition_key="submitted_at",
- primary_key="token",
+ # `token` alone is not a safe identity: the table aggregates responses across every
+ # form, and Typeform only documents the token as the id of a response within a form.
+ primary_key=["form_id", "token"],
page_size=1000,
- sort_mode="asc",
+ # Typeform returns responses newest-first (`submitted_at,desc` is the API default and
+ # `before` token pagination can't be combined with `sort`), so the pipeline must use
+ # descending-order incremental bookkeeping.
+ sort_mode="desc",
fanout=DependentEndpointConfig(
parent_name="forms",
resolve_param="form_id",
diff --git a/posthog/temporal/data_imports/sources/typeform/tests/test_typeform.py b/posthog/temporal/data_imports/sources/typeform/tests/test_typeform.py
index d15f162b0a0d..5ff7ff9f35e9 100644
--- a/posthog/temporal/data_imports/sources/typeform/tests/test_typeform.py
+++ b/posthog/temporal/data_imports/sources/typeform/tests/test_typeform.py
@@ -102,6 +102,40 @@ class TestTypeformTransport:
assert "before" not in request_b.params
assert request_b.params["since"] == "2026-03-01"
+ @parameterized.expand(
+ [
+ # Whole page predates the watermark — everything further back is already synced.
+ ("entire_page_older", "2026-03-01T00:00:00Z", "2026-02-27T10:00:00Z", "2026-02-20T10:00:00Z", False),
+ # Newest row in the page is still at/after the watermark — keep walking back.
+ ("page_straddles_watermark", "2026-03-01T00:00:00Z", "2026-03-02T10:00:00Z", "2026-02-20T10:00:00Z", True),
+ # No watermark (first sync) — full history walk continues.
+ (None, None, "2026-02-27T10:00:00Z", "2026-02-20T10:00:00Z", True),
+ ]
+ )
+ def test_responses_paginator_stops_once_page_is_older_than_watermark(
+ self, _name, watermark, newest_submitted_at, oldest_submitted_at, expected_has_next
+ ) -> None:
+ paginator = TypeformResponsesPaginator(stop_when_older_than=watermark)
+ response = Mock()
+
+ paginator.update_state(
+ response,
+ data=[
+ {"token": "tok_1", "submitted_at": newest_submitted_at},
+ {"token": "tok_2", "submitted_at": oldest_submitted_at},
+ ],
+ )
+
+ assert paginator.has_next_page is expected_has_next
+
+ def test_responses_paginator_watermark_ignores_rows_without_submitted_at(self) -> None:
+ paginator = TypeformResponsesPaginator(stop_when_older_than="2026-03-01T00:00:00Z")
+ response = Mock()
+
+ paginator.update_state(response, data=[{"token": "tok_1"}, {"token": "tok_2", "submitted_at": None}])
+
+ assert paginator.has_next_page is False
+
def test_validated_api_base_url_rejects_unknown(self) -> None:
with pytest.raises(
ValueError,
@@ -266,6 +300,9 @@ class TestTypeformTransport:
rows = list(cast(Any, response.items()))
assert rows == [{"response_id": "resp_1", "form_id": "form_1"}]
assert response.partition_mode == "datetime"
+ # Tokens are only unique within a form, and the API returns responses newest-first.
+ assert response.primary_keys == ["form_id", "token"]
+ assert response.sort_mode == "desc"
@patch("posthog.temporal.data_imports.sources.typeform.typeform.build_dependent_resource")
def test_typeform_source_responses_passes_items_data_selector_to_fanout(
@@ -288,6 +325,35 @@ class TestTypeformTransport:
assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], TypeformFormsPaginator)
assert isinstance(kwargs["child_endpoint_extra"]["paginator"], TypeformResponsesPaginator)
+ @parameterized.expand(
+ [
+ # Incremental sync with a watermark — paginator gets the stop floor.
+ ("incremental_with_watermark", True, datetime(2026, 3, 1, tzinfo=UTC), "2026-03-01T00:00:00Z"),
+ # First sync (no watermark) — full history walk.
+ ("first_sync", True, None, None),
+ # Non-incremental sync — no floor even if a stale value exists.
+ ("not_incremental", False, datetime(2026, 3, 1, tzinfo=UTC), None),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.typeform.typeform.build_dependent_resource")
+ def test_typeform_source_responses_watermark_wiring(
+ self, _name, should_use_incremental_field, last_value, expected_floor, mock_build_dependent_resource
+ ) -> None:
+ mock_build_dependent_resource.return_value = iter([])
+
+ typeform_source(
+ auth_token="token",
+ api_base_url="https://api.typeform.com",
+ endpoint="responses",
+ team_id=1,
+ job_id="job-1",
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+
+ paginator = mock_build_dependent_resource.call_args.kwargs["child_endpoint_extra"]["paginator"]
+ assert paginator._stop_when_older_than == expected_floor
+
def test_typeform_source_rejects_unknown_api_base_url(self) -> None:
with pytest.raises(
ValueError,
diff --git a/posthog/temporal/data_imports/sources/typeform/typeform.py b/posthog/temporal/data_imports/sources/typeform/typeform.py
index 2845723297b0..464ca2bfc2de 100644
--- a/posthog/temporal/data_imports/sources/typeform/typeform.py
+++ b/posthog/temporal/data_imports/sources/typeform/typeform.py
@@ -101,9 +101,19 @@ class TypeformFormsPaginator(BasePaginator):
class TypeformResponsesPaginator(BasePaginator):
- def __init__(self) -> None:
+ """Token-cursor paginator for /forms/{form_id}/responses.
+
+ Typeform rejects mixing `before` token pagination with the `since`/`until` datetime
+ window, so only the first page is windowed; later pages walk back through history via
+ `before`. Without a stop condition that walk re-fetches a form's entire response
+ history on every incremental sync, so when a watermark is known we stop as soon as a
+ whole page is older than it.
+ """
+
+ def __init__(self, stop_when_older_than: str | None = None) -> None:
super().__init__()
self._cursor: str | None = None
+ self._stop_when_older_than = stop_when_older_than
def init_request(self, request: Request) -> None:
self._cursor = None
@@ -123,6 +133,17 @@ class TypeformResponsesPaginator(BasePaginator):
self._cursor = None
self._has_next_page = self._cursor is not None
+ # Responses arrive newest-first; once an entire page predates the incremental
+ # watermark, everything further back has already been synced. Timestamps are
+ # RFC3339 UTC strings, so lexicographic comparison is chronological.
+ if self._has_next_page and self._stop_when_older_than is not None:
+ newest_in_page = max(
+ (item.get("submitted_at") or "" for item in data if isinstance(item, dict)),
+ default="",
+ )
+ if newest_in_page < self._stop_when_older_than:
+ self._has_next_page = False
+
def update_request(self, request: Request) -> None:
if self._cursor:
if request.params is None:
@@ -278,6 +299,14 @@ def typeform_source(
endpoint_config = TYPEFORM_ENDPOINTS[endpoint]
base_api_url = _validated_api_base_url(api_base_url)
+ incremental_watermark: str | None = None
+ if (
+ should_use_incremental_field
+ and db_incremental_field_last_value is not None
+ and (incremental_field or endpoint_config.default_incremental_field) == "submitted_at"
+ ):
+ incremental_watermark = _start_param_for_typeform(db_incremental_field_last_value)
+
if endpoint_config.fanout:
dependent_resource = cast(
Iterable[Any],
@@ -299,7 +328,7 @@ def typeform_source(
"data_selector": "items",
},
child_endpoint_extra={
- "paginator": TypeformResponsesPaginator(),
+ "paginator": TypeformResponsesPaginator(stop_when_older_than=incremental_watermark),
"data_selector": "items",
},
),