Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

Поиск
Список
Период
Сортировка
Искать

Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi Bernhard,

Good report.  I reproduced it and measured a few things around it.

The slowdown reproduces on 18.6.  With your script, ms per ATTACH goes
from 0.07 (empty) to 20.7 at 1M pg_constraint rows, the nullable control
stays flat, and pg_stat_sys_tables shows exactly one pg_constraint
seqscan per ATTACH.  My absolute numbers are lower than yours (faster
machine) but the shape is the same.

I also ran your script on 17.11, which you hadn't.  It stays flat, 0.06
to 0.26 ms per ATTACH, and pg_constraint stays at ~110 rows the whole
way.  The seqscan happens on 17 too, but with almost nothing in
pg_constraint it costs nothing.  So this is 14e87ffa5 feeding a scan
that was always there, as you say.

On your option (c), one thing makes it cheaper than it looks: only
foreign-key rows have confrelid <> 0.  I checked every contype, and
not-null, check, primary-key and unique constraints all store
confrelid = 0, so a partial index

    CREATE INDEX ... ON pg_constraint (confrelid) WHERE confrelid <> 0;

covers only the FK rows, not the not-null rows that dominate the
catalog.  On a database with 1,000,198 constraints of which 1 is an FK,
that index is 16 kB, and the lookup CloneFkReferenced() does drops from
a 58 ms seqscan (1M rows filtered) to a 0.03 ms index scan.  The partial
predicate also answers the maintenance worry you raised for (c): the
not-null inserts that make up the bulk match confrelid = 0, so they
never touch the index.

One correction on the DETACH path: I could not reproduce a slowdown
there.  Detaching 50 partitions with 1M pg_constraint rows stays at
0.06 ms each and adds zero pg_constraint seqscans, so
GetParentedForeignKeyRefs() does not seem to be reached on a plain
DETACH with no foreign key involved.  ATTACH is where the cost is.

I'd be glad to put a patch together once there's a sense of the
preferred direction.  The partial index is the smallest change, but
whether a new catalog index is the way to go, versus the pg_depend
lookup or the trigger-based early exit, is more your and the
committers' call.  Happy to test any of them against the reproducer.

Regards,
Manu


Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-29, Manu wrote:

> I'd be glad to put a patch together once there's a sense of the
> preferred direction.  The partial index is the smallest change, but
> whether a new catalog index is the way to go, versus the pg_depend
> lookup or the trigger-based early exit, is more your and the
> committers' call.  Happy to test any of them against the reproducer.

I vaguely recall looking into adding such an index, and finding out that
we don't support partial indexes on catalogs.  Is that doable in some
clean way nowadays?  (Or maybe the index worked fine, and what failed
was adding a syscache on top of it?  Not sure.)

I first mentioned this in 2019 ...
https://postgr.es/m/20190318220223.GA15196@alvherre.pgsql

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
"Drawing in linguistics, Makefiles are more like proto languages, where you might
identify a few fragments but otherwise never be sure if the speaker asked for
a proto sandwich or all your money."  (grmnsftphr, https://lwn.net/Articles/1093871/)


Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
> I vaguely recall looking into adding such an index, and finding out
> that we don't support partial indexes on catalogs.  Is that doable in
> some clean way nowadays?  (Or maybe the index worked fine, and what
> failed was adding a syscache on top of it?  Not sure.)

Thanks for the pointer -- it sent me to check, and your recollection
holds up. It's the same "no usable index" seqscan from back then; it
only stayed cheap while pg_constraint was small, and not-null
constraints moving into it for 18 is what surfaced it.

On whether a partial index is doable cleanly: still not, and there are
two separate walls, not one.

Declaration: the bootstrap grammar has no place for a predicate.
Boot_DeclareIndexStmt in src/backend/bootstrap/bootparse.y is just
"DECLARE INDEX name oid ON table USING am ( params )", no WHERE. genbki
does pass the predicate string through into postgres.bki, so the build
succeeds, but initdb then fails with a syntax error at that line.

