addFkRecurseReferencing use unassigned fkconstraint->fk_with_period value

Started by jian he4 months ago7 messageshackers

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1jian he
jian.universality@gmail.com

Hi.

While trying to make ALTER COLUMN SET EXPRESSION just validate the
existing constraint instead of dropping and recreating constraints,
(https://commitfest.postgresql.org/patch/7117).
I find the following code suspicious.

In CloneFkReferencing we have:
{
/* No dice. Set up to create our own constraint */
fkconstraint = makeNode(Constraint);
fkconstraint->contype = CONSTRAINT_FOREIGN;
/* ->conname determined below */
fkconstraint->deferrable = constrForm->condeferrable;
fkconstraint->initdeferred = constrForm->condeferred;
fkconstraint->location = -1;
fkconstraint->pktable = NULL;
/* ->fk_attrs determined below */
fkconstraint->pk_attrs = NIL;
fkconstraint->fk_matchtype = constrForm->confmatchtype;
fkconstraint->fk_upd_action = constrForm->confupdtype;
fkconstraint->fk_del_action = constrForm->confdeltype;
fkconstraint->fk_del_set_cols = NIL;
fkconstraint->old_conpfeqop = NIL;
fkconstraint->old_pktable_oid = InvalidOid;
fkconstraint->is_enforced = constrForm->conenforced;
fkconstraint->skip_validation = false;
fkconstraint->initially_valid = constrForm->convalidated;
for (int i = 0; i < numfks; i++)
{
Form_pg_attribute att;

att = TupleDescAttr(RelationGetDescr(partRel),
mapped_conkey[i] - 1);
fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
makeString(NameStr(att->attname)));
}

indexOid = constrForm->conindid;
with_period = constrForm->conperiod;

/* Create the pg_constraint entry at this level */
address = addFkConstraint(addFkReferencingSide,
NameStr(constrForm->conname), fkconstraint,
partRel, pkrel, indexOid, parentConstrOid,
numfks, confkey,
mapped_conkey, conpfeqop,
conppeqop, conffeqop,
numfkdelsetcols, confdelsetcols,
false, with_period);
}

And in
addFkRecurseReferencing
{
tab = ATGetQueueEntry(wqueue, rel);
newcon = palloc0_object(NewConstraint);
....
newcon->conwithperiod = fkconstraint->fk_with_period;
newcon->qual = (Node *) fkconstraint;
tab->constraints = lappend(tab->constraints, newcon);
}
------------------------------------
The preceding code shows that in CloneFkReferencing
{
addFkConstraint
....
addFkRecurseReferencing
}

We not set fkconstraint->fk_with_period value and just use it in
addFkRecurseReferencing,
and validateForeignKeyConstraint require NewConstraint->conwithperiod
to set properly.
So I asked Claude to confirm this; the Claude response is attached.

Looking at src/test/regress/sql/without_overlaps.sql, there is no such
test case:
ATTACH PARTITION where the partition has data.

The minimum reproducible example:
drop table if exists tp, tfk, tfk2;
CREATE TABLE tp (
id int4range,
valid_at daterange,
CONSTRAINT tp_pk PRIMARY KEY (id, valid_at WITHOUT OVERLAPS)
);
INSERT INTO tp VALUES ('[1,2)', daterange('2000-01-01', '2000-02-01'));
CREATE TABLE tfk (
id int4range,
parent_id int4range,
valid_at daterange,
CONSTRAINT tfk_fk FOREIGN KEY (parent_id, PERIOD valid_at)
REFERENCES tp (id, PERIOD valid_at)
) PARTITION BY LIST (id);

CREATE TABLE tfk2 (LIKE tfk including all);
INSERT INTO tfk2(id, parent_id, valid_at) VALUES ('[2,3)', '[1,2)',
daterange('2000-01-01', '2010-01-01'));
ALTER TABLE tfk ATTACH PARTITION tfk2 FOR VALUES IN ('[2,3)'); --
expect error, but no error now.
INSERT INTO tfk2(id, parent_id, valid_at) VALUES ('[2,3)', '[1,2)',
daterange('2000-01-01', '2010-01-01')); -- error as expected.

--
jian
https://www.enterprisedb.com/

Attachments:

