: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): document xmin sync type and add e2e tests (#64942)
Daniel RC9a80dd7e6531
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex c8a769f086a2..3618ffaf7c01 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -22,7 +22,7 @@ Looking to add a new source to data warehouse? [We have a detailed guide in the4. user = posthog5. password = posthog6. schema = public-3. Hit next, then select which tables you'd like to import. [More info on the sync types can be found here](https://posthog.com/docs/cdp/sources#incremental-vs-append-only-vs-full-table)+3. Hit next, then select which tables you'd like to import. [More info on the sync types can be found here](https://posthog.com/docs/cdp/sources#incremental-vs-append-only-vs-full-table). For the Postgres-specific `xmin` (cursorless incremental) sync type and its limitations, see the [Postgres source README](https://github.com/PostHog/posthog/blob/master/posthog/temporal/data_imports/sources/postgres/README.md)4. Hit next and finish the import - `temporal-worker-data-warehouse` will then import the data into your local object storage## Accessing object storagediff --git a/posthog/temporal/data_imports/sources/postgres/README.md b/posthog/temporal/data_imports/sources/postgres/README.mdnew file mode 100644index 000000000000..209ae3f7a373--- /dev/null+++ b/posthog/temporal/data_imports/sources/postgres/README.md@@ -0,0 +1,53 @@+# Postgres source++Sync types available per table: `full_refresh`, `incremental`, `append`, `cdc`, and `xmin`.++## xmin replication++xmin is a **cursorless incremental** sync type. It tracks changes using Postgres's hidden+`xmin` system column — the transaction id (XID) that last inserted or updated each row — so a+table can sync incrementally even when it has no good user-defined cursor (e.g. no+`updated_at`).++Each sync captures a ceiling (`pg_snapshot_xmin(pg_current_snapshot())`, the lowest+still-running xid) on the row-serving connection, reads every row whose `xmin` falls in+`[previous ceiling, this ceiling)`, and persists the ceiling at job completion. Rows are+upserted by primary key, so a re-read of an already-synced row is idempotent.++### When to use it++- The table has **no reliable incremental cursor** and you'd otherwise use `full_refresh`.+- The database is **not under heavy write churn** (every sync is a full sequential scan — see+ limitations).+- You don't need deletes captured (if you do, choose `cdc`).++### Limitations++These are inherent to how `xmin` works, not bugs:++- **No hard deletes.** A vacuumed deleted tuple leaves nothing for `xmin` to observe, so deletes+ never propagate. Updates and inserts are captured; deletes are not.+- **Full sequential scan every sync.** `xmin` has no index (`xmin::text::bigint` is an+ expression), so each sync scans the whole table. On large tables this can hit the+ 10-minute `statement_timeout`. The unindexed-field warning fires in the UI.+- **Frozen tuples are invisible to future diffs.** `VACUUM FREEZE` rewrites very old tuples'+ `xmin` to `FrozenTransactionId` (2). The initial full snapshot (first run reads everything+ below the ceiling) is what guarantees those rows were synced — a frozen row can't be+ re-detected afterwards.+- **PostgreSQL 13+ only.** The durable cursor uses the 64-bit, wraparound-safe `xid8`+ (`pg_snapshot_xmin`), available from PG13.+- **Heap tables and materialized views only.** Plain views and foreign tables have no physical+ `xmin`; partitioned parents are excluded (a single global ceiling can't span independent+ per-partition xid spaces).+- **Requires a primary key** for clean upsert deduplication.++### Wraparound++The bare 32-bit `xmin` counter wraps every ~4 billion transactions. We persist the full+`xid8` ceiling and its epoch (`xmin_num_wraparound`) so wraparound is handled explicitly: a+single wrap reads `>= lower OR < upper`; a multi-wrap forces a full re-read.++### Feature flag++Gated behind `dwh-postgres-xmin` (organization-scoped). See+`products/data_warehouse/backend/data_load/service.py:is_xmin_enabled_for_team`.diff --git a/posthog/temporal/tests/data_imports/test_end_to_end.py b/posthog/temporal/tests/data_imports/test_end_to_end.pyindex d54dc79939cc..7cdf23e31d31 100644--- a/posthog/temporal/tests/data_imports/test_end_to_end.py+++ b/posthog/temporal/tests/data_imports/test_end_to_end.py@@ -63,6 +63,7 @@ from posthog.temporal.data_imports.row_tracking import get_rowsfrom posthog.temporal.data_imports.settings import ACTIVITIESfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistryfrom posthog.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient as PostHogRESTClient+from posthog.temporal.data_imports.sources.postgres.postgres import XminBoundsfrom posthog.temporal.data_imports.sources.stripe.constants import (BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,CHARGE_RESOURCE_NAME as STRIPE_CHARGE_RESOURCE_NAME,@@ -4136,3 +4137,185 @@ async def test_mysql_decimal_and_unsigned_types(team, mysql_config, mysql_connecassert str(rows[0][1]) == "123.45"# Unsigned BIGINT > signed-int64 max — must come back intact.assert int(rows[0][2]) == 9_000_000_000_000_000_000+++def _postgres_job_inputs(postgres_config: dict) -> dict[str, str | dict[str, str]]:+ return {+ "host": postgres_config["host"],+ "port": postgres_config["port"],+ "database": postgres_config["database"],+ "user": postgres_config["user"],+ "password": postgres_config["password"],+ "schema": postgres_config["schema"],+ "ssh_tunnel_enabled": "False",+ }++[email protected]_db(transaction=True)+async def test_postgres_xmin_sync(team, postgres_config, postgres_connection):+ """End-to-end xmin replication: initial snapshot, incremental delta on insert/update,+ persisted ceiling state, and hard-delete invisibility."""+ schema_name = postgres_config["schema"]+ await postgres_connection.execute(+ "CREATE TABLE IF NOT EXISTS {schema}.xmin_table (id integer PRIMARY KEY, name text)".format(schema=schema_name)+ )+ await postgres_connection.execute(+ "INSERT INTO {schema}.xmin_table (id, name) VALUES (1, 'a')".format(schema=schema_name)+ )+ await postgres_connection.commit()++ # Initial snapshot captures the committed row (`_run` asserts exactly one row landed).+ _workflow_id, inputs = await _run(+ team=team,+ schema_name="xmin_table",+ table_name="postgres_xmin_table",+ source_type="Postgres",+ job_inputs=_postgres_job_inputs(postgres_config),+ mock_data_response=[],+ sync_type=ExternalDataSchema.SyncType.XMIN,+ sync_type_config={},+ )++ res = await sync_to_async(execute_hogql_query)("SELECT id, name FROM postgres_xmin_table ORDER BY id", team)+ assert [(r[0], r[1]) for r in res.results] == [(1, "a")]++ # Ceiling state persisted at job completion (next run's lower bound + durable cursor + epoch).+ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)+ assert schema.xmin_last_value is not None+ assert schema.xmin_ceiling is not None+ assert schema.xmin_num_wraparound is not None+ first_ceiling = schema.xmin_last_value++ # Mutate: update the existing row and insert a new one. Both get a fresh xmin above the ceiling.+ await postgres_connection.execute(+ "UPDATE {schema}.xmin_table SET name = 'a2' WHERE id = 1".format(schema=schema_name)+ )+ await postgres_connection.execute(+ "INSERT INTO {schema}.xmin_table (id, name) VALUES (2, 'b')".format(schema=schema_name)+ )+ await postgres_connection.commit()++ await _execute_run(str(uuid.uuid4()), inputs, [])+ await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)++ # Only the delta is read, upserted by primary key: row 1 reflects the update, row 2 is new.+ res = await sync_to_async(execute_hogql_query)("SELECT id, name FROM postgres_xmin_table ORDER BY id", team)+ assert [(r[0], r[1]) for r in res.results] == [(1, "a2"), (2, "b")]++ # Ceiling advanced strictly past the first run's value — the delta committed new transactions.+ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)+ assert schema.xmin_last_value is not None+ assert schema.xmin_last_value > first_ceiling++ # Hard deletes are invisible to xmin — a vacuumed tuple leaves nothing to read.+ await postgres_connection.execute("DELETE FROM {schema}.xmin_table WHERE id = 2".format(schema=schema_name))+ await postgres_connection.commit()++ await _execute_run(str(uuid.uuid4()), inputs, [])+ await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)++ res = await sync_to_async(execute_hogql_query)("SELECT id, name FROM postgres_xmin_table ORDER BY id", team)+ assert [(r[0], r[1]) for r in res.results] == [(1, "a2"), (2, "b")]++[email protected]_db(transaction=True)+async def test_postgres_xmin_wraparound_or_range(team, postgres_config, postgres_connection):+ """The single-wrap `>= lower OR < upper` predicate executes against real Postgres and reads rows.+ A mocked ceiling forces the wraparound branch (the exact SQL is covered by unit tests)."""+ schema_name = postgres_config["schema"]+ await postgres_connection.execute(+ "CREATE TABLE IF NOT EXISTS {schema}.xmin_wrap (id integer PRIMARY KEY, name text)".format(schema=schema_name)+ )+ await postgres_connection.execute(+ "INSERT INTO {schema}.xmin_wrap (id, name) VALUES (1, 'a')".format(schema=schema_name)+ )+ await postgres_connection.commit()++ # Force the OR-range branch with a huge `upper` so the `< upper` side matches every real+ # (small) tuple xmin — exercising the wraparound predicate end-to-end.+ wraparound_bounds = XminBounds(+ lower=4_000_000_000,+ upper=4_294_967_295,+ ceiling_xid8=(1 << 32) | 4_294_967_295,+ num_wraparound=1,+ wraparound_or_range=True,+ )++ with mock.patch(+ "posthog.temporal.data_imports.sources.postgres.postgres._capture_xmin_ceiling",+ return_value=wraparound_bounds,+ ) as mock_capture:+ await _run(+ team=team,+ schema_name="xmin_wrap",+ table_name="postgres_xmin_wrap",+ source_type="Postgres",+ job_inputs=_postgres_job_inputs(postgres_config),+ mock_data_response=[],+ sync_type=ExternalDataSchema.SyncType.XMIN,+ sync_type_config={},+ )++ mock_capture.assert_called_once()++ res = await sync_to_async(execute_hogql_query)("SELECT id, name FROM postgres_xmin_wrap ORDER BY id", team)+ assert [(r[0], r[1]) for r in res.results] == [(1, "a")]++[email protected]_db(transaction=True)+async def test_postgres_switch_to_xmin_rebuilds_table(team, postgres_config, postgres_connection):+ """Switching an already-synced table to xmin rebuilds the Delta table. Without the resync the+ write fails: the old physical schema lacks the non-nullable `_ph_xmin` control column."""+ schema_name = postgres_config["schema"]+ await postgres_connection.execute(+ "CREATE TABLE IF NOT EXISTS {schema}.switch_tbl (id integer PRIMARY KEY, name text)".format(schema=schema_name)+ )+ await postgres_connection.execute(+ "INSERT INTO {schema}.switch_tbl (id, name) VALUES (1, 'a')".format(schema=schema_name)+ )+ await postgres_connection.commit()++ # First sync as incremental — the Delta table is created without `_ph_xmin`.+ _workflow_id, inputs = await _run(+ team=team,+ schema_name="switch_tbl",+ table_name="postgres_switch_tbl",+ source_type="Postgres",+ job_inputs=_postgres_job_inputs(postgres_config),+ mock_data_response=[],+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},+ )++ res = await sync_to_async(execute_hogql_query)("SELECT id, name FROM postgres_switch_tbl ORDER BY id", team)+ assert [(r[0], r[1]) for r in res.results] == [(1, "a")]++ # Switch to xmin with reset_pipeline — what the serializer sets when crossing the xmin boundary.+ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)+ schema.sync_type = ExternalDataSchema.SyncType.XMIN+ schema.sync_type_config = {"primary_key_columns": ["id"], "reset_pipeline": True}+ await sync_to_async(schema.save)()++ await postgres_connection.execute(+ "INSERT INTO {schema}.switch_tbl (id, name) VALUES (2, 'b')".format(schema=schema_name)+ )+ await postgres_connection.commit()++ await _execute_run(str(uuid.uuid4()), inputs, [])+ await _replay_v3_consumer(team_id=team.pk, schema_id=inputs.external_data_schema_id)++ # The table was rebuilt from scratch under xmin (first xmin run reads everything below the+ # ceiling), so both rows land and the `_ph_xmin` column is present.+ res = await sync_to_async(execute_hogql_query)(+ "SELECT id, name, _ph_xmin FROM postgres_switch_tbl ORDER BY id", team+ )+ assert [(r[0], r[1]) for r in res.results] == [(1, "a"), (2, "b")]+ assert all(r[2] is not None for r in res.results)++ # Reset consumed: xmin state seeded fresh, reset_pipeline cleared.+ schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)+ assert schema.sync_type_config.get("reset_pipeline") is None+ assert schema.xmin_last_value is not Nonediff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.pyindex c64e93b7120b..a6ad6d082190 100644--- a/products/data_warehouse/backend/api/external_data_schema.py+++ b/products/data_warehouse/backend/api/external_data_schema.py@@ -716,6 +716,25 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):"Add a primary key on the source table and retry.")+ # Switching sync type across the xmin boundary changes the physical Delta schema: xmin+ # force-projects a non-nullable `_ph_xmin` control column that no other sync type writes.+ # Reusing the existing Delta table fails the write — the column is missing on the way in, or+ # lingers on the way out — so force a full resync to rebuild the table from scratch.+ if (+ "sync_type" in data+ and sync_type != instance.sync_type+ and ExternalDataSchema.SyncType.XMIN in (sync_type, instance.sync_type)+ ):+ if is_any_external_data_schema_paused(instance.team_id):+ raise ValidationError(+ "Monthly sync limit reached. Please increase your billing limit before changing "+ "the sync type — a full re-sync would be required."+ )+ validated_data.setdefault("sync_type_config", instance.sync_type_config)+ validated_data["sync_type_config"]["reset_pipeline"] = True+ if should_sync if should_sync is not None else instance.should_sync:+ trigger_refresh = True+# When re-enabling a webhook schema, force a full refresh to avoid missing dataif (should_sync is Truediff --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 18d0e8315974..b937b921472e 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@@ -984,6 +984,74 @@ class TestExternalDataSchema(APIBaseTest):if expected_status == 400:assert "1-minute" in str(response.json()).lower() or "cdc" in str(response.json()).lower()+ def test_update_schema_to_xmin_forces_full_resync(self):+ # Switching to xmin from another strategy adds the `_ph_xmin` control column to the physical+ # schema, so the existing Delta table must be rebuilt — force a full resync.+ source = self._xmin_postgres_source()+ table = DataWarehouseTable.objects.create(team=self.team)+ schema = ExternalDataSchema.objects.create(+ name="public.orders",+ team=self.team,+ source=source,+ should_sync=True,+ status=ExternalDataSchema.Status.COMPLETED,+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type_config={"primary_key_columns": ["id"]},+ table=table,+ )++ get_schemas_patch, flag_patch = self._xmin_discovery_patches()+ with (+ get_schemas_patch,+ flag_patch,+ mock.patch(+ "products.data_warehouse.backend.api.external_data_schema.trigger_external_data_workflow"+ ) as mock_trigger,+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": "xmin", "primary_key_columns": ["id"]},+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ schema.refresh_from_db()+ assert schema.sync_type == ExternalDataSchema.SyncType.XMIN+ assert schema.sync_type_config.get("reset_pipeline") is True+ mock_trigger.assert_called_once()++ def test_update_schema_from_xmin_forces_full_resync(self):+ # Leaving xmin for another strategy must also rebuild the table — the lingering `_ph_xmin`+ # column would otherwise break the incremental write.+ source = self._xmin_postgres_source()+ table = DataWarehouseTable.objects.create(team=self.team)+ schema = ExternalDataSchema.objects.create(+ name="public.orders",+ team=self.team,+ source=source,+ should_sync=True,+ status=ExternalDataSchema.Status.COMPLETED,+ sync_type=ExternalDataSchema.SyncType.XMIN,+ sync_type_config={"primary_key_columns": ["id"], "xmin_last_value": 123},+ table=table,+ )++ with (+ mock.patch(+ "products.data_warehouse.backend.api.external_data_schema.trigger_external_data_workflow"+ ) as mock_trigger,+ mock.patch.object(DataWarehouseTable, "get_max_value_for_column", return_value=1),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": "incremental", "incremental_field": "id", "incremental_field_type": "integer"},+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ schema.refresh_from_db()+ assert schema.sync_type == ExternalDataSchema.SyncType.INCREMENTAL+ assert schema.sync_type_config.get("reset_pipeline") is True+ mock_trigger.assert_called_once()+@parameterized.expand([("incremental", ExternalDataSchema.SyncType.INCREMENTAL, 400),diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsxindex d47c06f4dd04..418e365ea8ba 100644--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx@@ -36,6 +36,7 @@ import {import {StatusTagSetting,SyncFrequencyLabelMap,+ SyncTypeLabelMap,allowedSyncFrequencies,defaultQuery,syncAnchorIntervalToHumanReadable,@@ -359,25 +360,53 @@ function SyncMethodSection({incrementalFieldLookbackSeconds?: number | null): Promise<void> => {const noIncrementalField = syncType === 'full_refresh' || syncType === 'cdc' || syncType === 'xmin'- setSaving(true)- try {- await api.externalDataSchemas.update(schema.id, {- should_sync: true,- sync_type: syncType,- incremental_field: noIncrementalField ? null : incrementalField,- incremental_field_type: noIncrementalField ? null : incrementalFieldType,- incremental_field_lookback_seconds:- syncType === 'incremental' ? (incrementalFieldLookbackSeconds ?? null) : null,- primary_key_columns: syncType === 'incremental' ? (primaryKeyColumns ?? null) : null,- ...(syncType === 'cdc' && cdcTableMode ? { cdc_table_mode: cdcTableMode } : {}),++ const applyUpdate = async (): Promise<void> => {+ setSaving(true)+ try {+ await api.externalDataSchemas.update(schema.id, {+ should_sync: true,+ sync_type: syncType,+ incremental_field: noIncrementalField ? null : incrementalField,+ incremental_field_type: noIncrementalField ? null : incrementalFieldType,+ incremental_field_lookback_seconds:+ syncType === 'incremental' ? (incrementalFieldLookbackSeconds ?? null) : null,+ primary_key_columns: syncType === 'incremental' ? (primaryKeyColumns ?? null) : null,+ ...(syncType === 'cdc' && cdcTableMode ? { cdc_table_mode: cdcTableMode } : {}),+ })+ lemonToast.success('Sync method saved')+ loadSchema()+ } catch (e: any) {+ lemonToast.error(e?.message || "Can't save sync method at this time")+ } finally {+ setSaving(false)+ }+ }++ // Switching to or from xmin changes the table's physical schema (the `_ph_xmin` control+ // column), so the backend rebuilds the table from scratch. Warn before discarding the data.+ const crossesXminBoundary = syncType === 'xmin' || schema.sync_type === 'xmin'+ if (crossesXminBoundary && syncType !== schema.sync_type && schema.last_synced_at) {+ LemonDialog.open({+ title: 'Switching sync method requires a full resync',+ content: (+ <div className="text-sm text-secondary deprecated-space-y-2">+ <p>+ Switching <strong>{schema.table?.name ?? schema.name}</strong> from{' '}+ <strong>{SyncTypeLabelMap[schema.sync_type ?? 'full_refresh']}</strong> to{' '}+ <strong>{SyncTypeLabelMap[syncType ?? 'full_refresh']}</strong> changes the table's+ structure, so it will be deleted and resynced from scratch.+ </p>+ <p>The existing synced data is replaced. This can take a while for large tables.</p>+ </div>+ ),+ primaryButton: { children: 'Resync now', onClick: () => void applyUpdate() },+ secondaryButton: { children: 'Cancel', type: 'tertiary' },})- lemonToast.success('Sync method saved')- loadSchema()- } catch (e: any) {- lemonToast.error(e?.message || "Can't save sync method at this time")- } finally {- setSaving(false)+ return}++ await applyUpdate()}return (