[PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

Started by Ante Krešić6 months ago10 messageshackers
Jump to latest
#1Ante Krešić
ante@tigerdata.com

Hi,

ALTER TABLE ... REPLICA IDENTITY USING INDEX checks key columns by
reading attnotnull, but since a379061a22a8 (PG 18, NOT NULL NOT VALID)
attnotnull is set even when the constraint is unvalidated. An index on
a column that actually contains NULLs is therefore accepted as replica
identity:

CREATE TABLE t (id int);
INSERT INTO t VALUES (1), (NULL), (2);
ALTER TABLE t ADD CONSTRAINT id_nn NOT NULL id NOT VALID;
CREATE UNIQUE INDEX t_idx ON t(id);
ALTER TABLE t REPLICA IDENTITY USING INDEX t_idx; -- accepted
-- relreplident => 'i'

This would cause data divergence on UPDATE/DELETE targeting NULL-keyed rows.

Patch follows same pattern as d9ffc27291f (the same bugfix for identity
columns);
after the attnotnull check, look up the constraint and reject if
!convalidated.

Thanks,
Ante Kresic
Staff Engineer | Tiger Data
TigerData.com

Attachments:

t139639_1
0001-Reject-REPLICA-IDENTITY-USING-INDEX-on-column-with-i.patchtext/x-patch; charset=US-ASCII; name=0001-Reject-REPLICA-IDENTITY-USING-INDEX-on-column-with-i.patchDownload+68-1
#2Aleksander Alekseev
aleksander@tigerdata.com
In reply to: Ante Krešić (#1)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

Hi Ante,

ALTER TABLE ... REPLICA IDENTITY USING INDEX checks key columns by
reading attnotnull, but since a379061a22a8 (PG 18, NOT NULL NOT VALID)
attnotnull is set even when the constraint is unvalidated. An index on
a column that actually contains NULLs is therefore accepted as replica
identity:

CREATE TABLE t (id int);
INSERT INTO t VALUES (1), (NULL), (2);
ALTER TABLE t ADD CONSTRAINT id_nn NOT NULL id NOT VALID;
CREATE UNIQUE INDEX t_idx ON t(id);
ALTER TABLE t REPLICA IDENTITY USING INDEX t_idx; -- accepted
-- relreplident => 'i'

This would cause data divergence on UPDATE/DELETE targeting NULL-keyed rows.

Patch follows same pattern as d9ffc27291f (the same bugfix for identity columns);
after the attnotnull check, look up the constraint and reject if !convalidated.

Thanks for the patch. This clearly seems to be a bug.

The patch is well written and has regression tests. The tests pass, I
also tested under Valgrind. All in all the patch looks good to me.

I added the patch to the commitfest application to make sure it's not
going to be lost [1]https://commitfest.postgresql.org/patch/6801/. Please add yourself as the author.

[1]: https://commitfest.postgresql.org/patch/6801/

--
Best regards,
Aleksander Alekseev

#3Masahiko Sawada
sawada.mshk@gmail.com
In reply to: Aleksander Alekseev (#2)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

On Tue, May 26, 2026 at 2:36 AM Aleksander Alekseev
<aleksander@tigerdata.com> wrote:

Hi Ante,

ALTER TABLE ... REPLICA IDENTITY USING INDEX checks key columns by
reading attnotnull, but since a379061a22a8 (PG 18, NOT NULL NOT VALID)
attnotnull is set even when the constraint is unvalidated. An index on
a column that actually contains NULLs is therefore accepted as replica
identity:

CREATE TABLE t (id int);
INSERT INTO t VALUES (1), (NULL), (2);
ALTER TABLE t ADD CONSTRAINT id_nn NOT NULL id NOT VALID;
CREATE UNIQUE INDEX t_idx ON t(id);
ALTER TABLE t REPLICA IDENTITY USING INDEX t_idx; -- accepted
-- relreplident => 'i'

This would cause data divergence on UPDATE/DELETE targeting NULL-keyed rows.

Patch follows same pattern as d9ffc27291f (the same bugfix for identity columns);
after the attnotnull check, look up the constraint and reject if !convalidated.

Good catch!

Thanks for the patch. This clearly seems to be a bug.

The patch is well written and has regression tests. The tests pass, I
also tested under Valgrind. All in all the patch looks good to me.

Regarding the patch,

+               /*
+                * attnotnull is set even for invalid (NOT VALID) not-null
+                * constraints, which do not prove the column is
null-free, so verify
+                * that the underlying constraint is validated.
+                */
+               {
+                       HeapTuple       contup;
+                       Form_pg_constraint conForm;
+
+                       contup =
findNotNullConstraintAttnum(RelationGetRelid(rel), attno);
+                       if (!HeapTupleIsValid(contup))
+                               elog(ERROR, "cache lookup failed for
not-null constraint on column \"%s\" of relation \"%s\"",
+                                        NameStr(attr->attname),
RelationGetRelationName(rel));
+
+                       conForm = (Form_pg_constraint) GETSTRUCT(contup);
+                       if (!conForm->convalidated)
+                               ereport(ERROR,
+
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                                               errmsg("index \"%s\"
cannot be used as replica identity because column \"%s\" has an
invalid not-null constraint",
+
RelationGetRelationName(indexRel),
+
NameStr(attr->attname)),
+                               /*- translator: second %s is a
constraint characteristic such as NOT VALID */
+                                               errdetail("The
constraint \"%s\" is marked %s.",
+
NameStr(conForm->conname), "NOT VALID"),
+                                               errhint("You might
need to validate it using %s.",
+                                                               "ALTER
TABLE ... VALIDATE CONSTRAINT"));
+                       heap_freetuple(contup);
+               }

It would be better to factor the into a common function that checks
whether the column has a valid NOT NULL constraint, to remove the code
duplication.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

#4Chao Li
li.evan.chao@gmail.com
In reply to: Masahiko Sawada (#3)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

On Jun 12, 2026, at 02:48, Masahiko Sawada <sawada.mshk@gmail.com> wrote:

On Tue, May 26, 2026 at 2:36 AM Aleksander Alekseev
<aleksander@tigerdata.com> wrote:

Hi Ante,

ALTER TABLE ... REPLICA IDENTITY USING INDEX checks key columns by
reading attnotnull, but since a379061a22a8 (PG 18, NOT NULL NOT VALID)
attnotnull is set even when the constraint is unvalidated. An index on
a column that actually contains NULLs is therefore accepted as replica
identity:

CREATE TABLE t (id int);
INSERT INTO t VALUES (1), (NULL), (2);
ALTER TABLE t ADD CONSTRAINT id_nn NOT NULL id NOT VALID;
CREATE UNIQUE INDEX t_idx ON t(id);
ALTER TABLE t REPLICA IDENTITY USING INDEX t_idx; -- accepted
-- relreplident => 'i'

This would cause data divergence on UPDATE/DELETE targeting NULL-keyed rows.

Patch follows same pattern as d9ffc27291f (the same bugfix for identity columns);
after the attnotnull check, look up the constraint and reject if !convalidated.

Good catch!

Thanks for the patch. This clearly seems to be a bug.

The patch is well written and has regression tests. The tests pass, I
also tested under Valgrind. All in all the patch looks good to me.

Regarding the patch,

+               /*
+                * attnotnull is set even for invalid (NOT VALID) not-null
+                * constraints, which do not prove the column is
null-free, so verify
+                * that the underlying constraint is validated.
+                */
+               {
+                       HeapTuple       contup;
+                       Form_pg_constraint conForm;
+
+                       contup =
findNotNullConstraintAttnum(RelationGetRelid(rel), attno);
+                       if (!HeapTupleIsValid(contup))
+                               elog(ERROR, "cache lookup failed for
not-null constraint on column \"%s\" of relation \"%s\"",
+                                        NameStr(attr->attname),
RelationGetRelationName(rel));
+
+                       conForm = (Form_pg_constraint) GETSTRUCT(contup);
+                       if (!conForm->convalidated)
+                               ereport(ERROR,
+
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                                               errmsg("index \"%s\"
cannot be used as replica identity because column \"%s\" has an
invalid not-null constraint",
+
RelationGetRelationName(indexRel),
+
NameStr(attr->attname)),
+                               /*- translator: second %s is a
constraint characteristic such as NOT VALID */
+                                               errdetail("The
constraint \"%s\" is marked %s.",
+
NameStr(conForm->conname), "NOT VALID"),
+                                               errhint("You might
need to validate it using %s.",
+                                                               "ALTER
TABLE ... VALIDATE CONSTRAINT"));
+                       heap_freetuple(contup);
+               }

It would be better to factor the into a common function that checks
whether the column has a valid NOT NULL constraint, to remove the code
duplication.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Hi Masahiko-san,

As you are on this topic, I reported a related bug about REPLICA IDENTITY USING INDEX some time ago: when ALTER TABLE ... ALTER COLUMN TYPE rebuilds an index used as replica identity on a partitioned table, the rebuilt partition indexes can silently lose their indisreplident marking. The parent index keeps its replica identity flag, but the corresponding child partition index is rebuilt with the flag cleared, leaving the partition without the expected replica identity.

Would you please take a look at it as well when you get a chance? This is an old bug, not for v19, so no rush at all. It’s here: https://commitfest.postgresql.org/patch/6440/.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

#5Alvaro Herrera
alvherre@kurilemu.de
In reply to: Masahiko Sawada (#3)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

On 2026-Jun-11, Masahiko Sawada wrote:

It would be better to factor the into a common function that checks
whether the column has a valid NOT NULL constraint, to remove the code
duplication.

I agree, we should have a function like
bool
notNullConstraintValidated(Oid relid, AttrNumber attnum)
in pg_constraint.c, and use it in the various places where we only care
about the constraint validation status.

--
Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/

#6Alvaro Herrera
alvherre@kurilemu.de
In reply to: Alvaro Herrera (#5)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

On 2026-Jun-12, Álvaro Herrera wrote:

On 2026-Jun-11, Masahiko Sawada wrote:

It would be better to factor the into a common function that checks
whether the column has a valid NOT NULL constraint, to remove the code
duplication.

I agree, we should have a function like
bool
notNullConstraintValidated(Oid relid, AttrNumber attnum)
in pg_constraint.c, and use it in the various places where we only care
about the constraint validation status.

I take that back. I think this change would warrant merging this new
code with the existing verifyNotNullPKCompatible(), which wants to do
pretty much the same; but that's probably a larger refactoring that
should be done in pg20 only. So maybe we can just do the simple thing
(Ante's patch, mostly, I think) for this backpatchable bug fix, then
change things more fully later on.

--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/

#7Alvaro Herrera
alvherre@kurilemu.de
In reply to: Ante Krešić (#1)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

On 2026-May-14, Ante Krešić wrote:

+			if (!conForm->convalidated)
+				ereport(ERROR,
+						errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+						errmsg("index \"%s\" cannot be used as replica identity because column \"%s\" has an invalid not-null constraint",
+							   RelationGetRelationName(indexRel),
+							   NameStr(attr->attname)),
+				/*- translator: second %s is a constraint characteristic such as NOT VALID */
+						errdetail("The constraint \"%s\" is marked %s.",
+								  NameStr(conForm->conname), "NOT VALID"),
+						errhint("You might need to validate it using %s.",
+								"ALTER TABLE ... VALIDATE CONSTRAINT"));

I'd rather make this error be

+           ereport(ERROR,
+                   errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                   errmsg("cannot use index \"%s\" as replica identity",
+                          RelationGetRelationName(indexRel),
+                          NameStr(attr->attname)),
+                   /*- translator: third %s is a constraint characteristic such as NOT VALID */
+                   errdetail("The constraint \"%s\" on column \"%s\" is marked %s.",
+                             NameStr(conForm->conname), NameStr(attr->attname), "NOT VALID"),
+                   errhint("You might need to validate it using %s.",
+                           "ALTER TABLE ... VALIDATE CONSTRAINT"));

The other ones which you're mimicking are IMO in poor style.

--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/
Officer Krupke, what are we to do?
Gee, officer Krupke, Krup you! (West Side Story, "Gee, Officer Krupke")

#8Ante Krešić
ante@tigerdata.com
In reply to: Alvaro Herrera (#7)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

Hi all,

I've rebased and updated my patch based on Álvaro Herrera's wording
suggestion.

I have left the function refactoring for future work as suggested.

Thanks,

On Mon, Jun 15, 2026 at 8:44 PM Álvaro Herrera <alvherre@kurilemu.de> wrote:

Show quoted text

On 2026-May-14, Ante Krešić wrote:

+                     if (!conForm->convalidated)
+                             ereport(ERROR,
+

errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),

+ errmsg("index \"%s\"

cannot be used as replica identity because column \"%s\" has an invalid
not-null constraint",

+

RelationGetRelationName(indexRel),

+

NameStr(attr->attname)),

+ /*- translator: second %s is a constraint

characteristic such as NOT VALID */

+ errdetail("The constraint

\"%s\" is marked %s.",

+

NameStr(conForm->conname), "NOT VALID"),

+ errhint("You might need to

validate it using %s.",

+ "ALTER

TABLE ... VALIDATE CONSTRAINT"));

I'd rather make this error be

+           ereport(ERROR,
+                   errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                   errmsg("cannot use index \"%s\" as replica identity",
+                          RelationGetRelationName(indexRel),
+                          NameStr(attr->attname)),
+                   /*- translator: third %s is a constraint
characteristic such as NOT VALID */
+                   errdetail("The constraint \"%s\" on column \"%s\" is
marked %s.",
+                             NameStr(conForm->conname),
NameStr(attr->attname), "NOT VALID"),
+                   errhint("You might need to validate it using %s.",
+                           "ALTER TABLE ... VALIDATE CONSTRAINT"));

The other ones which you're mimicking are IMO in poor style.

--
Álvaro Herrera Breisgau, Deutschland —
https://www.EnterpriseDB.com/
Officer Krupke, what are we to do?
Gee, officer Krupke, Krup you! (West Side Story, "Gee, Officer Krupke")

Attachments:

t139639_8
v2-0001-Reject-REPLICA-IDENTITY-USING-INDEX-on-column-wit.patchtext/x-patch; charset=US-ASCII; name=v2-0001-Reject-REPLICA-IDENTITY-USING-INDEX-on-column-wit.patchDownload+67-1
#9solai v
solai.cdac@gmail.com
In reply to: Ante Krešić (#8)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

Hi,

I tested the patch on my current branch.
Before applying the patch i was able to reproduce the reported issue.
I created a table containing a NULL value, added a NOT NULL NOT VALID
constraint on the column, and created a unique index. PostgreSQL
accepted ALTER TABLE REPLICA IDENTITY USING INDEX even though the
underlying NOT NULL constraint had not been validated and the column
still contained NULL values. The command succeeded and relreplident
was set to i, confirming the behavior described in the report.

After applying the patch i repeated the same test.
PostgreSQL correctly rejected the operation with
ERROR: cannot use index "t_idx" as replica identity
DETAIL: The constraint "id_nn" on column "id" is marked NOT VALID.
HINT: You might need to validate it using ALTER TABLE ... VALIDATE CONSTRAINT.

This matches the expected behavior, since a column with an unvalidated
NOT NULL constraint cannot guarantee that all rows are non-null and
therefore should not be eligible for use as a replica identity.
I also ran the regression tests, and all tests passed successfully.

Regards,
Solai

#10Alvaro Herrera
alvherre@kurilemu.de
In reply to: solai v (#9)
Re: [PATCH] REPLICA IDENTITY USING INDEX accepts column with invalid NOT NULL

On 2026-Jun-18, solai v wrote:

After applying the patch i repeated the same test.
PostgreSQL correctly rejected the operation with
ERROR: cannot use index "t_idx" as replica identity
DETAIL: The constraint "id_nn" on column "id" is marked NOT VALID.
HINT: You might need to validate it using ALTER TABLE ... VALIDATE CONSTRAINT.

This matches the expected behavior,

I agree. I have pushed it now to all three branches.

The only problem left (famous last words!) on this at this point is that
somebody could have an instance in 18 where the replica identity has
already been set to an index with an invalid not-null, and they might
only find out when they try to pg_upgrade to 19 or 20 and it fails in
the middle of the upgrade. Would you be interested in patching
pg_upgrade so that it detects this problem during --check and reports it
there?

Thanks

--
Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/
"Ellos andaban todos desnudos como su madre los parió, y también las mujeres,
aunque no vi más que una, harto moza, y todos los que yo vi eran todos
mancebos, que ninguno vi de edad de más de XXX años" (Cristóbal Colón)