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(warehouse-sources): read the whole table on an xmin backfill (#85687)

Daniel RCd02622ea3c08
diff --git a/products/warehouse_sources/backend/management/commands/reset_wrapped_xmin_cursors.py b/products/warehouse_sources/backend/management/commands/reset_wrapped_xmin_cursors.py
new file mode 100644
index 000000000000..97f2436147a7
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/reset_wrapped_xmin_cursors.py
@@ -0,0 +1,121 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandParser
+
+import structlog
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+logger = structlog.get_logger(__name__)
+
+
+class Command(BaseCommand):
+ help = (
+ "Clear the xmin cursor on schemas whose backfill may have run against a wrapped cluster. "
+ "Those backfills filtered on an [0, ceiling) window of raw 32-bit xids, which skips tuples "
+ "written in an earlier epoch, so the table can be missing rows that no later incremental "
+ "run brings back. Clearing the cursor makes the next sync re-read the whole table and "
+ "upsert by primary key."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument(
+ "--live-run",
+ action="store_true",
+ help="Actually clear the cursors. Without this flag the command only lists matches (dry-run).",
+ )
+ parser.add_argument(
+ "--team-id",
+ type=int,
+ default=None,
+ help="Only consider schemas belonging to this team",
+ )
+ parser.add_argument(
+ "--schema-id",
+ action="append",
+ default=None,
+ help="Target these schema ids explicitly, skipping the wraparound filter. Repeatable.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ live_run = options["live_run"]
+ team_id = options["team_id"]
+ schema_ids = options["schema_id"]
+
+ schemas = ExternalDataSchema.objects.select_related("source").filter(
+ sync_type=ExternalDataSchema.SyncType.XMIN,
+ deleted=False,
+ )
+
+ if team_id is not None:
+ schemas = schemas.filter(team_id=team_id)
+
+ if schema_ids:
+ # An operator naming schemas has already established they need re-seeding, so don't
+ # second-guess it with the epoch heuristic.
+ candidates = list(schemas.filter(id__in=schema_ids))
+ else:
+ # Epoch 0 clusters never wrapped, so their [0, ceiling) window covered the whole xid
+ # space and the backfill read everything. Past a wraparound the window is a candidate
+ # rather than proof, since a large remainder can still have caught every tuple.
+ candidates = [schema for schema in schemas if (schema.xmin_num_wraparound or 0) > 0]
+
+ if not candidates:
+ self.stdout.write(self.style.WARNING("No xmin schemas found with a cursor captured past a wraparound."))
+ return
+
+ # A sync that is already streaming persists the ceiling it captured at startup when it
+ # completes, which would restore the cursor this command just cleared.
+ running = set(
+ ExternalDataJob.objects.filter(
+ schema_id__in=[schema.id for schema in candidates],
+ status=ExternalDataJob.Status.RUNNING,
+ ).values_list("schema_id", flat=True)
+ )
+
+ self.stdout.write(f"Found {len(candidates)} xmin schema(s) whose backfill may have skipped rows:\n")
+
+ for schema in candidates:
+ # Share of the 32-bit xid space the backfill window covered. The lower it is, the more
+ # of the table the backfill could have skipped.
+ window_covered = (schema.xmin_last_value or 0) / 0x100000000
+ self.stdout.write(
+ f" schema={schema.id} team={schema.team_id} source={schema.source_id} "
+ f"name={schema.name} epoch={schema.xmin_num_wraparound} cursor={schema.xmin_ceiling} "
+ f"window_covered={window_covered:.1%}"
+ + (" [sync running, will be skipped]" if schema.id in running else "")
+ )
+
+ if not live_run:
+ self.stdout.write(
+ self.style.WARNING(
+ f"\nDry run: {len(candidates) - len(running)} cursor(s) would be cleared. Pass --live-run to execute."
+ )
+ )
+ return
+
+ succeeded = 0
+ failed = 0
+ skipped = 0
+
+ for schema in candidates:
+ if schema.id in running:
+ skipped += 1
+ self.stdout.write(
+ self.style.WARNING(f"Skipped schema={schema.id}: a sync is running. Re-run once it finishes.")
+ )
+ continue
+ try:
+ schema.clear_xmin_state()
+ succeeded += 1
+ logger.info(
+ "Cleared xmin cursor for re-backfill",
+ schema_id=str(schema.id),
+ team_id=schema.team_id,
+ )
+ except Exception:
+ failed += 1
+ logger.exception("Failed to clear xmin cursor", schema_id=str(schema.id), team_id=schema.team_id)
+
+ self.stdout.write(self.style.SUCCESS(f"\nDone. Cleared: {succeeded}, Skipped: {skipped}, Failed: {failed}"))
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 49e593e5d934..0d90652d6cc2 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -961,6 +961,16 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
if save:
self.save(skip_activity_log=True)
+ def clear_xmin_state(self, save: bool = True) -> None:
+ # Drops the cursor so the next run takes the backfill path and re-reads the whole table,
+ # upserting by primary key. Use it to repair a schema whose backfill missed rows.
+ self.sync_type_config.pop("xmin_last_value", None)
+ self.sync_type_config.pop("xmin_ceiling", None)
+ self.sync_type_config.pop("xmin_num_wraparound", None)
+
+ if save:
+ self.save(skip_activity_log=True)
+
def soft_delete(self):
self.deleted = True
self.deleted_at = timezone.now()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/README.md b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/README.md
index fe277c7577e2..a5eebc24820e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/README.md
@@ -14,6 +14,11 @@ still-running xid) on the row-serving connection, reads every row whose `xmin` f
`[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.
+The first sync has no previous ceiling, so it reads the **whole table** with no `xmin`
+predicate. It still captures the ceiling first and persists it afterwards, which means rows
+committed while the scan runs are re-read on the next sync instead of being skipped. A
+multi-wrap epoch jump falls back to the same whole-table read.
+
### When to use it
- The table has **no reliable incremental cursor** and you'd otherwise use `full_refresh`.
@@ -30,10 +35,11 @@ These are inherent to how `xmin` works, not bugs:
- **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.
+- **Frozen tuples are invisible to future diffs.** Since PG 9.4 freezing sets
+ `HEAP_XMIN_FROZEN` in the tuple's infomask and leaves the raw `xmin` alone (it no longer
+ rewrites it to `FrozenTransactionId`, 2), so a frozen row keeps an xid that says nothing about
+ when it last changed. The initial whole-table read is what guarantees those rows were synced,
+ because 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
@@ -43,9 +49,20 @@ These are inherent to how `xmin` works, not bugs:
### 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.
+The bare 32-bit `xmin` counter wraps every ~4 billion transactions, and a tuple's `xmin`
+carries no epoch, so a raw comparison is only meaningful relative to the epoch the stored cursor
+was captured in. 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 re-reads
+the whole table, as does a backfill.
+
+Bounding a backfill by `xmin < ceiling` is wrong on a cluster that has wrapped: the ceiling's low
+32 bits are a small remainder of the current epoch, and every tuple written in an earlier epoch
+sits above it, so the read silently returns almost nothing. Use
+`reset_wrapped_xmin_cursors` (management command) to find schemas whose cursor was captured past a
+wraparound and clear it, which makes the next sync re-read the whole table. A cursor captured past
+a wraparound is a candidate rather than proof: the command reports how much of the xid space each
+backfill window covered, and a window that covered most of the space may have read the whole table
+anyway.
### Feature flag
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 30675454e4ec..ad10bc030af0 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
@@ -1848,7 +1848,7 @@ class SafeTimetzLoader(TimetzLoader):
return _load_time_clamping_hour_24(super().load, data)
[email protected](frozen=True)
class XminBounds:
"""Bounded xmin window captured once at sync start (see §2.2/§2.3 of the design).
@@ -1856,6 +1856,11 @@ class XminBounds:
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`.
+
+ `full_scan` drops the window and reads every tuple. A backfill has to do that because tuple
+ `xmin` carries no epoch: on a cluster past its first wraparound the rows written in earlier
+ epochs keep 32-bit xids above the current epoch's remainder, so no `[0, ceiling)` window
+ reaches them.
"""
lower: int
@@ -1863,6 +1868,7 @@ class XminBounds:
ceiling_xid8: int
num_wraparound: int
wraparound_or_range: bool
+ full_scan: bool = False
def _capture_xmin_ceiling(
@@ -1893,8 +1899,13 @@ def _capture_xmin_ceiling(
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.
+ # First run (no stored cursor): read the whole table, with no xmin predicate. An
+ # `xmin < ceiling` window silently drops most of the table on a wrapped cluster, because
+ # `ceiling_xid` is only the low 32 bits of the ceiling while historical tuples keep raw xids
+ # above it (since PG 9.4 freezing sets HEAP_XMIN_FROZEN in the infomask and leaves `xmin`
+ # alone instead of rewriting it to FrozenTransactionId, so those xids stay large). The
+ # ceiling is still captured here and persisted after the run, so rows committed during the
+ # scan are re-read next run rather than skipped.
if stored_last_value is None:
return XminBounds(
lower=0,
@@ -1902,6 +1913,7 @@ def _capture_xmin_ceiling(
ceiling_xid8=ceiling_xid8,
num_wraparound=num_wraparound,
wraparound_or_range=False,
+ full_scan=True,
)
delta = num_wraparound - (stored_num_wraparound or 0)
@@ -1922,14 +1934,19 @@ def _capture_xmin_ceiling(
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`.
+ # delta >= 2 (or a negative epoch drift): too much churn to reconstruct safely, so re-read the
+ # whole table like a backfill does.
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
+ lower=0,
+ upper=ceiling_xid,
+ ceiling_xid8=ceiling_xid8,
+ num_wraparound=num_wraparound,
+ wraparound_or_range=False,
+ full_scan=True,
)
@@ -2057,6 +2074,9 @@ def _build_query(
def _xmin_predicate(bounds: XminBounds) -> sql.Composed:
"""Bounded predicate over the cast `xmin` (no ordering operators exist on raw `xid`)."""
+ if bounds.full_scan:
+ # No window is safe across wraparound epochs (see `_capture_xmin_ceiling`), so read it all.
+ return sql.SQL("TRUE").format()
xmin_expr = sql.SQL("xmin::text::bigint")
if bounds.wraparound_or_range:
return sql.SQL("({xmin} >= {lo} OR {xmin} < {hi})").format(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index 2d1ce8c9a792..6e7f2e93575c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -4961,23 +4961,34 @@ 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:
+ def _bounds(
+ self, *, lower=0, upper=5000, num_wraparound=0, wraparound_or_range=False, full_scan=False
+ ) -> XminBounds:
return XminBounds(
lower=lower,
upper=upper,
ceiling_xid8=(num_wraparound << 32) | upper,
num_wraparound=num_wraparound,
wraparound_or_range=wraparound_or_range,
+ full_scan=full_scan,
)
- def test_first_run_reads_below_ceiling(self):
- query = _build_query("public", "users", False, "table", None, None, None, xmin_bounds=self._bounds(lower=0))
+ def test_full_scan_drops_the_xmin_window(self):
+ query = _build_query(
+ "public", "users", False, "table", None, None, None, xmin_bounds=self._bounds(full_scan=True)
+ )
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 "xmin::text::bigint >=" not in rendered
+ assert "xmin::text::bigint <" not in rendered
assert rendered.rstrip().endswith("ORDER BY xmin::text::bigint ASC")
+ def test_full_scan_count_query_counts_every_row(self):
+ query = _build_count_query("public", "users", False, None, None, None, xmin_bounds=self._bounds(full_scan=True))
+ rendered = self._render(query)
+ assert "xmin::text::bigint >=" not in rendered
+ assert "xmin::text::bigint <" not in rendered
+
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)
@@ -5047,18 +5058,27 @@ class TestCaptureXminCeiling:
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
+ @parameterized.expand(
+ [
+ ("first_run", None, None),
+ ("multi_wrap", 4000000000, 0),
+ ]
+ )
+ def test_reads_whole_table_when_no_window_is_safe(self, _name, stored_last_value, stored_num_wraparound):
+ # Backfills and multi-wrap re-reads can't use a 32-bit window: `ceiling_xid` is only the low
+ # half of the ceiling, so tuples written in earlier epochs sit above it.
+ cursor = self._cursor(server_version=150000, ceiling_xid8=(12 << 32) | 500, ceiling_xid=500)
+ bounds = _capture_xmin_ceiling(cursor, stored_last_value, stored_num_wraparound, MagicMock())
+ assert bounds.full_scan is True
+ assert bounds.ceiling_xid8 == (12 << 32) | 500
+ assert bounds.num_wraparound == 12
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
+ assert bounds.full_scan is False
def test_single_wrap_sets_or_range(self):
# Epoch advanced by exactly 1 since last sync.
@@ -5067,12 +5087,36 @@ class TestCaptureXminCeiling:
assert bounds.num_wraparound == 1
assert bounds.wraparound_or_range is True
assert bounds.lower == 4000000000
+ assert bounds.full_scan is False
- 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 TestXminBackfillAgainstPostgres:
+ @pytest.mark.django_db
+ def test_backfill_reads_tuples_above_the_ceiling_remainder(self):
+ # Reproduces the reported silent data loss. On a cluster past a wraparound the ceiling's
+ # low 32 bits are a small remainder while every tuple written in an earlier epoch keeps a
+ # much larger raw `xmin`, so the old `[0, remainder)` backfill window matched no rows and
+ # the run still completed and advanced the cursor.
+ with django_connection.cursor() as dj_cursor:
+ dj_cursor.execute("CREATE TABLE xmin_wraparound_probe (id int PRIMARY KEY)")
+ dj_cursor.execute("INSERT INTO xmin_wraparound_probe SELECT generate_series(1, 10)")
+ dj_cursor.execute("SELECT MIN(xmin::text::bigint) FROM xmin_wraparound_probe")
+ lowest_tuple_xmin = dj_cursor.fetchone()[0]
+
+ snapshot_cursor = MagicMock()
+ snapshot_cursor.connection.info.server_version = 150000
+ snapshot_cursor.fetchone.return_value = ((12 << 32) | lowest_tuple_xmin,)
+ bounds = _capture_xmin_ceiling(snapshot_cursor, None, None, MagicMock())
+
+ dj_cursor.execute(
+ _build_query("public", "xmin_wraparound_probe", False, "table", None, None, None, xmin_bounds=bounds)
+ )
+ assert len(dj_cursor.fetchall()) == 10
+
+ dj_cursor.execute(
+ _build_count_query("public", "xmin_wraparound_probe", False, None, None, None, xmin_bounds=bounds)
+ )
+ assert dj_cursor.fetchone()[0] == 10
class TestXminCapableTablesFromConn:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index d0f0d94251ed..7731a03f423b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -4900,8 +4900,8 @@ async def test_postgres_switch_to_xmin_rebuilds_table(team, postgres_config, pos
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.
+ # The table was rebuilt from scratch under xmin (the first xmin run reads the whole table),
+ # 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
)
diff --git a/products/warehouse_sources/backend/tests/management/test_reset_wrapped_xmin_cursors.py b/products/warehouse_sources/backend/tests/management/test_reset_wrapped_xmin_cursors.py
new file mode 100644
index 000000000000..3884123464c3
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/management/test_reset_wrapped_xmin_cursors.py
@@ -0,0 +1,102 @@
+import uuid
+from io import StringIO
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+
+class TestResetWrappedXminCursors(BaseTest):
+ def _schema(self, name: str, *, sync_type: str, sync_type_config: dict) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+ return ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source=source,
+ name=name,
+ sync_type=sync_type,
+ sync_type_config=sync_type_config,
+ )
+
+ def _xmin_schema(self, name: str, *, num_wraparound: int) -> ExternalDataSchema:
+ return self._schema(
+ name,
+ sync_type=ExternalDataSchema.SyncType.XMIN,
+ sync_type_config={
+ "xmin_last_value": 500,
+ "xmin_ceiling": (num_wraparound << 32) | 500,
+ "xmin_num_wraparound": num_wraparound,
+ },
+ )
+
+ def _running_job(self, schema: ExternalDataSchema) -> ExternalDataJob:
+ return ExternalDataJob.objects.create(
+ team_id=self.team.pk,
+ pipeline=schema.source,
+ schema=schema,
+ status=ExternalDataJob.Status.RUNNING,
+ pipeline_version=ExternalDataJob.PipelineVersion.V2,
+ )
+
+ def _run(self, **options) -> str:
+ out = StringIO()
+ call_command("reset_wrapped_xmin_cursors", stdout=out, **options)
+ return out.getvalue()
+
+ def test_dry_run_lists_wrapped_schemas_without_clearing_them(self) -> None:
+ schema = self._xmin_schema("orders", num_wraparound=12)
+
+ output = self._run()
+
+ assert str(schema.id) in output
+ schema.refresh_from_db()
+ assert schema.xmin_last_value == 500
+
+ def test_live_run_clears_only_wrapped_xmin_cursors(self) -> None:
+ wrapped = self._xmin_schema("orders", num_wraparound=12)
+ never_wrapped = self._xmin_schema("customers", num_wraparound=0)
+ incremental = self._schema(
+ "events",
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ sync_type_config={"incremental_field_last_value": "5"},
+ )
+
+ self._run(live_run=True)
+
+ wrapped.refresh_from_db()
+ assert wrapped.xmin_last_value is None
+ assert wrapped.xmin_ceiling is None
+ assert wrapped.xmin_num_wraparound is None
+
+ never_wrapped.refresh_from_db()
+ assert never_wrapped.xmin_last_value == 500
+
+ incremental.refresh_from_db()
+ assert incremental.sync_type_config["incremental_field_last_value"] == "5"
+
+ def test_schema_with_a_running_sync_keeps_its_cursor(self) -> None:
+ wrapped = self._xmin_schema("orders", num_wraparound=12)
+ self._running_job(wrapped)
+
+ output = self._run(live_run=True)
+
+ wrapped.refresh_from_db()
+ assert wrapped.xmin_last_value == 500
+ assert "sync is running" in output
+
+ def test_named_schemas_skip_the_wraparound_filter(self) -> None:
+ never_wrapped = self._xmin_schema("customers", num_wraparound=0)
+
+ self._run(live_run=True, schema_id=[str(never_wrapped.id)])
+
+ never_wrapped.refresh_from_db()
+ assert never_wrapped.xmin_last_value is None