Maintenance: even past that, the catalog insert path assumes
non-partial. CatalogIndexInsert() in src/backend/catalog/indexing.c:

  /*
   * Expressional and partial indexes on system catalogs are not
   * supported, nor exclusion constraints, nor deferred uniqueness
   */
  Assert(indexInfo->ii_Predicate == NIL);

It never evaluates a predicate. Forcing a partial index in with
allow_system_table_mods confirms it: after ~1M not-null rows the
"WHERE confrelid <> 0" index holds all of them rather than the one FK
row, silently on a non-assert build. So a clean partial catalog index
would mean teaching both the bootstrap grammar and CatalogIndexInsert to
carry and evaluate a predicate.

The syscache isn't the blocker here. CloneFkReferenced() scans with
systable_beginscan(pg_constraint, InvalidOid, true, ...), not a syscache
lookup, so a plain (non-unique) index on confrelid is picked up just by
passing its OID in place of InvalidOid; no syscache involved.

So I went with a full index on pg_constraint(confrelid), which is
declarable today, and pointed the scan at it (one scankey on confrelid,
contype filtered in the loop). That's the attached v1. With the catalog
grown to ~1M not-null rows, ms per ATTACH goes from about 25 ms (growing
linearly) to 0.27 ms and stays flat as the catalog grows; make check is
clean. The cost is that a full index also covers every not-null/pk/check
row, so it is ~6 MB rather than the ~16 kB a confrelid<>0 partial would
be, and adds ~5% to bulk DDL on pg_constraint. That size gap is exactly
what makes the partial version attractive, and exactly what can't be
declared.

Glad to drop it for the trigger-based early-exit instead if you'd rather
not add a catalog index; that route also has the advantage of being
backpatchable, which a catalog change is not.

-- 
Manu

Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-29, Manu wrote:

> So I went with a full index on pg_constraint(confrelid), which is
> declarable today, and pointed the scan at it (one scankey on confrelid,
> contype filtered in the loop). That's the attached v1. With the catalog
> grown to ~1M not-null rows, ms per ATTACH goes from about 25 ms (growing
> linearly) to 0.27 ms and stays flat as the catalog grows; make check is
> clean. The cost is that a full index also covers every not-null/pk/check
> row, so it is ~6 MB rather than the ~16 kB a confrelid<>0 partial would
> be, and adds ~5% to bulk DDL on pg_constraint. That size gap is exactly
> what makes the partial version attractive, and exactly what can't be
> declared.

If I recall correctly, there are other pg_constraint scans that could
benefit from this index -- GetParentedForeignKeyRefs() at least; maybe
others?  I couldn't find anything in a quick grep.

I mentioned the syscache because I think I wanted to add a syscache on
top of such index for some reason.  It might well be that I'm
remembering a syscache that I wanted to add on some other column, maybe
even on a different catalog altogether :-)

> Glad to drop it for the trigger-based early-exit instead if you'd rather
> not add a catalog index; that route also has the advantage of being
> backpatchable, which a catalog change is not.

Hmm, I'm not eager to backpatch anything here, I'd rather go with a
master-only solution.

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
"Ninguna manada de bestias tiene una voz tan horrible como la humana" (Orual)


Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
> If I recall correctly, there are other pg_constraint scans that could
> benefit from this index -- GetParentedForeignKeyRefs() at least; maybe
> others?  I couldn't find anything in a quick grep.

Right.  v2 attached points three confrelid scans at the index:

  - CloneFkReferenced() on ATTACH PARTITION / PARTITION OF
  - GetParentedForeignKeyRefs() on DETACH PARTITION
  - ATPrepChangePersistence() on ALTER TABLE ... SET UNLOGGED

The third is the "maybe others": grepping Anum_pg_constraint_confrelid
turns up its else branch, which scans confrelid on SET UNLOGGED and
whose own comment already noted it had no usable index -- it does now.
The other two share CloneFkReferenced's shape, so they scan on confrelid
alone and filter contype in the loop.

On a catalog bloated to ~250k rows, each of the three drops from a
pg_constraint seqscan to an index scan (seq_scan delta 1-2 -> 0), and
ATTACH stays at the ~25 ms -> 0.3 ms per partition from before.  make
check is clean.

> I mentioned the syscache because I think I wanted to add a syscache on
> top of such index for some reason.

No need for these three -- they all go through systable_beginscan, so a
plain index is enough; I left the syscache out.

> Hmm, I'm not eager to backpatch anything here, I'd rather go with a
> master-only solution.

Works for me -- a catalog change is master-only anyway.

-- 
Manu

Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-29, Manu wrote:

> The third is the "maybe others": grepping Anum_pg_constraint_confrelid
> turns up its else branch, which scans confrelid on SET UNLOGGED and
> whose own comment already noted it had no usable index -- it does now.
> The other two share CloneFkReferenced's shape, so they scan on confrelid
> alone and filter contype in the loop.

Makes sense.  Please create a commitfest entry for this, if there isn't
one already.

I think we should explore the idea of adding support for partial indexes
on catalogs, though.  Having an index 90% populated by useless entries
doesn't sound like the best use of resources.  Perhaps we could also use
such functionality on ConstraintRelidTypidNameIndexId, splitting that
into two indexes, one for constraints on types and another for indexes
on relations, and avoid having to store InvalidOid on the other column.

This doesn't have to delay this patch, however.

-- 
Álvaro Herrera               48°01'N 7°57'E  —  https://www.EnterpriseDB.com/
"La rebeldía es la virtud original del hombre" (Arthur Schopenhauer)


Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
On 2026-Sep-29, Álvaro Herrera wrote:

> Makes sense.  Please create a commitfest entry for this, if there
> isn't one already.

Done -- it's CF 7365 in PG20-3.

> I think we should explore the idea of adding support for partial
> indexes on catalogs, though.  Having an index 90% populated by
> useless entries doesn't sound like the best use of resources.
> Perhaps we could also use such functionality on
> ConstraintRelidTypidNameIndexId, splitting that into two indexes,
> one for constraints on types and another for indexes on relations,
> and avoid having to store InvalidOid on the other column.
> This doesn't have to delay this patch, however.

I'd like to take that up.  I spent some time mapping what stands in
the way today, and it comes down to two places:

  - The bootstrap index grammar (Boot_DeclareIndexStmt in
    bootparse.y) has no WHERE production, so a predicate declared in
    the catalog headers reaches genbki but initdb cannot parse it.

  - CatalogIndexInsert() asserts ii_Predicate == NIL and never
    evaluates a predicate, so even a built index would be maintained
    for every row.

The engine side (index_create) already carries ii_Predicate, so the
work looks contained to those two spots rather than the access method
layer.

If that reading matches yours, I can start a separate thread with a
first sketch, using confrelid and the ConstraintRelidTypidNameIndexId
split you mention as the two motivating cases.  Happy to hear if
you'd shape it differently.

Manu


Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-30, Manu wrote:

> I spent some time mapping what stands in
> the way today, and it comes down to two places:
> 
>   - The bootstrap index grammar (Boot_DeclareIndexStmt in
>     bootparse.y) has no WHERE production, so a predicate declared in
>     the catalog headers reaches genbki but initdb cannot parse it.
> 
>   - CatalogIndexInsert() asserts ii_Predicate == NIL and never
>     evaluates a predicate, so even a built index would be maintained
>     for every row.
> 
> The engine side (index_create) already carries ii_Predicate, so the
> work looks contained to those two spots rather than the access method
> layer.
> 
> If that reading matches yours, I can start a separate thread with a
> first sketch, using confrelid and the ConstraintRelidTypidNameIndexId
> split you mention as the two motivating cases.  Happy to hear if
> you'd shape it differently.

