: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
feat(warehouse): add xmin read path for postgres source (#64721)
Daniel RCcb7f4139d9d0
diff --git a/posthog/temporal/data_imports/pipelines/common/extract.py b/posthog/temporal/data_imports/pipelines/common/extract.pyindex bf4c22a3187f..f4fdabfb156a 100644--- a/posthog/temporal/data_imports/pipelines/common/extract.py+++ b/posthog/temporal/data_imports/pipelines/common/extract.py@@ -340,6 +340,36 @@ async def finalize_desc_sort_incremental_value(await database_sync_to_async_pool(schema.update_incremental_field_value)(last_incremental_field_value)+async def advance_xmin_state(+ resource: SourceResponse,+ schema: "ExternalDataSchema",+ logger: FilteringBoundLogger,+ log_prefix: str = "",+) -> None:+ """Persist the xmin ceiling captured at sync start, once the run's data is durable.++ Persist-then-advance: the ceiling was captured before streaming and is stored only here, at+ completion, so a mid-run crash re-reads the window next time (the upsert on PK is idempotent).+ Deliberately not the per-batch MAX-of-observed advance, which would store the wrong value and is+ wraparound-unsafe for xmin.+ """+ if (+ not schema.is_xmin+ or resource.xmin_ceiling_xid is None+ or resource.xmin_ceiling_xid8 is None+ or resource.xmin_num_wraparound is None+ ):+ return++ await logger.adebug(f"{log_prefix}Advancing xmin cursor to ceiling {resource.xmin_ceiling_xid8}")+ await database_sync_to_async_pool(schema.refresh_from_db)()+ await database_sync_to_async_pool(schema.update_xmin_state)(+ ceiling_xid=resource.xmin_ceiling_xid,+ ceiling_xid8=resource.xmin_ceiling_xid8,+ num_wraparound=resource.xmin_num_wraparound,+ )++async def cdp_producer_clear_chunks(cdp_producer: CDPProducer):if await cdp_producer.should_produce_table():await cdp_producer.clear_s3_chunks()diff --git a/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline/pipeline.pyindex fffc450f1820..ae6b97f0b23c 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py@@ -15,6 +15,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.shutdown import ShutdownMonitorfrom posthog.temporal.data_imports.pipelines.common.extract import (+ advance_xmin_state,cdp_producer_clear_chunks,cleanup_memory,finalize_desc_sort_incremental_value,@@ -163,7 +164,9 @@ class PipelineNonDLT(Generic[ResumableData]):self._schema = schemaself._source = sourceself._table = table- self._is_incremental = schema.is_incremental or schema.is_webhook+ # xmin reads deltas and upserts on the primary key, so it writes incrementally too — never+ # as a full_refresh overwrite, which would wipe earlier data on the second (delta-only) sync.+ self._is_incremental = schema.is_incremental or schema.is_webhook or schema.is_xminself._delta_table_helper = DeltaTableHelper(self._resource_name, self._job, self._logger)self._resumable_source_manager = resumable_source_manager@@ -255,6 +258,8 @@ class PipelineNonDLT(Generic[ResumableData]):await self._post_run_operations(row_count=row_count)+ await advance_xmin_state(self._resource, self._schema, self._logger)+return {"should_trigger_cdp_producer": await self._cdp_producer.should_produce_table()}finally:# Help reduce the memory footprint of each job@@ -284,7 +289,7 @@ class PipelineNonDLT(Generic[ResumableData]):pa_table = _handle_null_columns_with_definitions(pa_table, self._resource)write_type: Literal["incremental", "full_refresh", "append"] = "full_refresh"- if self._schema.is_incremental or self._schema.is_webhook:+ if self._schema.is_incremental or self._schema.is_webhook or self._schema.is_xmin:write_type = "incremental"elif self._schema.is_append:write_type = "append"diff --git a/posthog/temporal/data_imports/pipelines/pipeline/typings.py b/posthog/temporal/data_imports/pipelines/pipeline/typings.pyindex 33d6fa13c2bb..301b9999b8c6 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/typings.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/typings.py@@ -59,6 +59,12 @@ class SourceResponse:rows_to_sync: Optional[int] = Nonehas_duplicate_primary_keys: Optional[bool] = None"""Whether incremental tables have non-unique primary keys"""+ xmin_ceiling_xid: Optional[int] = None+ """xmin syncs: bare 32-bit ceiling captured this run, persisted as the next run's lower bound."""+ xmin_ceiling_xid8: Optional[int] = None+ """xmin syncs: full 64-bit `xid8` ceiling, the durable wraparound-safe cursor."""+ xmin_num_wraparound: Optional[int] = None+ """xmin syncs: epoch (high 32 bits of `xmin_ceiling_xid8`) at this run's ceiling."""@dataclasses.dataclassdiff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.pyindex 37427e052c29..3d93b3a93dd2 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py@@ -11,6 +11,7 @@ from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URLfrom posthog.temporal.common.activity_context import current_workflow_id, current_workflow_run_idfrom posthog.temporal.common.shutdown import ShutdownMonitorfrom posthog.temporal.data_imports.pipelines.common.extract import (+ advance_xmin_state,cdp_producer_clear_chunks,cleanup_memory,finalize_desc_sort_incremental_value,@@ -107,7 +108,9 @@ class PipelineV3(Generic[ResumableData]):self._schema = schemaself._source = sourceself._table = table- self._is_incremental = schema.is_incremental or schema.is_webhook+ # xmin reads deltas and upserts on the primary key, so it writes incrementally too — never+ # as a full_refresh overwrite, which would wipe earlier data on the second (delta-only) sync.+ self._is_incremental = schema.is_incremental or schema.is_webhook or schema.is_xminself._delta_table_helper = DeltaTableHelper(self._resource_name, self._job, self._logger)@@ -116,7 +119,7 @@ class PipelineV3(Generic[ResumableData]):)sync_type: SyncTypeLiteral = "full_refresh"- if self._schema.is_incremental or self._schema.is_webhook:+ if self._schema.is_incremental or self._schema.is_webhook or self._schema.is_xmin:sync_type = "incremental"elif self._schema.is_append:sync_type = "append"@@ -384,6 +387,8 @@ class PipelineV3(Generic[ResumableData]):self._resource, self._schema, self._last_incremental_field_value, self._logger, log_prefix="V3 Pipeline: ")+ await advance_xmin_state(self._resource, self._schema, self._logger, log_prefix="V3 Pipeline: ")+if not self._schema.initial_sync_complete:await self._logger.adebug("V3 Pipeline: Setting initial_sync_complete on schema")await set_initial_sync_complete(schema_id=self._schema.id, team_id=self._job.team_id)diff --git a/posthog/temporal/data_imports/sources/postgres/exceptions.py b/posthog/temporal/data_imports/sources/postgres/exceptions.pyindex ccb850cb6ffa..2759b4beac57 100644--- a/posthog/temporal/data_imports/sources/postgres/exceptions.py+++ b/posthog/temporal/data_imports/sources/postgres/exceptions.py@@ -7,3 +7,12 @@ class CDCHandledExternally(Exception):CDC streaming schemas are handled by CDCExtractionWorkflow, not by theregular ExternalDataJobWorkflow pipeline."""+++class XminUnsupportedError(Exception):+ """Raised when an xmin sync targets a relation that can't support it.++ Deterministic (a server too old, or a partitioned parent), so the class name+ is listed in `PostgresSource.get_non_retryable_errors` to stop Temporal+ retrying into the same wall.+ """diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex 32476ba39fd7..5172c2689d1f 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -63,6 +63,7 @@ from posthog.temporal.data_imports.sources.common.sql.predicates_psycopg importrender_psycopg_row_filter_conditions,)from posthog.temporal.data_imports.sources.generated_configs import PostgresSourceConfig+from posthog.temporal.data_imports.sources.postgres.exceptions import XminUnsupportedErrorfrom posthog.temporal.data_imports.sources.postgres.partitioned_tables import (build_partition_query,get_estimated_row_count_for_partitioned_table as _get_estimated_row_count_for_partitioned_table,@@ -89,6 +90,12 @@ SYNC_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 minsMETADATA_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins+# Alias for the projected `xmin` system column on xmin syncs. `SELECT *` never returns system+# columns, so it must be projected explicitly; the alias also names the ORDER BY / WHERE cursor.+XMIN_PROJECTED_COLUMN = "_ph_xmin"+# xmin replication relies on `pg_snapshot_xmin` / `xid8`, both PG13+.+XMIN_MIN_SERVER_VERSION = 130000+# In-process retries for a recovery conflict before the abort (non-retryable, see source.py). The# read path counts these only once the chunk has shrunk to the floor._MAX_SETUP_RECOVERY_CONFLICT_RETRIES = 10@@ -860,6 +867,62 @@ def _rls_active_from_conn(return {}+def _xmin_capable_tables_from_conn(+ connection: psycopg.Connection,+ schema: str | None,+ names: list[str] | None,+) -> set[str]:+ """Display names of relations that can support an xmin sync.++ xmin needs a physical heap tuple (`relkind` `r`/`m` — ordinary tables and materialized views)+ and PG13+ (for `pg_snapshot_xmin`/`xid8`). Partitioned parents (`p`), plain views (`v`) and+ foreign tables (`f`) are excluded: the parent has no tuples of its own and a single global+ ceiling can't span its children's independent xid spaces.+ """+ try:+ if connection.info.server_version < XMIN_MIN_SERVER_VERSION:+ return set()+ with connection.cursor() as cursor:+ cursor.execute(+ sql.SQL("SET LOCAL statement_timeout = {timeout}").format(timeout=sql.Literal(1000 * 30)) # 30 secs+ )+ discovered_tables, _qualify_with_schema = _get_discovered_tables(cursor, schema, names)+ if not discovered_tables:+ return set()++ display_by_source = {+ (schema_name, table_name): display_name+ for display_name, (_source_catalog, schema_name, table_name) in discovered_tables.items()+ }+ wanted = sql.SQL(", ").join(+ sql.SQL("({}, {})").format(sql.Literal(schema_name), sql.Literal(table_name))+ for schema_name, table_name in display_by_source+ )+ query = sql.SQL("""+ SELECT n.nspname, c.relname+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ JOIN (VALUES {wanted}) AS want(schema_name, table_name)+ ON n.nspname::text = want.schema_name AND c.relname::text = want.table_name+ WHERE c.relkind IN ('r', 'm')+ """).format(wanted=wanted)++ cursor.execute(query)+ capable: set[str] = set()+ for nspname, relname in cursor.fetchall():+ display_name = display_by_source.get((nspname, relname))+ if display_name is not None:+ capable.add(display_name)+ return capable+ except Exception as e:+ # Best-effort like the PK/RLS/index lookups it runs alongside: losing the `supports_xmin`+ # hint just hides the option for this listing. A non-Postgres engine may lack `relkind`+ # semantics entirely, so degrade quietly.+ if not connection.closed and not connection.broken and not isinstance(e, psycopg.errors.InFailedSqlTransaction):+ structlog.get_logger().warning("Failed to detect xmin-capable tables for Postgres schemas", exc_info=e)+ return set()++def get_postgres_row_count(host: str,port: int,@@ -1335,6 +1398,91 @@ class SafeTimetzLoader(TimetzLoader):return _load_time_clamping_hour_24(super().load, data)+class XminBounds:+ """Bounded xmin window captured once at sync start (see §2.2/§2.3 of the design).++ `lower`/`upper` are bare 32-bit xids compared against tuple `xmin`. `ceiling_xid8` is the+ full 64-bit `pg_snapshot_xmin` we persist as the durable, wraparound-safe cursor; `num_wraparound`+ is its epoch (high 32 bits). `wraparound_or_range` selects the single-wrap `>= lower OR < upper`+ predicate instead of the steady-state `>= lower AND < upper`.+ """++ lower: int+ upper: int+ ceiling_xid8: int+ num_wraparound: int+ wraparound_or_range: bool+++def _capture_xmin_ceiling(+ cursor: psycopg.Cursor,+ stored_last_value: Optional[int],+ stored_num_wraparound: Optional[int],+ logger: FilteringBoundLogger,+) -> XminBounds:+ """Capture this run's xmin ceiling on the row-serving connection and derive the read window.++ The ceiling is `pg_snapshot_xmin(pg_current_snapshot())` — the lowest still-running xid — so+ every row with `xmin < ceiling` is committed as of the snapshot and in-flight transactions are+ excluded. Must run on the connection that serves rows (a replica's snapshot xmin lags the+ primary's), which is the autocommit setup cursor here.+ """+ server_version = cursor.connection.info.server_version+ if server_version < XMIN_MIN_SERVER_VERSION:+ raise XminUnsupportedError(+ f"xmin replication requires PostgreSQL 13 or newer (server reports {server_version}). "+ "Choose a different sync type for this table."+ )++ cursor.execute(sql.SQL("SELECT pg_snapshot_xmin(pg_current_snapshot())::text::bigint"))+ row = cursor.fetchone()+ if row is None or row[0] is None:+ raise XminUnsupportedError("Could not read the xmin snapshot ceiling from the source database.")+ ceiling_xid8 = int(row[0])+ ceiling_xid = ceiling_xid8 & 0xFFFFFFFF+ num_wraparound = ceiling_xid8 >> 32++ # First run (no stored cursor): read everything `< ceiling` once. `lower = 0` is below+ # FrozenTransactionId (2) so even frozen tuples are captured by the initial snapshot.+ if stored_last_value is None:+ return XminBounds(+ lower=0,+ upper=ceiling_xid,+ ceiling_xid8=ceiling_xid8,+ num_wraparound=num_wraparound,+ wraparound_or_range=False,+ )++ delta = num_wraparound - (stored_num_wraparound or 0)+ if delta == 0:+ return XminBounds(+ lower=int(stored_last_value),+ upper=ceiling_xid,+ ceiling_xid8=ceiling_xid8,+ num_wraparound=num_wraparound,+ wraparound_or_range=False,+ )+ if delta == 1:+ # Single wrap: changed rows split into `>= old_lower OR < new_upper`.+ return XminBounds(+ lower=int(stored_last_value),+ upper=ceiling_xid,+ ceiling_xid8=ceiling_xid8,+ num_wraparound=num_wraparound,+ wraparound_or_range=True,+ )+ # delta >= 2 (or a negative epoch drift): too much churn to reconstruct safely — force a full+ # re-read of everything `< ceiling`.+ logger.warning(+ f"xmin epoch advanced by {delta} since the last sync (stored={stored_num_wraparound}, "+ f"current={num_wraparound}); forcing a full re-read."+ )+ return XminBounds(+ lower=0, upper=ceiling_xid, ceiling_xid8=ceiling_xid8, num_wraparound=num_wraparound, wraparound_or_range=False+ )++def _build_query(schema: str,table_name: str,@@ -1349,6 +1497,7 @@ def _build_query(enabled_columns: Optional[list[str]] = None,primary_keys: Optional[list[str]] = None,row_filters: Optional[list[ValidatedRowFilter]] = None,+ xmin_bounds: Optional[XminBounds] = None,) -> sql.Composed:projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)select_clause: sql.Composable = (@@ -1358,6 +1507,11 @@ def _build_query(# (an over-estimate is harmless).row_filter_conditions = render_psycopg_row_filter_conditions(row_filters or [])+ if xmin_bounds is not None:+ return _build_xmin_query(+ schema, table_name, select_clause, xmin_bounds, row_filter_conditions, add_sampling=bool(add_sampling)+ )+if not should_use_incremental_field:if add_sampling:if table_type == "view":@@ -1368,8 +1522,7 @@ def _build_query(query = sql.SQL("SELECT {cols} FROM {table} TABLESAMPLE SYSTEM (1)").format(cols=select_clause, table=sql.Identifier(schema, table_name))- query_with_limit = cast(LiteralString, f"{query.as_string()} LIMIT 1000")- return sql.SQL(query_with_limit).format()+ return query + sql.SQL(" LIMIT 1000")query = sql.SQL("SELECT {cols} FROM {table}").format(cols=select_clause, table=sql.Identifier(schema, table_name)@@ -1426,8 +1579,7 @@ def _build_query()if add_sampling:- query_with_limit = cast(LiteralString, f"{query.as_string()} LIMIT 1000")- return sql.SQL(query_with_limit).format()+ return query + sql.SQL(" LIMIT 1000")if upper_bound_inclusive is not None:query = sql.SQL("{inner} AND {field} <= {upper}").format(@@ -1439,8 +1591,46 @@ def _build_query(if row_filter_conditions:query = query + sql.SQL(" AND ") + and_join(row_filter_conditions)- query_str = cast(LiteralString, f"{query.as_string()} ORDER BY {{incremental_field}} ASC")- return sql.SQL(query_str).format(incremental_field=sql.Identifier(incremental_field))+ return query + sql.SQL(" ORDER BY {field} ASC").format(field=sql.Identifier(incremental_field))+++def _xmin_predicate(bounds: XminBounds) -> sql.Composed:+ """Bounded predicate over the cast `xmin` (no ordering operators exist on raw `xid`)."""+ xmin_expr = sql.SQL("xmin::text::bigint")+ if bounds.wraparound_or_range:+ return sql.SQL("({xmin} >= {lo} OR {xmin} < {hi})").format(+ xmin=xmin_expr, lo=sql.Literal(bounds.lower), hi=sql.Literal(bounds.upper)+ )+ return sql.SQL("({xmin} >= {lo} AND {xmin} < {hi})").format(+ xmin=xmin_expr, lo=sql.Literal(bounds.lower), hi=sql.Literal(bounds.upper)+ )+++def _build_xmin_query(+ schema: str,+ table_name: str,+ select_clause: sql.Composable,+ bounds: XminBounds,+ row_filter_conditions: list[sql.Composable],+ *,+ add_sampling: bool,+) -> sql.Composed:+ # `_ph_xmin` is force-projected (system columns never come back from `SELECT *`) and kept out of+ # `compute_projected_columns` so it can't collide with the user's incremental-field machinery.+ select = sql.SQL("xmin::text::bigint AS {alias}, {cols}").format(+ alias=sql.Identifier(XMIN_PROJECTED_COLUMN), cols=select_clause+ )+ query = sql.SQL("SELECT {cols} FROM {table} WHERE {predicate}").format(+ cols=select, table=sql.Identifier(schema, table_name), predicate=_xmin_predicate(bounds)+ )+ if row_filter_conditions:+ query = query + sql.SQL(" AND ") + and_join(row_filter_conditions)++ # ORDER BY the cast cursor so the offset-resume path stays correct on a connection drop.+ ordered = query + sql.SQL(" ORDER BY xmin::text::bigint ASC")+ if add_sampling:+ return ordered + sql.SQL(" LIMIT 1000")+ return ordereddef _build_count_query(@@ -1450,7 +1640,15 @@ def _build_count_query(incremental_field: Optional[str],incremental_field_type: Optional[IncrementalFieldType],db_incremental_field_last_value: Optional[Any],+ xmin_bounds: Optional[XminBounds] = None,) -> sql.Composed:+ if xmin_bounds is not None:+ return sql.SQL("SELECT COUNT(*) FROM {schema}.{table} WHERE {predicate}").format(+ schema=sql.Identifier(schema),+ table=sql.Identifier(table_name),+ predicate=_xmin_predicate(xmin_bounds),+ )+if not should_use_incremental_field:return sql.SQL("SELECT COUNT(*) FROM {schema}.{table}").format(schema=sql.Identifier(schema),@@ -2182,6 +2380,9 @@ def postgres_source(is_initial_sync: bool = False,enabled_columns: Optional[list[str]] = None,row_filters: Optional[list[ValidatedRowFilter]] = None,+ is_xmin: bool = False,+ xmin_last_value: Optional[int] = None,+ xmin_num_wraparound: Optional[int] = None,) -> SourceResponse:table_name = table_names[0]if not table_name:@@ -2233,6 +2434,10 @@ def postgres_source(# letting Temporal re-run setup straight back into the same wall.setup_recovery_conflicts = 0setup_connection_dropped_errors = 0+ # Captured once at sync start on the row-serving connection (see `_capture_xmin_ceiling`).+ # Re-derived on each setup retry, which is harmless — a later ceiling just reads a slightly+ # wider window. Persisted only at job completion (see the pipeline's xmin advance).+ xmin_bounds: XminBounds | None = Nonewhile True:# Opening the setup connection can itself hit a transient drop ("server closed the# connection unexpectedly", idle cull, failover) — the same class of error the read@@ -2266,6 +2471,10 @@ def postgres_source())+ # Capture the xmin ceiling on this row-serving connection before streaming.+ if is_xmin:+ xmin_bounds = _capture_xmin_ceiling(cursor, xmin_last_value, xmin_num_wraparound, logger)+try:logger.debug("Checking if source is a read replica...")using_read_replica = _is_read_replica(cursor)@@ -2284,6 +2493,14 @@ def postgres_source(primary_keys = ["id"]used_id_pk_fallback = True+ # xmin reads deltas and relies on an idempotent upsert to dedupe a+ # re-read window after a crash, so it requires a primary key.+ if is_xmin and not primary_keys:+ raise XminUnsupportedError(+ f"Table {schema}.{table_name} has no primary key, which xmin replication "+ "requires. Add a primary key or choose a different sync type."+ )+# Project both the Arrow schema and the SELECT clause so the cursor's row shape# matches what downstream consumers expect.retained_columns: list[str] | None = None@@ -2314,6 +2531,7 @@ def postgres_source(add_sampling=True,enabled_columns=enabled_columns,primary_keys=primary_keys,+ xmin_bounds=xmin_bounds,)count_query = _build_count_query(@@ -2323,6 +2541,7 @@ def postgres_source(incremental_field,incremental_field_type,db_incremental_field_last_value,+ xmin_bounds=xmin_bounds,)logger.debug("Checking if table is partitioned...")@@ -2334,6 +2553,17 @@ def postgres_source(child_partitions = list_child_partitions(cursor, schema, table_name)except Exception as e:logger.debug(f"Partition detection failed: {e}")++ # A single global ceiling can't span a partitioned parent's independent+ # per-partition xid spaces, so xmin is refused on parents (and hidden in+ # discovery for them). Partition/window chunking below is gated on+ # `should_use_incremental_field`, which is False for xmin, so xmin always+ # takes the non-partitioned single-cursor path.+ if is_xmin and is_partitioned:+ raise XminUnsupportedError(+ f"Table {schema}.{table_name} is a partitioned parent, which xmin replication "+ "does not support. Choose a different sync type."+ )logger.debug("Getting table chunk size...")if chunk_size_override is not None:chunk_size = chunk_size_override@@ -2473,6 +2703,10 @@ def postgres_source(def get_rows(chunk_size: int) -> Iterator[Any]:arrow_schema = table.to_arrow_schema()+ if xmin_bounds is not None:+ # The forced `_ph_xmin` projection isn't part of the discovered columns, so add it to+ # the Arrow schema (as the leading field, matching the SELECT) for a clean zip.+ arrow_schema = arrow_schema.insert(0, pa.field(XMIN_PROJECTED_COLUMN, pa.int64(), nullable=False))with tunnel() as (host, port):cursor_factory = psycopg.ServerCursor if not using_read_replica else None@@ -2559,6 +2793,7 @@ def postgres_source(enabled_columns=enabled_columns,primary_keys=primary_keys,row_filters=row_filters,+ xmin_bounds=xmin_bounds,)successive_errors = 0@@ -2589,12 +2824,11 @@ def postgres_source(# argument: 'name'". This LIMIT/OFFSET fetchall path wants an# unnamed client cursor.with psycopg.Cursor(connection) as cursor:- query_with_limit = cast(- LiteralString, f"{query.as_string()} LIMIT {chunk_size} OFFSET {offset}"+ query_with_limit_sql = query + sql.SQL(" LIMIT {limit} OFFSET {offset}").format(+ limit=sql.Literal(chunk_size),+ offset=sql.Literal(offset),)- query_with_limit_sql = sql.SQL(query_with_limit).format()-- logger.debug(f"Postgres query: {query_with_limit}")+ logger.debug(f"Postgres query: {query_with_limit_sql}")cursor.execute(query_with_limit_sql)column_names = [column.name for column in cursor.description or []]@@ -2758,6 +2992,7 @@ def postgres_source(enabled_columns=enabled_columns,primary_keys=primary_keys,row_filters=row_filters,+ xmin_bounds=xmin_bounds,)logger.debug(f"Postgres query: {query.as_string()}")@@ -2809,11 +3044,12 @@ def postgres_source(if not _is_connection_dropped_error(e):raise# Offset-based resume is only safe when the query has a stable- # ORDER BY (added by _build_query for incremental syncs). A- # full-table scan has no ORDER BY, so Postgres may return rows in- # a different order on the resumed query and OFFSET would skip or- # duplicate rows. In that case re-raise and let the sync restart.- if not should_use_incremental_field:+ # ORDER BY (added by _build_query for incremental syncs, and by the+ # xmin branch). A full-table scan has no ORDER BY, so Postgres may+ # return rows in a different order on the resumed query and OFFSET+ # would skip or duplicate rows. In that case re-raise and let the+ # sync restart.+ if not should_use_incremental_field and xmin_bounds is None:raiselogger.debug(f"Connection dropped ({e}). Falling back to offset chunking at offset {offset}.")yield from offset_chunking(offset, chunk_size)@@ -2829,6 +3065,9 @@ def postgres_source(partition_size=partition_settings.partition_size if partition_settings else None,rows_to_sync=rows_to_sync,has_duplicate_primary_keys=has_duplicate_primary_keys,+ xmin_ceiling_xid=xmin_bounds.upper if xmin_bounds is not None else None,+ xmin_ceiling_xid8=xmin_bounds.ceiling_xid8 if xmin_bounds is not None else None,+ xmin_num_wraparound=xmin_bounds.num_wraparound if xmin_bounds is not None else None,)diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.pyindex 34c19d48b266..6053914560b3 100644--- a/posthog/temporal/data_imports/sources/postgres/source.py+++ b/posthog/temporal/data_imports/sources/postgres/source.py@@ -33,6 +33,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (PostgresImplementation,SSLRequiredError,_rls_active_from_conn,+ _xmin_capable_tables_from_conn,filter_postgres_incremental_fields,get_connection_metadata as get_postgres_connection_metadata,get_foreign_keys as get_postgres_foreign_keys,@@ -46,7 +47,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import ()from products.data_warehouse.backend.postgres_helpers import reconcile_postgres_schemas-from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalField+from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalField, IncrementalFieldTypelog = logging.getLogger(__name__)@@ -210,6 +211,11 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDadef get_non_retryable_errors(self) -> dict[str, str | None]:return {+ # xmin can't run against this relation (server < PG13, no primary key, or a partitioned+ # parent) — deterministic, so don't retry. `XminUnsupportedError` matches once Temporal+ # wraps the failure; the message fragment matches the raw activity-level `str(e)`.+ "XminUnsupportedError": None,+ "xmin replication": None,"NoSuchTableError": None,"is not permitted to log in": None,"Tenant or user not found connection to server": None,@@ -535,6 +541,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaindexed_columns_by_table: dict[str, set[str]] | None = {}tables_with_pks: set[str] = set()rls_active_by_table: dict[str, bool] = {}+ xmin_capable_tables: set[str] = set()try:with pg_connection(@@ -604,6 +611,10 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa# Row-level security check powers the advisory warning in the table picker.rls_active_by_table = _rls_active_from_conn(conn, config.schema, names)++ # xmin availability (heap tables + matviews, PG13+). Postgres-only: the generic+ # `supports_xmin` default stays False for every other source.+ xmin_capable_tables = _xmin_capable_tables_from_conn(conn, config.schema, names)except Exception as e:# Connection-level failure for the best-effort PK/index/RLS metadata lookup. The# schema listing already succeeded above (`db_schemas`), so degrade quietly — log a@@ -617,6 +628,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaindexed_columns_by_table = Nonetables_with_pks = set()rls_active_by_table = {}+ xmin_capable_tables = set()for table_name, discovered_schema in db_schemas.items():incremental_field_tuples = filter_postgres_incremental_fields(discovered_schema.columns)@@ -634,13 +646,32 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa}for field_name, field_type, nullable in incremental_field_tuples]+ # `supports_incremental`/`supports_append` must reflect the real cursor fields only —+ # compute them before appending the synthetic xmin entry.+ supports_real_cursor = len(incremental_fields) > 0++ # xmin is advertised synthetically: it's never in information_schema (negative attnum),+ # so `filter_postgres_incremental_fields` can't produce it. It's always unindexed+ # (`xmin::text::bigint` is an expression), so the UI warns about the full seq scan.+ supports_xmin = table_name in xmin_capable_tables+ if supports_xmin:+ incremental_fields.append(+ {+ "label": "xmin",+ "type": IncrementalFieldType.XID,+ "field": "xmin",+ "field_type": IncrementalFieldType.XID,+ "is_indexed": False,+ }+ )schemas.append(SourceSchema(name=table_name,- supports_incremental=len(incremental_fields) > 0,- supports_append=len(incremental_fields) > 0,+ supports_incremental=supports_real_cursor,+ supports_append=supports_real_cursor,supports_cdc=table_name in tables_with_pks,+ supports_xmin=supports_xmin,incremental_fields=incremental_fields,row_count=row_counts.get(table_name, None),columns=discovered_schema.columns,@@ -812,6 +843,11 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDais_initial_sync=not schema.initial_sync_complete,enabled_columns=inputs.enabled_columns,row_filters=inputs.row_filters,+ # xmin state is read straight off the schema here (the generic `SourceInputs` stays+ # Postgres-agnostic). xmin rides the normal full per-schema path — no CDC dispatch.+ is_xmin=schema.is_xmin,+ xmin_last_value=schema.xmin_last_value,+ xmin_num_wraparound=schema.xmin_num_wraparound,)# `SourceResponse.name` must match `DataWarehouseTable.url_pattern` (both derived from the# storage key when present, otherwise the row name) so HogQL reads from where we wrote.diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex e1a0c20517c4..7e7de7f8f9a7 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -6,7 +6,7 @@ from typing import Any, castimport pytestfrom freezegun import freeze_timefrom unittest import mock-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.db import connection as django_connection@@ -24,6 +24,7 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (TemporaryFileSizeExceedsLimitException,)from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter+from posthog.temporal.data_imports.sources.postgres.exceptions import XminUnsupportedErrorfrom posthog.temporal.data_imports.sources.postgres.partitioned_tables import (WINDOW_MAX_QUERY_CANCELED_RETRIES,WINDOW_MAX_SERIALIZATION_RETRIES,@@ -46,6 +47,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (FORCE_UTF8_CLIENT_ENCODING,METADATA_STATEMENT_TIMEOUT_MS,SSL_REQUIRED_AFTER_DATE,+ XMIN_PROJECTED_COLUMN,JsonAsStringLoader,PostgresDiscoveredSchema,PostgresImplementation,@@ -57,8 +59,10 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (SafeTimestamptzLoader,SafeTimetzLoader,SSLRequiredError,+ XminBounds,_build_count_query,_build_query,+ _capture_xmin_ceiling,_connect_to_postgres,_connect_with_dropped_retry,_connect_with_options_fallback,@@ -85,6 +89,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (_role_subject_to_rls,_safe_close_connection,_statement_timeout_as_non_retryable,+ _xmin_capable_tables_from_conn,filter_postgres_incremental_fields,get_foreign_keys,get_leading_index_columns,@@ -2722,6 +2727,133 @@ class TestBuildQuery:assert "'x''; DROP TABLE y; --'" in rendered+class TestBuildXminQuery:+ def _render(self, composed: sql.Composed) -> str:+ return composed.as_string()++ def _bounds(self, *, lower=0, upper=5000, num_wraparound=0, wraparound_or_range=False) -> XminBounds:+ return XminBounds(+ lower=lower,+ upper=upper,+ ceiling_xid8=(num_wraparound << 32) | upper,+ num_wraparound=num_wraparound,+ wraparound_or_range=wraparound_or_range,+ )++ def test_first_run_reads_below_ceiling(self):+ query = _build_query("public", "users", False, "table", None, None, None, xmin_bounds=self._bounds(lower=0))+ rendered = self._render(query)+ assert f'xmin::text::bigint AS "{XMIN_PROJECTED_COLUMN}"' in rendered+ assert "xmin::text::bigint >= 0 AND xmin::text::bigint < 5000" in rendered+ assert "OR xmin::text::bigint" not in rendered+ assert rendered.rstrip().endswith("ORDER BY xmin::text::bigint ASC")++ def test_steady_state_single_range(self):+ query = _build_query(+ "public", "users", False, "table", None, None, None, xmin_bounds=self._bounds(lower=100, upper=5000)+ )+ rendered = self._render(query)+ assert "xmin::text::bigint >= 100 AND xmin::text::bigint < 5000" in rendered++ def test_wraparound_or_range(self):+ query = _build_query(+ "public",+ "users",+ False,+ "table",+ None,+ None,+ None,+ xmin_bounds=self._bounds(lower=4000000000, upper=500, num_wraparound=1, wraparound_or_range=True),+ )+ rendered = self._render(query)+ assert "xmin::text::bigint >= 4000000000 OR xmin::text::bigint < 500" in rendered++ def test_projects_ph_xmin_alias(self):+ query = _build_query("public", "users", False, "table", None, None, None, xmin_bounds=self._bounds())+ rendered = self._render(query)+ # `*` is kept so the user's columns come back alongside the synthetic cursor.+ assert f'SELECT xmin::text::bigint AS "{XMIN_PROJECTED_COLUMN}", *' in rendered++ def test_row_filter_anded_into_predicate(self):+ query = _build_query(+ "public",+ "users",+ False,+ "table",+ None,+ None,+ None,+ xmin_bounds=self._bounds(lower=100, upper=5000),+ row_filters=[ValidatedRowFilter(column="age", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],+ )+ rendered = self._render(query)+ assert 'AND "age" > 21' in rendered+ assert rendered.index("xmin::text::bigint < 5000") < rendered.index('"age" > 21')++ def test_sampling_appends_limit(self):+ query = _build_query(+ "public", "users", False, "table", None, None, None, add_sampling=True, xmin_bounds=self._bounds()+ )+ rendered = self._render(query)+ assert rendered.rstrip().endswith("LIMIT 1000")++ def test_count_query_uses_bounded_predicate(self):+ query = _build_count_query("public", "users", False, None, None, None, xmin_bounds=self._bounds(lower=100))+ rendered = self._render(query)+ assert "SELECT COUNT(*)" in rendered+ assert "xmin::text::bigint >= 100 AND xmin::text::bigint < 5000" in rendered+++class TestCaptureXminCeiling:+ def _cursor(self, *, server_version: int, ceiling_xid8: int, ceiling_xid: int) -> MagicMock:+ cursor = MagicMock()+ cursor.connection.info.server_version = server_version+ cursor.fetchone.return_value = (ceiling_xid8, ceiling_xid)+ return cursor++ def test_requires_pg13(self):+ cursor = self._cursor(server_version=120000, ceiling_xid8=5000, ceiling_xid=5000)+ with pytest.raises(XminUnsupportedError, match="PostgreSQL 13"):+ _capture_xmin_ceiling(cursor, None, None, MagicMock())++ def test_first_run_seeds_zero_lower_bound(self):+ cursor = self._cursor(server_version=150000, ceiling_xid8=5000, ceiling_xid=5000)+ bounds = _capture_xmin_ceiling(cursor, None, None, MagicMock())+ assert bounds.lower == 0+ assert bounds.upper == 5000+ assert bounds.wraparound_or_range is False++ def test_steady_state_uses_stored_lower_bound(self):+ cursor = self._cursor(server_version=150000, ceiling_xid8=5000, ceiling_xid=5000)+ bounds = _capture_xmin_ceiling(cursor, 100, 0, MagicMock())+ assert bounds.lower == 100+ assert bounds.wraparound_or_range is False++ def test_single_wrap_sets_or_range(self):+ # Epoch advanced by exactly 1 since last sync.+ cursor = self._cursor(server_version=150000, ceiling_xid8=(1 << 32) | 500, ceiling_xid=500)+ bounds = _capture_xmin_ceiling(cursor, 4000000000, 0, MagicMock())+ assert bounds.num_wraparound == 1+ assert bounds.wraparound_or_range is True+ assert bounds.lower == 4000000000++ def test_multi_wrap_forces_full_reread(self):+ cursor = self._cursor(server_version=150000, ceiling_xid8=(3 << 32) | 500, ceiling_xid=500)+ bounds = _capture_xmin_ceiling(cursor, 4000000000, 0, MagicMock())+ assert bounds.lower == 0+ assert bounds.wraparound_or_range is False+++class TestXminCapableTablesFromConn:+ def test_pg12_is_never_xmin_capable(self):+ # The PG13 guard short-circuits before any catalog query runs.+ connection = MagicMock()+ connection.info.server_version = 120000+ assert _xmin_capable_tables_from_conn(connection, "public", None) == set()+ connection.cursor.assert_not_called()++class TestBuildPartitionQuery:def _render(self, composed: sql.Composed) -> str:return composed.as_string()diff --git a/posthog/temporal/tests/data_imports/test_import_data.py b/posthog/temporal/tests/data_imports/test_import_data.pyindex cf5a485156d8..3444b8466523 100644--- a/posthog/temporal/tests/data_imports/test_import_data.py+++ b/posthog/temporal/tests/data_imports/test_import_data.py@@ -104,6 +104,9 @@ async def test_job_inputs_with_whitespace(activity_environment, team, **kwargs):is_initial_sync=True,enabled_columns=None,row_filters=[],+ is_xmin=False,+ xmin_last_value=None,+ xmin_num_wraparound=None,)@@ -147,6 +150,9 @@ async def test_postgres_source_without_ssh_tunnel(activity_environment, team, **is_initial_sync=True,enabled_columns=None,row_filters=[],+ is_xmin=False,+ xmin_last_value=None,+ xmin_num_wraparound=None,)@@ -202,6 +208,9 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, teis_initial_sync=True,enabled_columns=None,row_filters=[],+ is_xmin=False,+ xmin_last_value=None,+ xmin_num_wraparound=None,)@@ -272,6 +281,9 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, teais_initial_sync=True,enabled_columns=None,row_filters=[],+ is_xmin=False,+ xmin_last_value=None,+ xmin_num_wraparound=None,)diff --git a/products/data_warehouse/backend/api/test/test_external_data_schema.py b/products/data_warehouse/backend/api/test/test_external_data_schema.pyindex a1021445f086..18d0e8315974 100644--- a/products/data_warehouse/backend/api/test/test_external_data_schema.py+++ b/products/data_warehouse/backend/api/test/test_external_data_schema.py@@ -209,7 +209,15 @@ class TestExternalDataSchema(APIBaseTest):"nullable": True,# Table has no index on `id`, so the warning UI will fire for this field."is_indexed": False,- }+ },+ # xmin is synthetic: advertised for any ordinary PG13+ table, unindexed by definition.+ {+ "label": "xmin",+ "type": "xid",+ "field": "xmin",+ "field_type": "xid",+ "is_indexed": False,+ },],"incremental_available": True,"append_available": True,