Skip to content

feat(warehouse): add xmin read path for postgres source - #64721

Merged
danielcarletti merged 7 commits into
masterfrom
posthog-code/xmin-pr2-read-path
Jun 19, 2026
Merged

danielcarletti merged 7 commits into
masterfrom
posthog-code/xmin-pr2-read-path

Conversation

@danielcarletti

Copy link
Copy Markdown
Contributor

Problem

This is PR 2 of 5 in the xmin replication stack (foundation merged in #64415). Some Postgres tables have no good updated_at cursor, so today the only incremental option is CDC (heavyweight) or full refresh. xmin replication uses the hidden xmin system 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=xmin Postgres sync now actually reads changed rows.

Changes

  • Ceiling capture (postgres.py): at sync start, on the row-serving setup connection, capture pg_snapshot_xmin(pg_current_snapshot()) as both xid8 (durable, wraparound-safe) and bare xid (compared against tuple xmin). PG13+ only; a partitioned parent or a table without a PK raises a clear, non-retryable error.
  • Bounded query (_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 seeds lower = 0 (full read below the ceiling). Single epoch wrap switches to the >= old OR < new range; a multi-wrap drift forces a full re-read. Row filters AND into the predicate; the count query uses the same bound.
  • Discovery (source.py): supports_xmin advertised per table for heap tables + matviews on PG13+ (not partitioned parents, views, or foreign tables), plus a synthetic xmin incremental field (is_indexed=False, so the unindexed-scan warning fires). Postgres-only β€” populated solely here; every other source keeps the False default.
  • Incremental write + persist-then-advance (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 with update_xmin_state only 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_xmin projection, row filters, count query) and ceiling derivation (PG13 gate, first-run seed, wrap detection).
  • Existing 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-sources skill before touching the source code.

Decisions worth a reviewer's eye:

  • xmin state read off the schema in source_for_pipeline, not threaded through SourceInputs. The plan suggested reading it in import_data_sync.py into the generic inputs object. source_for_pipeline already loads the ExternalDataSchema, so reading schema.is_xmin / xmin_last_value / xmin_num_wraparound there keeps the generic SourceInputs Postgres-agnostic. No shared layer learns about xmin.
  • Touched pipeline.py / pipeline_v3/pipeline.py / typings.py beyond 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 on SourceResponse to be persisted at completion. The advance logic is factored into one shared advance_xmin_state helper used by both pipelines, mirroring the existing finalize_desc_sort_incremental_value advance point.
  • _ph_xmin is 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

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
@danielcarletti danielcarletti self-assigned this Jun 18, 2026
@pr-assigner-resolver-posthog
pr-assigner-resolver-posthog Bot requested a review from a team June 18, 2026 21:42
@greptile-apps

greptile-apps Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
Fix 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

Comment on lines +1618 to +1622
# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 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.

Suggested change
# 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed β€” switched to sql.Composed concatenation (query + sql.SQL("...")) so row filter values containing { or } cannot be misinterpreted as format placeholders.

Comment on lines +1419 to +1430
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
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!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
danielcarletti and others added 5 commits June 19, 2026 12:07
…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>
@danielcarletti
danielcarletti merged commit cb7f413 into master Jun 19, 2026
226 checks passed
@danielcarletti
danielcarletti deleted the posthog-code/xmin-pr2-read-path branch June 19, 2026 17:09
inkeep Bot added a commit to PostHog/posthog.com that referenced this pull request Jun 19, 2026
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.
@deployment-status-posthog

deployment-status-posthog Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Deploy status

Environment Status Deployed At Workflow
dev βœ… Deployed 2026-06-19 17:56 UTC Run
prod-us βœ… Deployed 2026-06-19 18:09 UTC Run
prod-eu βœ… Deployed 2026-06-19 18:12 UTC Run

fuziontech added a commit that referenced this pull request Jun 19, 2026
…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)
  ...
danielcarletti pushed a commit to PostHog/posthog.com that referenced this pull request Jul 16, 2026
#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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants