Skip to content

· Synx Data Labs

Two Rows, One Primary Key

How a missing field in a snapshot copy quietly corrupted heap tables across the Greenplum lineage — and why the obvious duplicate check returns nothing.

Product and Technology

A customer came to us with a table that had two live rows for the same primary key.

Not a constraint that had been dropped. Not a table loaded with the index disabled. A perfectly ordinary heap table, distributed by its primary key, with the unique index still in place and still happily returning both rows. REINDEX was the only thing that would admit something was wrong:

ERROR:  could not create unique index "orders_pkey"
DETAIL: Key (id)=(1) is duplicated.

The part that made it interesting was the check they hadn’t been able to run. The natural first move is:

SELECT id, count(*) FROM orders GROUP BY id HAVING count(*) > 1;

That query returned nothing. Not because the table was clean, but because GPORCA knows id is the primary key, and a primary key is unique, so a GROUP BY on it can’t produce a group larger than one. The optimizer planned a GroupAggregate with no Sort underneath and correctly answered the question it was asked. The database had been told the table was unique, so it believed the table was unique, and the corruption was invisible to the one query anyone would think to write.

Down to the snapshot

The corruption is a hint bit. Specifically HEAP_XMAX_INVALID, the bit that records “the transaction that deleted this row aborted, so ignore the xmax.”

Hint bits are an optimization. The first reader to resolve a tuple’s visibility writes the answer into the tuple header so the next reader doesn’t have to look it up again. They are also permanent, they are written through MarkBufferDirtyHint() without WAL, and the MVCC visibility path consults them before it consults any snapshot. A wrong hint bit is not a transient wrong answer. It’s a wrong answer cast in concrete, and — because it never reaches the WAL stream — one your mirror doesn’t even know about.

So: what makes a reader write HEAP_XMAX_INVALID on a row whose deleter went on to commit?

The reasoning inside HeapTupleSatisfiesMVCC is a chain, and it’s correct at every step:

XidInMVCCSnapshot_Local()   ->  XID_NOT_IN_SNAPSHOT     ("nobody is running this")
TransactionIdDidCommit()    ->  false                   (SUB_COMMITTED; parent hasn't committed)
                            ->  "then it must have aborted"
                            ->  HEAP_XMAX_INVALID

Every link holds if the first one is true. The transaction isn’t running and it hasn’t committed, so it aborted. There is no fourth option.

The first link was a lie.

The missing three fields

Greenplum-lineage systems split a query across a writer gang and one or more reader gangs. They have to agree on what they can see, so the writer publishes its local snapshot to shared memory and the readers pick it up. There are two routines that do the pickup, and one of them — readSharedLocalSnapshot_forCursor() in src/backend/utils/time/sharedsnapshot.c — copies the writer’s snapshot into the reader’s field by field:

snapshot->xmin  = dumpsnapshot->xmin;
snapshot->xmax  = dumpsnapshot->xmax;
snapshot->xcnt  = dumpsnapshot->xcnt;
memcpy(snapshot->xip, dumpsnapshot->xip, snapshot->xcnt * sizeof(TransactionId));
snapshot->curcid = dumpsnapshot->curcid;

That’s the whole copy. xmin, xmax, xcnt, xip[], curcid.

What’s not there is subxcnt, subxip[] and suboverflowed — the three fields that are the only way a subtransaction id reaches a snapshot. Top-level transaction ids travel in xip[], which is copied correctly, which is exactly why this never showed up in ordinary testing. Top-level transactions work fine.

And the fields aren’t missing because the data isn’t there. Two lines earlier the function calls RestoreSnapshot() and gets the writer’s complete snapshot, subtransaction array and all. It then reads five fields out of it and throws the rest away.

The reader ends up with a snapshot that asserts, with total confidence, that no session anywhere in the cluster has a subtransaction open.

There’s no second line of defence. You might expect the distributed snapshot to catch this, but DistributedLog_CommittedCheck() only knows about committed transactions — for one that is still running it returns COMMITTED_UNKNOWN. The local snapshot is the sole authority on “still running,” and the local snapshot had been handed a blank where the subtransactions should have been.

No cursor required

The function has “forCursor” in its name, which makes it sound like a narrow path. It is not.

The path is taken whenever DtxContextInfo.cursorContext is set, and that is just portal->is_extended_query. Three things set it:

  • DECLARE CURSOR — PerformCursorOpen() in portalcmds.c
  • an SPI cursor, which is every PL/pgSQL FOR rec IN SELECT ... — spi.c
  • any extended-protocol Bind — exec_bind_message() in postgres.c

The third one is the whole story. Every parameterized statement from JDBC, psycopg2, ODBC or PQexecParams goes through Bind. The comment in cdbdisp_query.c says it plainly: “Cursor queries and bind/execute path queries don’t run on the writer-gang QEs.”

Which is how the customer who found this hit it without using a single cursor. They use prepared statements, like everybody does.

Why it took years to surface

Three conditions have to line up, and the third is genuinely rare:

  1. The reader segment process holds subxcnt = 0 in its static snapshot struct. The cursor path never writes that field — it just doesn’t touch it — so whatever the process last had survives. A freshly forked reader, or one that warmed up during a window when no subtransaction existed anywhere, holds zero indefinitely.
  2. The tuple’s xmax is a subtransaction id. A top-level id is in xip[] and gets judged correctly.
  3. That subtransaction id is below the snapshot’s xmax. Which requires some third transaction to have committed after it, to push xmax past it. Otherwise the xid >= xmax means in progress range check at the top of XidInMVCCSnapshot() short-circuits, and the missing subxip[] is never consulted at all.

Condition 3 is the one that makes this a ghost. The same workload runs for months in the clear, then the timing lines up once and leaves permanent damage behind. By the time a REINDEX fails, whatever you’d need to reconstruct the sequence is long gone.

Note also that most subtransactions in the wild aren’t written as SAVEPOINT. Every PL/pgSQL EXCEPTION block opens one. Plenty of teams satisfy condition 2 constantly without having typed the word savepoint.

The fix, and the fix behind the fix

The direct fix is small: copy the three fields. We also copy takenDuringRecovery, which XidInMVCCSnapshot_Local() consults as well, and lower TransactionXmin to the snapshot’s xmin so that the pg_subtrans lookups the suboverflowed path performs stay inside the valid range.

Worth noting: the defect ran in both directions. The same stale process-static residue could also claim a finished subtransaction was still running, which hides rows that ought to be visible. Copying the fields closes both.

The second change matters more than the first, and it isn’t about snapshots at all. Any code path that stamps HEAP_XMAX_INVALID or HEAP_XMIN_INVALID on a transaction id that is still running is making an unrecoverable decision on incomplete information. So we now withhold both hint bits from a running xid, full stop. The snapshot bug is fixed; the class of bug that turns a bad snapshot into permanent on-disk corruption is fixed separately. If some other path ever delivers a mis-populated snapshot, the worst case is now a wrong answer for one query, not a wrong answer forever.

That’s the part I’d take away from this if you’re working anywhere near a storage engine. The snapshot bug was the cause. The hint bit was the reason it mattered.

Testing something that only happens by accident

The test lives in src/test/isolation2/sql/xmax_reader_subxact.sql and drives all three entry points. Each scenario:

  1. warms a reader gang up while no subtransaction exists anywhere — establishing condition 1 deliberately;
  2. has a second session DELETE a row inside a subtransaction and re-INSERT the key at top level — condition 2;
  3. has a third session commit, so the subxid lands inside the reader’s snapshot range — condition 3;
  4. reads, then asserts exactly one row survives and REINDEX still succeeds.

Without the fix, every scenario leaves two live rows and REINDEX fails.

The third scenario needed its own harness. The isolation2 driver speaks only the simple query protocol, so it structurally cannot exercise the extended-protocol Bind path — the very path that makes this bug reach ordinary applications. We wrote xmax_extquery_test, a small libpq helper in the style of extended_protocol_test, which performs the four-connection interleaving, prints one fixed line, and leaves the table for the test file to assert on.

That gap is worth dwelling on. A test framework that can’t speak the protocol your users speak has a blind spot shaped exactly like your users. This bug lived in that blind spot.

How to check your own tables

SET optimizer = off;

SELECT id, count(*)
FROM   your_table
GROUP  BY id
HAVING count(*) > 1;

The SET is not optional. Without it you get the same reassuring empty result the customer got, for the reason described at the top of this post.

To confirm a specific finding authoritatively:

REINDEX INDEX myschema.my_pkey;   -- ACCESS EXCLUSIVE lock

or, if amcheck is available, the lighter:

SELECT bt_index_check('myschema.my_pkey'::regclass, heapallindexed => true);

A clean result is not proof of absence. It means no duplicate live rows exist under a unique constraint at this moment. It says nothing about rows lost to the xmin-side variant, and nothing about tables without unique constraints.

And REINDEX is not a repair. It fails on an affected table; it does not fix one. The duplicate rows have to be removed first, and which row to keep is a business decision rather than a mechanical one. After removing them, rewrite the table — CTAS and swap, or VACUUM FULL. That is not cosmetic: the corrupt hint bits were written without WAL, so the primary and mirror hold different bytes on disk. A rewrite re-sends the pages through WAL and brings the mirror back into agreement. REINDEX alone does not.

Where this leaves the ecosystem

sharedsnapshot.c is old, widely-inherited code. We checked what’s public:

  • Apache Cloudberry (main, and 1.6.0): the three fields appear nowhere in the file. Affected.
  • Greenplum 7 lineage (gpdb-archive, main): identical code. Affected.
  • WarehousePG (main): has a substantially rewritten shared-snapshot implementation that does propagate subxcnt, subxip[] and suboverflowed. Not affected by the primary defect. It doesn’t copy takenDuringRecovery or lower TransactionXmin, so the suboverflowed path there deserves a second look, but the main hole is closed.
  • Greenplum 6.x: we couldn’t retrieve the source at the paths we tried. Unknown, which is not the same as safe.

We’re reporting this upstream to Apache Cloudberry. This is inherited code — it’s in our lineage too, and the honest framing is that a long-lived defect in shared open-source infrastructure went unnoticed by everyone downstream, us included, until a customer’s REINDEX failed.

If you operate any of the affected distributions, we publish a standalone duplicate-key check — a read-only sweep across every table carrying a unique constraint, plus guidance on confirming and remediating a finding. One warning about running it: set optimizer = off first, or you will get the same reassuring empty result the customer got.

FAQ

How can a heap table have two live rows under a unique index? A reader gang segment process can run with a snapshot that reports no subtransaction is open anywhere in the cluster. When it meets a row deleted inside a subtransaction, it concludes the deleting transaction aborted and permanently marks the row visible by writing the HEAP_XMAX_INVALID hint bit. The index still exists and still returns both rows, and no constraint violation is raised at any point.

Why does GROUP BY with HAVING count(*) > 1 return nothing on a corrupt table? GPORCA derives uniqueness from the declared primary key, so it plans a GroupAggregate with no Sort beneath it — a plan that cannot produce a group larger than one. It correctly answers the question it was asked. Set optimizer = off before running the check, or you will get a reassuring empty result on a table that is demonstrably corrupt.

Do I need to be using cursors to be exposed? No. The vulnerable path is taken whenever DtxContextInfo.cursorContext is set, which is portal->is_extended_query. That covers DECLARE CURSOR, every PL/pgSQL FOR rec IN SELECT, and any extended-protocol Bind — meaning every parameterized statement from JDBC, psycopg2, ODBC or PQexecParams. The site that found this uses no cursors at all.

Does REINDEX repair an affected table? No. REINDEX fails on an affected table, it does not fix one. The duplicate rows have to be removed first, and choosing which row to keep is a business decision. After removing them, rewrite the table — the corrupt hint bits were written without WAL, so the primary and mirror hold different bytes, and only a rewrite brings them back into agreement.

Which distributions are affected? We reviewed sharedsnapshot.c across the ecosystem in September 2026. Apache Cloudberry (main and 1.6.0) and the Greenplum 7 lineage do not propagate the subtransaction fields and are affected. WarehousePG has a substantially rewritten implementation that does propagate them and is not affected by the primary defect. Greenplum 6.x could not be retrieved at the paths we tried and is unverified, which is not the same as safe.


Found, root-caused and fixed by the SynxDB engineering team, September 2026. The fix ships in SynxDB 4.8.0.

A follow-up post covers a second, unrelated duplicate-key defect in the same lineage — this one in append-optimized storage: One INSERT, two rows, one primary key.