I think the difficult question here is how are we going to evaluate the
condition on the tuple.  We absolutely can't run the full executor, so
there needs to be some way to limit what we're willing to do, and
finding a way to do it without calling anything other than a very
limited set of functions -- something like "is OID different than
0" has got to be enough.  I have no idea how to make that work and still
have a representation of the restriction in the system catalogs for the
catalog rows themselves.

But yeah, let's discuss in a new thread if you can figure out an answer
to that.

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


Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi,

v3 attached, rebased on current master for CF 7365.  The only change
from v2 is that it no longer bumps catversion, which was the conflict;
that's left to the committer.  make check passes.

Regards,
Manu

Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi,

A status note for CF 7365, since the patch ended up split across two
threads.

The current version is v4, posted in the "Partial indexes on system
catalogs" thread [1], after Tom pointed out [2] that a plain non-unique
index on confrelid, like the one on contypid, is all this needs.  That
is what v4 does.  It also covers a lookup that v3 missed,
heap_truncate_find_FKs(), which runs on TRUNCATE and at every commit
that touches an ON COMMIT DELETE ROWS table with a foreign key or
trigger.

v4 still applies cleanly to master, make check passes, CFbot is green,
and amcheck is clean on the new index after DDL churn.  On today's
master with about a million constraints, the affected operations drop
from tens of milliseconds to under two: ATTACH PARTITION, DETACH
PARTITION, CREATE TABLE ... PARTITION OF, TRUNCATE of a table with a
trigger, and ALTER TABLE ... SET UNLOGGED are all around 50-90 ms on
master and under 2 ms with the index, roughly an 80x drop.  A commit
loop over an ON COMMIT DELETE ROWS table that has a foreign key goes
from about 3.5 s to a few ms.  Creating not-null or foreign-key
constraints costs the same as before, and the index is about 6 MB next
to a 340 MB catalog.

The existing regression tests already run all four call sites
(foreign_key, truncate, temp, alter_table), so I don't think it needs
new tests; it needs a reviewer.  Álvaro, since this got slow when
not-null constraints moved into pg_constraint, would you have time to
look at it?

[1] https://postgr.es/m/179115578677.1450953.3979833043111954204@gmail.com
[2] https://postgr.es/m/1298334.1790896057@sss.pgh.pa.us

Regards,
Manu


Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Oct-15, Manu wrote:

> The existing regression tests already run all four call sites
> (foreign_key, truncate, temp, alter_table), so I don't think it needs
> new tests; it needs a reviewer.  Álvaro, since this got slow when
> not-null constraints moved into pg_constraint, would you have time to
> look at it?

Sure.  But this is pg20 development work, and I'm still on the hook for
the yet-to-be-released pg19 and I also want to get older bugs repaired.
So I'm afraid this will have to wait.

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"No hay ausente sin culpa ni presente sin disculpa" (Prov. francés)


Re: ATTACH PARTITION cost grows linearly with pg_constraint size (seqscan in CloneFkReferenced), much worse since not-null constraints are in pg_constraint (PG 18)

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
Hello,

On 2026-Oct-02, Manu wrote:

> v3 attached, rebased on current master for CF 7365.  The only change
> from v2 is that it no longer bumps catversion, which was the conflict;
> that's left to the committer.  make check passes.

For closure: per [1], this has been committed.  I'm afraid we don't have
a solution for users of Postgres 18 and 19.

[1] https://postgr.es/m/avXKHF359xUI1AVE@alvherre.pgsql

Lastly, Manu: when you omit a necessary catversion bump (which IMO is
good to prevent pointless conflicts), I suggest to include an XXX note
in the commit message.  Otherwise somebody might forget to do it.  I
know it could happen to me, at least.

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


FAQ