Repository navigation
feat(warehouse): add xmin read path for postgres source - #64721
Conversation
Capture the snapshot xmin ceiling at sync start on the row-serving connection, build the bounded xmin query (single-range, wraparound OR-range, first-run full read), advertise xmin in discovery, and persist the ceiling at job completion. Generated-By: PostHog Code Task-Id: e5520cbc-5866-4ac6-a2e7-f429779cac84
Prompt To Fix All With AIFix the following 2 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 2
posthog/temporal/data_imports/sources/postgres/postgres.py:1618-1622
The ORDER BY and LIMIT are appended by calling `query.as_string()`, inserting that rendered SQL into an f-string, and then wrapping it in a new `sql.SQL(template).format()`. If any row filter value contains `{` or `}` β for example, a JSON string literal like `"data" = '{"type": "admin"}'` β psycopg3 would parse `{"type": "admin"}` as a format key and raise a `KeyError` at runtime. `sql.Composed` supports `+` concatenation directly, so the `as_string()` round-trip is unnecessary.
```suggestion
# 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 ordered
```
### Issue 2 of 2
posthog/temporal/data_imports/sources/postgres/postgres.py:1419-1430
`pg_current_snapshot()` is called twice in the same SELECT, producing both the `xid8` and bare `xid` representations. While PostgreSQL evaluates it consistently within a single statement, there's no need for the double call: `ceiling_xid` is just the low 32 bits of `ceiling_xid8`. Deriving it in Python removes the redundant server call and makes the relationship between the two values explicit.
```suggestion
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
```
Reviews (1): Last reviewed commit: "feat(warehouse): add xmin read path for ..." | Re-trigger Greptile |
| # ORDER BY the cast cursor so the offset-resume path stays correct on a connection drop. | ||
| ordered = sql.SQL(cast(LiteralString, f"{query.as_string()} ORDER BY xmin::text::bigint ASC")).format() | ||
| if add_sampling: | ||
| return sql.SQL(cast(LiteralString, f"{ordered.as_string()} LIMIT 1000")).format() | ||
| return ordered |
There was a problem hiding this comment.
The ORDER BY and LIMIT are appended by calling
query.as_string(), inserting that rendered SQL into an f-string, and then wrapping it in a new sql.SQL(template).format(). If any row filter value contains { or } β for example, a JSON string literal like "data" = '{"type": "admin"}' β psycopg3 would parse {"type": "admin"} as a format key and raise a KeyError at runtime. sql.Composed supports + concatenation directly, so the as_string() round-trip is unnecessary.
| # ORDER BY the cast cursor so the offset-resume path stays correct on a connection drop. | |
| ordered = sql.SQL(cast(LiteralString, f"{query.as_string()} ORDER BY xmin::text::bigint ASC")).format() | |
| if add_sampling: | |
| return sql.SQL(cast(LiteralString, f"{ordered.as_string()} LIMIT 1000")).format() | |
| return ordered | |
| # 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 ordered |
Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/temporal/data_imports/sources/postgres/postgres.py
Line: 1618-1622
Comment:
The ORDER BY and LIMIT are appended by calling `query.as_string()`, inserting that rendered SQL into an f-string, and then wrapping it in a new `sql.SQL(template).format()`. If any row filter value contains `{` or `}` β for example, a JSON string literal like `"data" = '{"type": "admin"}'` β psycopg3 would parse `{"type": "admin"}` as a format key and raise a `KeyError` at runtime. `sql.Composed` supports `+` concatenation directly, so the `as_string()` round-trip is unnecessary.
```suggestion
# 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 ordered
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fixed β switched to sql.Composed concatenation (query + sql.SQL("...")) so row filter values containing { or } cannot be misinterpreted as format placeholders.
| cursor.execute( | ||
| sql.SQL( | ||
| "SELECT pg_snapshot_xmin(pg_current_snapshot())::text::bigint, " | ||
| "(pg_snapshot_xmin(pg_current_snapshot())::xid)::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 = int(row[1]) | ||
| num_wraparound = ceiling_xid8 >> 32 |
There was a problem hiding this comment.
pg_current_snapshot() is called twice in the same SELECT, producing both the xid8 and bare xid representations. While PostgreSQL evaluates it consistently within a single statement, there's no need for the double call: ceiling_xid is just the low 32 bits of ceiling_xid8. Deriving it in Python removes the redundant server call and makes the relationship between the two values explicit.
| cursor.execute( | |
| sql.SQL( | |
| "SELECT pg_snapshot_xmin(pg_current_snapshot())::text::bigint, " | |
| "(pg_snapshot_xmin(pg_current_snapshot())::xid)::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 = int(row[1]) | |
| num_wraparound = ceiling_xid8 >> 32 | |
| 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 |
Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/temporal/data_imports/sources/postgres/postgres.py
Line: 1419-1430
Comment:
`pg_current_snapshot()` is called twice in the same SELECT, producing both the `xid8` and bare `xid` representations. While PostgreSQL evaluates it consistently within a single statement, there's no need for the double call: `ceiling_xid` is just the low 32 bits of `ceiling_xid8`. Deriving it in Python removes the redundant server call and makes the relationship between the two values explicit.
```suggestion
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
```
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Fixed β pg_current_snapshot() now called once; ceiling_xid derived as ceiling_xid8 & 0xFFFFFFFF in Python.
- Resolve import conflict with SSLRequiredError from master
- Fix ORDER BY/LIMIT appended via as_string() f-string β use sql.Composed
concatenation directly to avoid KeyError when filter values contain { or }
- Derive ceiling_xid from ceiling_xid8 in Python instead of calling
pg_current_snapshot() twice in the same SELECT
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
β¦params Tests asserting postgres_source call args missed is_xmin and xmin_last_value added in the xmin read path, and test_incremental_fields_postgres missed the synthetic xmin entry now advertised for ordinary PG13+ tables. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add is_xmin and xmin_last_value to postgres_source mock assertions in test_import_data.py (missed when the params were added) - Include synthetic xmin entry in test_incremental_fields_postgres expected result - Collapse cursor.execute call to single line per ruff format Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Widen _build_xmin_query row_filter_conditions from list[Composed] to list[Composable] to match render_psycopg_row_filter_conditions return type - Expand xmin_ceiling guard to include xid8 and num_wraparound so mypy can narrow them from Optional[int] before use Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Calling query.as_string() and embedding the result in an f-string, then
passing that to sql.SQL(...).format() is fragile: any literal value
containing { or } (e.g. a JSON row-filter value) would be misinterpreted
as a psycopg format placeholder at the .format() call site.
Use sql.Composed + concatenation directly instead.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
β¦mock assertions postgres_source() now receives xmin_num_wraparound from the schema, so the test mock assertions must include it. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds documentation for the new xmin sync method introduced in PostHog/posthog#64721. Includes a new subsection under Sync methods describing xmin's purpose, requirements (PG13+, primary key, heap tables/matviews only), and limitations (no delete tracking). Also updates the schema filter list to include xmin.
β¦fill-admin * origin/master: (203 commits) fix(experiments): add missing event properties to the backend events on the recalculation workflow. (#64923) refactor(capture): decouple v1 RequestContext from analytics Context (#64184) feat(data-warehouse): add direct_query_enabled toggle to data sources (#64685) feat(data-warehouse): persist duckling bucket on DuckgresServer (#64919) fix(dev): strip read-denied $HOME dirs from sandbox PATH (#64768) fix(mcp-analytics): keep muted text readable inside quill subtrees (#64898) feat(skills): add Scouts tab backed by a generic skill category (#64796) fix(ducklake): make get_instance_region a lazy import in common helpers (#64913) fix(replay-vision): drop vestigial scanner_type from VisionAction selection (#64737) feat(warehouse): add xmin read path for postgres source (#64721) feat(warehouse): add per-table xmin sync radio (flag-gated) (#64718) feat(warehouse): validate xmin sync type and surface availability (#64723) fix(data-warehouse): CDC improvements β fix dead orphan-slot sweeper (#64725) feat(data-warehouse): scaffold Razorpay source (#64484) fix(dags): read duckling backfill bucket from stored catalog (#64909) feat(inbox): add archived tab with restore (#64876) feat(signals): surface a banner when inbox filters are active (#64811) fix(lemon-dialog): isolate nested form dialogs with unique kea logic keys (#62113) feat(session-replay): show event triggers on mobile replay settings tab (#64859) fix(preflight): restore kafka connectivity probe (#58743) ...
#17804) * docs: add xmin sync method documentation for Postgres source * docs(sources): add xmin sync method to sources index page Adds documentation for the new xmin sync method introduced in PostHog/posthog#64721. Includes a new subsection under Sync methods describing xmin's purpose, requirements (PG13+, primary key, heap tables/matviews only), and limitations (no delete tracking). Also updates the schema filter list to include xmin. --------- Co-authored-by: inkeep[bot] <257615677+inkeep[bot]@users.noreply.github.com>
Problem
This is PR 2 of 5 in the xmin replication stack (foundation merged in #64415). Some Postgres tables have no good
updated_atcursor, so today the only incremental option is CDC (heavyweight) or full refresh. xmin replication uses the hiddenxminsystem column as a cursorless incremental cursor, riding the existing per-schema pipeline rather than CDC's out-of-band machinery.This PR wires the backend read path: an
sync_type=xminPostgres sync now actually reads changed rows.Changes
postgres.py): at sync start, on the row-serving setup connection, capturepg_snapshot_xmin(pg_current_snapshot())as bothxid8(durable, wraparound-safe) and barexid(compared against tuplexmin). PG13+ only; a partitioned parent or a table without a PK raises a clear, non-retryable error._build_xmin_query):SELECT xmin::text::bigint AS _ph_xmin, β¦ WHERE xmin::text::bigint >= lower AND < ceiling ORDER BY xmin::text::bigint ASC. First run seedslower = 0(full read below the ceiling). Single epoch wrap switches to the>= old OR < newrange; a multi-wrap drift forces a full re-read. Row filters AND into the predicate; the count query uses the same bound.source.py):supports_xminadvertised per table for heap tables + matviews on PG13+ (not partitioned parents, views, or foreign tables), plus a syntheticxminincremental field (is_indexed=False, so the unindexed-scan warning fires). Postgres-only β populated solely here; every other source keeps theFalsedefault.pipeline.py,pipeline_v3/pipeline.py,extract.py): xmin writes via the incremental merge path (PK upsert), never a full-refresh overwrite that would wipe earlier data on the delta-only second sync. The ceiling is persisted withupdate_xmin_stateonly at job completion, so a mid-run crash re-reads the window (idempotent on PK).How did you test this code?
I'm an agent (PostHog Code). Automated tests I ran locally, all green:
TestBuildXminQuery,TestCaptureXminCeiling,TestXminCapableTablesFromConnβ new unit coverage for query construction (single-range, wraparound, first-run,_ph_xminprojection, row filters, count query) and ceiling derivation (PG13 gate, first-run seed, wrap detection).TestBuildQuery/TestBuildCountQuery/TestPostgresSourceNonRetryableErrors(90 tests) and the V3 pipeline test still pass.End-to-end createβsyncβre-sync against a live Postgres is Agent 5's integration test (depends on this PR).
π€ Agent context
Autonomy: Human-driven (agent-assisted)
Built with PostHog Code (Claude Opus) as agent 2 of a pre-written 5-PR plan. Invoked the
/implementing-warehouse-sourcesskill before touching the source code.Decisions worth a reviewer's eye:
source_for_pipeline, not threaded throughSourceInputs. The plan suggested reading it inimport_data_sync.pyinto the generic inputs object.source_for_pipelinealready loads theExternalDataSchema, so readingschema.is_xmin/xmin_last_value/xmin_num_wraparoundthere keeps the genericSourceInputsPostgres-agnostic. No shared layer learns about xmin.pipeline.py/pipeline_v3/pipeline.py/typings.pybeyond the literal file list in the plan. These were required for correctness: without forcing the incremental write type, xmin's delta-only second sync would overwrite the whole table (data loss), and the captured ceiling has to surface onSourceResponseto be persisted at completion. The advance logic is factored into one sharedadvance_xmin_statehelper used by both pipelines, mirroring the existingfinalize_desc_sort_incremental_valueadvance point._ph_xminis force-projected and lands as a column in the warehouse table (per the stack's shared contract), added explicitly to the Arrow schema so the row zip aligns.Created with PostHog Code