Technical Advisory
Duplicate rows under a unique constraint: how to check
Published October 20, 2026
During 2026 we found two separate defects in Greenplum-lineage code that can leave two live rows carrying the same primary key. They are unrelated — different storage engines, different mechanisms, different failure modes — but they produce the same symptom, and neither raises an error when the damage is done.
This page is how to test your own cluster for both. Everything on it is read-only unless stated otherwise.
The two defects
1. Heap tables — reader-gang subtransaction snapshot loss
A reader gang segment process can run with a snapshot asserting that no subtransaction is open anywhere in the cluster. Meeting a row deleted inside a subtransaction, it concludes the deleting transaction aborted and permanently marks the row visible by writing a hint bit. The hint bit is written without WAL, so the primary and its mirror diverge on disk. The mirror-image failure on the insert side silently discards rows that should exist.
No cursor is required to reach the affected code path — any extended-protocol
Bind does it, which means every parameterized statement from JDBC,
psycopg2, ODBC or PQexecParams.
Full write-up.
2. Append-optimized tables — block directory placeholder overwrite
The uniqueness check on AO and AOCO tables never reads the data. It asks the block
directory whether a visible entry covers the tuple. A placeholder entry written at the
start of each command is supposed to cover the rows that command is inserting — but
when the first minipage fills, the flush overwrites the placeholder instead of leaving
it in place. From that point the statement cannot see its own rows, and duplicates
inside a single large INSERT are admitted.
The constraint works correctly against everything already committed, which is why this only appears at volume. Full write-up.
Before you run anything: turn the optimizer off
This matters more than any other instruction on the page. The obvious check is:
SET optimizer = off;
SELECT id, count(*)
FROM your_schema.your_table
GROUP BY id
HAVING count(*) > 1;
Without SET optimizer = off, that query can return nothing on a
table that is demonstrably corrupt. GPORCA knows the column is a primary key, knows a
primary key is unique, and plans a GroupAggregate that cannot produce a group larger
than one. It correctly answers the question it was asked. The Postgres planner makes no
such inference, which is why the sweep below sets the parameter first.
Check 1: sweep existing tables for damage
This script walks every heap, ao_row and ao_column table that
carries a valid unique constraint, counts duplicate keys, and records a per-row detail
query for anything it finds. Partial and expression indexes are out of scope.
Save it as detect-duplicate-unique-keys.sql and run it with
psql -f, once per database.
-- ===========================================================================
-- Detection sweep: duplicate live rows under a UNIQUE / PRIMARY KEY constraint
--
-- Covers both defects described on this page:
-- * heap tables -> reader-gang subtransaction snapshot loss
-- * append-optimized -> block directory placeholder overwrite
--
-- Read-only. Takes no locks beyond ordinary SELECT. Safe on a live cluster,
-- but a full sweep sequentially scans every table carrying a unique index --
-- run it off-peak, or narrow the schema filter below.
--
-- Run it on a non-production copy first and confirm the plans look right.
-- ===========================================================================
\set ON_ERROR_STOP on
\timing on
-- ---------------------------------------------------------------------------
-- CRITICAL. GPORCA derives uniqueness from the declared constraint and plans
-- "GROUP BY key HAVING count(*) > 1" as a GroupAggregate with no Sort beneath
-- it. The query then returns zero rows on a table that is visibly corrupt.
-- The Postgres planner makes no such inference, so it has to be used here.
-- ---------------------------------------------------------------------------
SET optimizer = off;
SET statement_timeout = 0;
SET gp_enable_relsize_collection = on;
DROP TABLE IF EXISTS dupkey_findings;
CREATE TEMP TABLE dupkey_findings (
schema_name text,
table_name text,
access_method text,
index_name text,
key_columns text,
dup_key_count bigint,
extra_rows bigint,
detail_query text,
checked_at timestamptz DEFAULT now()
);
DO $$
DECLARE
r record;
v_dupkeys bigint;
v_extra bigint;
v_sql text;
v_detail text;
v_scanned int := 0;
BEGIN
FOR r IN
SELECT n.nspname AS nsp,
c.relname AS rel,
am.amname AS am,
ci.relname AS idx,
string_agg(quote_ident(a.attname), ', ' ORDER BY k.ord) AS keycols
FROM pg_index i
JOIN pg_class c ON c.oid = i.indrelid
JOIN pg_class ci ON ci.oid = i.indexrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_am am ON am.oid = c.relam
CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = k.attnum
WHERE i.indisunique
AND i.indisvalid
AND c.relkind = 'r'
AND i.indpred IS NULL -- partial indexes: out of scope
AND i.indexprs IS NULL -- expression indexes: out of scope
AND am.amname IN ('heap', 'ao_row', 'ao_column')
AND n.nspname NOT IN ('pg_catalog','information_schema',
'gp_toolkit','pg_toast','pg_aoseg')
AND n.nspname NOT LIKE 'pg_temp%'
GROUP BY 1,2,3,4
ORDER BY 1,2,3,4
LOOP
v_scanned := v_scanned + 1;
v_sql := format(
'SELECT count(*), coalesce(sum(n - 1), 0) '
'FROM (SELECT %s, count(*) AS n FROM %I.%I '
' GROUP BY %s HAVING count(*) > 1) d',
r.keycols, r.nsp, r.rel, r.keycols);
BEGIN
EXECUTE v_sql INTO v_dupkeys, v_extra;
EXCEPTION WHEN OTHERS THEN
RAISE WARNING 'skipped %.% (%): %', r.nsp, r.rel, r.idx, SQLERRM;
CONTINUE;
END;
IF v_dupkeys > 0 THEN
v_detail := format(
'SET optimizer = off; '
'SELECT gp_segment_id, tableoid::regclass, ctid, %s FROM %I.%I '
'WHERE (%s) IN (SELECT %s FROM %I.%I GROUP BY %s HAVING count(*) > 1) '
'ORDER BY %s, gp_segment_id, ctid;',
r.keycols, r.nsp, r.rel,
r.keycols, r.keycols, r.nsp, r.rel, r.keycols,
r.keycols);
INSERT INTO dupkey_findings
(schema_name, table_name, access_method, index_name,
key_columns, dup_key_count, extra_rows, detail_query)
VALUES (r.nsp, r.rel, r.am, r.idx, r.keycols,
v_dupkeys, v_extra, v_detail);
RAISE WARNING 'DUPLICATE KEYS: %.% (%) via % -- % key(s), % extra row(s)',
r.nsp, r.rel, r.am, r.idx, v_dupkeys, v_extra;
END IF;
END LOOP;
RAISE NOTICE 'scanned % unique constraint(s)', v_scanned;
END
$$;
SELECT schema_name, table_name, access_method, index_name,
key_columns, dup_key_count, extra_rows
FROM dupkey_findings
ORDER BY extra_rows DESC, schema_name, table_name; An empty result means no duplicate live rows exist under any unique constraint at this moment. That is not proof of absence. It says nothing about rows lost to the insert-side variant of the heap defect, which no generic query can detect, and nothing about tables with no unique constraint.
Check 2: does your build still admit duplicates?
Check 1 looks for damage already done. This one tests whether the append-optimized defect is live in the binary you are running. It takes a few minutes and creates one throwaway table.
-- Does this build admit a duplicate inside a single INSERT?
DROP TABLE IF EXISTS t_dupcheck;
CREATE TABLE t_dupcheck (id bigint NOT NULL, pad text, PRIMARY KEY (id))
USING ao_row
DISTRIBUTED BY (id);
INSERT INTO t_dupcheck
SELECT CASE WHEN i = 200000 THEN 199999 ELSE i END, 'x'
FROM generate_series(1, 200000) i;
-- Expected on a fixed build: ERROR, duplicate key value violates unique constraint
-- On an affected build: INSERT 0 200000
If that reports INSERT 0 200000 rather than a unique violation, your build
carries the defect. Row-oriented append-optimized tables trip at around two hundred
thousand rows in a single statement at stock settings; column-oriented tables usually
need tens of millions, because the check inspects only the first non-dropped column and
a large block size lets one directory entry cover an enormous number of rows.
Raising gp_blockdirectory_minipage_size does not help. 161 is both the
default and the maximum, and any statement large enough still crosses it.
Confirming a finding
To see which segment and partition hold the duplicates:
SET optimizer = off;
SELECT gp_segment_id, tableoid::regclass AS partition, ctid, xmin, xmax, *
FROM your_schema.your_table
WHERE id = 12345
ORDER BY gp_segment_id, ctid;
Both rows will sit on the same segment, since the distribution key is always a subset
of the unique key. For the heap defect, the resurrected row is typically the one
carrying a non-zero xmax whose transaction did in fact commit.
For an authoritative confirmation on a heap table, REINDEX INDEX will fail
where a plain SELECT will not — but it takes an ACCESS EXCLUSIVE
lock, so use it on a specific finding rather than as a sweep. If the amcheck
extension is available, bt_index_check() with
heapallindexed => true is lighter and does not rewrite the index.
If you find duplicates
-
REINDEXis not a repair. It 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, not a mechanical one. The tuple headers tell you what happened, not which row your business considers correct. - After removing duplicates from a heap table, rewrite it — CTAS and
swap, or
VACUUM FULL. This is not cosmetic. The corrupt hint bits were written without WAL, so the primary and mirror hold different bytes. A rewrite re-sends the pages through WAL and brings the mirror back into agreement.REINDEXalone does not. - A fixed build stops new duplicates; it does not remove existing ones. Rows already on disk need a deduplication pass of their own.
- While you wait for a fixed build, the append-optimized defect is avoidable by splitting very large loads into several smaller statements — the failure is confined to what one statement wrote. Verify each load with the grouped count above rather than relying on the constraint alone.
Which distributions are affected
For the heap defect we reviewed
src/backend/utils/time/sharedsnapshot.c across the ecosystem in
September 2026:
- Apache Cloudberry (
main, 1.6.0) — subtransaction fields not propagated. Affected. - Greenplum 7 lineage (
gpdb-archive,main) — identical code. Affected. - WarehousePG (
main) — rewritten implementation that does propagate them. Not affected by the primary defect, though it does not copytakenDuringRecoveryor lowerTransactionXmin. - Greenplum 6.x — source not retrievable at the paths we tried. Unverified, which is not the same as safe.
- SynxDB — fixed in 4.8.0.
For the append-optimized defect, unique indexes on AO tables arrived in the Greenplum 7 generation and the block directory code beneath them is shared ancestry across that lineage. We have not run the reproduction against every distribution and we will not publish a verdict we have not verified. Check 2 above takes minutes on any build. SynxDB is fixed in 4.8.1.
Getting the fixes
Both fixes are being contributed upstream to Apache Cloudberry (Incubating). This is inherited open-source code — it is in our lineage too, and in both cases a long-lived defect went unnoticed by everyone downstream, ourselves included, until a customer's table produced two rows for one key.
If you are running an affected distribution and would rather have a patch directly than wait for it to flow through, or you want help interpreting a finding from the sweep, get in touch. There is nothing proprietary in either fix.