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.

feat(data-warehouse): checkpoint the postgres keyset seek on uuid keys (#112720)

Tom Owers51cfa7ce3687
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index 34f98278e8d1..aa7902931571 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -2460,6 +2460,16 @@ def _column_is_not_null(table: Table[PostgreSQLColumn], column_name: str) -> boo
return any(is_not_null(column.nullable) for column in table.columns if column.name == column_name)
+def _is_uuid_column(table: Table[PostgreSQLColumn], column_name: str) -> bool:
+ """Whether a keyset checkpoint can hold `column_name` as a uuid.
+
+ The Arrow type of a uuid column is string, which a checkpoint refuses because the order of text
+ depends on a collation. Postgres compares uuid values byte by byte, with no collation. The value
+ goes into the checkpoint as text, and Postgres reads that text back as the same uuid.
+ """
+ return any(column.data_type.lower() == "uuid" for column in table.columns if column.name == column_name)
+
+
def _build_keyset_query(
schema: str,
table_name: str,
@@ -2840,7 +2850,11 @@ def resolve_postgres_keyset(
# Were it reached, the SELECT would omit the key and the seek would fail looking it up in the
# cursor description, so fall back to the server cursor rather than crash the read.
return PostgresKeyset(reason=f"primary_key_not_projected:{missing[0]}")
- unorderable = [key for key in primary_keys if not is_orderable_keyset_type(arrow_schema.field(key).type)]
+ unorderable = [
+ key
+ for key in primary_keys
+ if not is_orderable_keyset_type(arrow_schema.field(key).type) and not _is_uuid_column(full_table, key)
+ ]
if unorderable:
# Seeking in-process on this key stays fine: one connection, one collation, one process. What
# it cannot do is survive the trip through Redis, where the ordering assumption would have to
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_keyset_key_types.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_keyset_key_types.py
new file mode 100644
index 000000000000..af9b5e1abeea
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_keyset_key_types.py
@@ -0,0 +1,74 @@
+import uuid
+from contextlib import contextmanager
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import Table
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import (
+ KeysetResumeState,
+ keyset_last_key,
+ keyset_state,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (
+ PostgreSQLColumn,
+ resolve_postgres_keyset,
+)
+
+
+def _resolve(columns: list[tuple[str, str]], primary_keys: list[str]) -> Any:
+ table = Table(
+ name="orders",
+ parents=("public",),
+ columns=[PostgreSQLColumn(name=name, data_type=data_type, nullable=False) for name, data_type in columns],
+ )
+ return resolve_postgres_keyset(
+ primary_keys=primary_keys,
+ arrow_schema=table.to_arrow_schema(),
+ used_id_pk_fallback=False,
+ has_duplicate_primary_keys=False,
+ is_partitioned=False,
+ should_use_incremental_field=False,
+ is_xmin=False,
+ is_duckdb=False,
+ full_table=table,
+ )
+
+
+ "columns,primary_keys,checkpointable,reason",
+ [
+ ([("id", "uuid")], ["id"], True, None),
+ ([("id", "UUID")], ["id"], True, None),
+ ([("tenant", "integer"), ("id", "uuid")], ["tenant", "id"], True, None),
+ ([("id", "bigint")], ["id"], True, None),
+ ([("id", "text")], ["id"], False, "non_orderable_type:string"),
+ ([("tenant", "uuid"), ("slug", "character varying")], ["tenant", "slug"], False, "non_orderable_type:string"),
+ ([("id", "uuid"), ("note", "text")], ["id"], True, None),
+ ],
+)
+def test_uuid_key_can_checkpoint_and_text_key_cannot(columns, primary_keys, checkpointable, reason):
+ keyset = _resolve(columns, primary_keys)
+ assert (keyset.columns, keyset.checkpointable, keyset.reason) == (primary_keys, checkpointable, reason)
+
+
+def test_uuid_key_returns_from_the_checkpoint_as_text():
+ store: dict[str, str] = {}
+ redis = MagicMock()
+ redis.set.side_effect = lambda key, value, ex=None: store.__setitem__(key, value)
+ redis.get.side_effect = store.get
+
+ class _Manager(ResumableSourceManager[KeysetResumeState]):
+ @contextmanager
+ def _get_redis(self):
+ yield redis
+
+ manager = _Manager(MagicMock(team_id=1, job_id="job-1"), KeysetResumeState)
+ key = (7, uuid.UUID(int=0xABCDEF << 64))
+
+ manager.save_state(keyset_state(key))
+ manager.commit()
+
+ assert keyset_last_key(manager.load_state(), key_length=2) == (7, str(key[1]))