scratch28.txttext/plain; charset=UTF-8; name=scratch28.txtDownload
#2Haibo Yan
tristan.yim@gmail.com
In reply to: jian he (#1)
Re: addFkRecurseReferencing use unassigned fkconstraint->fk_with_period value

On Mon, Aug 10, 2026 at 3:09 AM jian he <jian.universality@gmail.com> wrote:

Hi.

While trying to make ALTER COLUMN SET EXPRESSION just validate the
existing constraint instead of dropping and recreating constraints,
(https://commitfest.postgresql.org/patch/7117).
I find the following code suspicious.

In CloneFkReferencing we have:
{
/* No dice. Set up to create our own constraint */
fkconstraint = makeNode(Constraint);
fkconstraint->contype = CONSTRAINT_FOREIGN;
/* ->conname determined below */
fkconstraint->deferrable = constrForm->condeferrable;
fkconstraint->initdeferred = constrForm->condeferred;
fkconstraint->location = -1;
fkconstraint->pktable = NULL;
/* ->fk_attrs determined below */
fkconstraint->pk_attrs = NIL;
fkconstraint->fk_matchtype = constrForm->confmatchtype;
fkconstraint->fk_upd_action = constrForm->confupdtype;
fkconstraint->fk_del_action = constrForm->confdeltype;
fkconstraint->fk_del_set_cols = NIL;
fkconstraint->old_conpfeqop = NIL;
fkconstraint->old_pktable_oid = InvalidOid;
fkconstraint->is_enforced = constrForm->conenforced;
fkconstraint->skip_validation = false;
fkconstraint->initially_valid = constrForm->convalidated;
for (int i = 0; i < numfks; i++)
{
Form_pg_attribute att;

att = TupleDescAttr(RelationGetDescr(partRel),
mapped_conkey[i] - 1);
fkconstraint->fk_attrs = lappend(fkconstraint->fk_attrs,
makeString(NameStr(att->attname)));
}

indexOid = constrForm->conindid;
with_period = constrForm->conperiod;

/* Create the pg_constraint entry at this level */
address = addFkConstraint(addFkReferencingSide,
NameStr(constrForm->conname), fkconstraint,
partRel, pkrel, indexOid, parentConstrOid,
numfks, confkey,
mapped_conkey, conpfeqop,
conppeqop, conffeqop,
numfkdelsetcols, confdelsetcols,
false, with_period);
}

And in
addFkRecurseReferencing
{
tab = ATGetQueueEntry(wqueue, rel);
newcon = palloc0_object(NewConstraint);
....
newcon->conwithperiod = fkconstraint->fk_with_period;
newcon->qual = (Node *) fkconstraint;
tab->constraints = lappend(tab->constraints, newcon);
}
------------------------------------
The preceding code shows that in CloneFkReferencing
{
addFkConstraint
....
addFkRecurseReferencing
}

We not set fkconstraint->fk_with_period value and just use it in
addFkRecurseReferencing,
and validateForeignKeyConstraint require NewConstraint->conwithperiod
to set properly.
So I asked Claude to confirm this; the Claude response is attached.

Looking at src/test/regress/sql/without_overlaps.sql, there is no such
test case:
ATTACH PARTITION where the partition has data.

The minimum reproducible example:
drop table if exists tp, tfk, tfk2;
CREATE TABLE tp (
id int4range,
valid_at daterange,
CONSTRAINT tp_pk PRIMARY KEY (id, valid_at WITHOUT OVERLAPS)
);
INSERT INTO tp VALUES ('[1,2)', daterange('2000-01-01', '2000-02-01'));
CREATE TABLE tfk (
id int4range,
parent_id int4range,
valid_at daterange,
CONSTRAINT tfk_fk FOREIGN KEY (parent_id, PERIOD valid_at)
REFERENCES tp (id, PERIOD valid_at)
) PARTITION BY LIST (id);

CREATE TABLE tfk2 (LIKE tfk including all);
INSERT INTO tfk2(id, parent_id, valid_at) VALUES ('[2,3)', '[1,2)',
daterange('2000-01-01', '2010-01-01'));
ALTER TABLE tfk ATTACH PARTITION tfk2 FOR VALUES IN ('[2,3)'); --
expect error, but no error now.
INSERT INTO tfk2(id, parent_id, valid_at) VALUES ('[2,3)', '[1,2)',
daterange('2000-01-01', '2010-01-01')); -- error as expected.

--
jian
https://www.enterprisedb.com/

Hi Jian,

Thanks for the report and the reproducer. I can confirm the issue on master.

The problem is that CloneFkReferencing() reconstructs a Constraint node from
the catalog but doesn’t set fk_with_period, so addFkRecurseReferencing()
initializes NewConstraint.conwithperiod as false even when the constraint is
actually a PERIOD FK. That leads phase 3 validation to incorrectly take the
RI_Initial_Check() fast path, which is insufficient for PERIOD semantics: it
only checks for some overlapping referenced row, rather than requiring the
referencing period to be covered by the aggregate of matching referenced
periods.

The fix is to set conwithperiod from the correct source:

* In addFkRecurseReferencing(), use the with_period argument directly.
* In QueueFKConstraintValidation() and ATExecAlterFKConstrEnforceability(),
read it from pg_constraint.conperiod.

I’ve also added regression tests covering ATTACH PARTITION, VALIDATE
CONSTRAINT, and ALTER CONSTRAINT … ENFORCED, including cases with pre-existing
violating rows.

Passes make check-world with assertions enabled.

Best,
Haibo

Attachments:

t253366_2
v1-0001-Fix-loss-of-PERIOD-semantics-when-validating-temp.patchapplication/octet-stream; name=v1-0001-Fix-loss-of-PERIOD-semantics-when-validating-temp.patchDownload+228-2
#3Andrew Krylosov
krylosov.andrew@gmail.com
In reply to: Haibo Yan (#2)
Re: addFkRecurseReferencing use unassigned fkconstraint->fk_with_period value

Hi,

Haibo Yan wrote:

The fix is to set conwithperiod from the correct source:

I tested v1 on 3c5d9d914f with assertions enabled on macos.
without_overlaps and the full regress and isolation suites pass.
With only the tablecmds.c changes reverted, the new tests fail at all
four expected rejection cases: VALIDATE, ENFORCED, and both ATTACH
paths.

The changes look right to me. In addFkRecurseReferencing(), with_period
is correct for both the parser path and the partially reconstructed
Constraint from CloneFkReferencing(). The other two assignments take it
from the catalog row being validated. I found no other producer of a
foreign-key NewConstraint.

I tried multiranges with gaps in coverage, partitioned tables on both
sides of the FK, recursive validation and enforcement, attaching a
partitioned table with a different column order, and reusing a NOT VALID
FK during ADD FOREIGN KEY. The affected operations accept uncovered
rows on the base revision and reject them with v1; the corresponding
covered rows pass with v1.

One point for the commit message: constraints that went through one of
these paths on 18.x may already be marked valid with uncovered rows.
The fix does not recheck them, and VALIDATE CONSTRAINT is a no-op for
a valid constraint. Such rows can be found with a query modeled on the
RI check; alternatively, with the fix, the constraint can be dropped and
re-added as NOT VALID in one transaction and then validated separately,
which keeps it enforced for new rows if validation fails.

For a separate cleanup, RI_Initial_Check() could return false when
riinfo->hasperiod is true. It already fetches that information, so
this could avoid making callers maintain another copy of the flag.
I think the minimal fix in v1 is suitable for backpatching as it stands.

Two small test nits: "with pre-existing rows" would read better than
"with rows already", and the NOT VALID/NOT ENFORCED block would fit
better after the pg_get_constraintdef checks, keeping those checks
next to the constraint they inspect.

I think this is ready for a committer.

Best regards,
Andrew Krylosov

#4Haibo Yan
tristan.yim@gmail.com
In reply to: Andrew Krylosov (#3)
Re: addFkRecurseReferencing use unassigned fkconstraint->fk_with_period value

On Mon, Sep 28, 2026 at 9:17 AM Andrew Krylosov
<krylosov.andrew@gmail.com> wrote:

Hi,

Haibo Yan wrote:

The fix is to set conwithperiod from the correct source:

I tested v1 on 3c5d9d914f with assertions enabled on macos.
without_overlaps and the full regress and isolation suites pass.
With only the tablecmds.c changes reverted, the new tests fail at all
four expected rejection cases: VALIDATE, ENFORCED, and both ATTACH
paths.

The changes look right to me. In addFkRecurseReferencing(), with_period
is correct for both the parser path and the partially reconstructed
Constraint from CloneFkReferencing(). The other two assignments take it
from the catalog row being validated. I found no other producer of a
foreign-key NewConstraint.

I tried multiranges with gaps in coverage, partitioned tables on both
sides of the FK, recursive validation and enforcement, attaching a
partitioned table with a different column order, and reusing a NOT VALID
FK during ADD FOREIGN KEY. The affected operations accept uncovered
rows on the base revision and reject them with v1; the corresponding
covered rows pass with v1.

One point for the commit message: constraints that went through one of
these paths on 18.x may already be marked valid with uncovered rows.
The fix does not recheck them, and VALIDATE CONSTRAINT is a no-op for
a valid constraint. Such rows can be found with a query modeled on the
RI check; alternatively, with the fix, the constraint can be dropped and
re-added as NOT VALID in one transaction and then validated separately,
which keeps it enforced for new rows if validation fails.

For a separate cleanup, RI_Initial_Check() could return false when
riinfo->hasperiod is true. It already fetches that information, so
this could avoid making callers maintain another copy of the flag.
I think the minimal fix in v1 is suitable for backpatching as it stands.

Two small test nits: "with pre-existing rows" would read better than
"with rows already", and the NOT VALID/NOT ENFORCED block would fit
better after the pg_get_constraintdef checks, keeping those checks
next to the constraint they inspect.

I think this is ready for a committer.

Best regards,
Andrew Krylosov

Hi Andrew,

Thanks for the review and additional testing.

I addressed both test comments in v2: changed the wording to "with pre-existing
rows" and moved the NOT VALID / NOT ENFORCED tests after the
pg_get_constraintdef checks.

There are no code changes from v1.

Thanks,
Haibo

Attachments:

t253366_4
v2-0001-Fix-loss-of-PERIOD-semantics-when-validating-temp.patchapplication/octet-stream; name=v2-0001-Fix-loss-of-PERIOD-semantics-when-validating-temp.patchDownload+228-2
#5Paul A Jungwirth
pj@illuminatedcomputing.com
In reply to: Haibo Yan (#4)
Re: addFkRecurseReferencing use unassigned fkconstraint->fk_with_period value

On Mon, Sep 28, 2026 at 11:18 PM Haibo Yan <tristan.yim@gmail.com> wrote:

changed the wording to "with pre-existing

rows" and moved the NOT VALID / NOT ENFORCED tests after the
pg_get_constraintdef checks.

There are no code changes from v1.

This looks good to me too. Andres reported the VALIDATE CONSTRAINT
case in [0]/messages/by-id/sesqxzfcujkcnrwpir5xvhy7iamhsbjiqt6r2xqmb7hqkulte6@bbuc42qzanzs, but it's nice to have fixes to all three cases in one
place.

If you want, here is a v3 with a less verbose commit message. Also I
added the note suggested by Andrew, which seems worth including in
release notes.

[0]: /messages/by-id/sesqxzfcujkcnrwpir5xvhy7iamhsbjiqt6r2xqmb7hqkulte6@bbuc42qzanzs

Yours,

--
Paul ~{:-)
pj@illuminatedcomputing.com

Attachments:

t253366_5
v3-0001-Fix-loss-of-PERIOD-semantics-when-validating-temp.patchapplication/octet-stream; name=v3-0001-Fix-loss-of-PERIOD-semantics-when-validating-temp.patchDownload+228-2
#6Haibo Yan
tristan.yim@gmail.com
In reply to: Paul A Jungwirth (#5)
Re: addFkRecurseReferencing use unassigned fkconstraint->fk_with_period value

On Thu, Oct 8, 2026 at 10:22 PM Paul A Jungwirth
<pj@illuminatedcomputing.com> wrote:

On Mon, Sep 28, 2026 at 11:18 PM Haibo Yan <tristan.yim@gmail.com> wrote:

changed the wording to "with pre-existing

rows" and moved the NOT VALID / NOT ENFORCED tests after the
pg_get_constraintdef checks.

There are no code changes from v1.

This looks good to me too. Andres reported the VALIDATE CONSTRAINT
case in [0], but it's nice to have fixes to all three cases in one
place.

If you want, here is a v3 with a less verbose commit message. Also I
added the note suggested by Andrew, which seems worth including in
release notes.

[0] /messages/by-id/sesqxzfcujkcnrwpir5xvhy7iamhsbjiqt6r2xqmb7hqkulte6@bbuc42qzanzs

Yours,

--
Paul ~{:-)
pj@illuminatedcomputing.com

Hi Paul,

Thanks for picking this up and preparing v3.

The changes look good to me. One minor wording nit in the commit
message: "despite covering violating rows" might be clearer as
"despite containing violating rows".

Otherwise, v3 looks good to me.

Thanks,
Haibo

#7solai v
solai.cdac@gmail.com
In reply to: Paul A Jungwirth (#5)
Re: addFkRecurseReferencing use unassigned fkconstraint->fk_with_period value

Hi,

I tested the v3 patch for the PERIOD foreign-key validation issue.
Before applying the patch, I reproduced the bug: attaching a partition
containing an invalid existing row succeeded unexpectedly, while
inserting the same invalid row afterward failed with a foreign-key
violation.
After applying the patch and rebuilding PostgreSQL, the same partition
attachment was correctly rejected with a foreign-key violation.
I also ran 'make check' and all regression tests passed. The added
regression tests cover 'VALIDATE CONSTRAINT', 'ALTER CONSTRAINT ...
ENFORCED', and 'ATTACH PARTITION', including cases where existing rows
are invalid or their periods are covered after correction.
Based on my testing, the patch fixes the reproduced
partition-attachment issue, and I did not observe regression-test
failures.

Regards,
solai