Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

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

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
Hi Matthias,

Thanks for the review.

> [0001-0003]
> I Haven't looked at these in detail. Yes, they provide the largest
> savings, but that also makes them most complicated to review in
> detail.  I'll stave that off for now.

While the diff is relatively big, the changes are quite mechanical. The
biggest challenge is knowing that all code has been adapted. Apart from
grepping, I relied on the tests for that.

>> - 0004: Removes the rd_lockinfo member. RelationGetLockRelId() now
>> computes it when needed. This also removes RelationInitLockInfo() and
>> the initialization work associated with it.
>> => sizeof(RelationData) == 304 bytes
> 
> Can we really rely on rd_rel always being valid when we need the
> LockInfo? I'm OK with avoiding duplicating
> rd_id/rd_lockinfo.lockRelId.relId, but I'm not sure dbId can always be
> derived with rd_rel->relisshared whenever we need it.

The information is derived exactly the same way, just deferred to when
it's needed. The old RelationInitLockInfo() did:

if (relation->rd_rel->relisshared)
    relation->rd_lockInfo.lockRelId.dbId = InvalidOid;
else
    relation->rd_lockInfo.lockRelId.dbId = MyDatabaseId;

Beyond that, every Relation that can reach RelationGetLockRelId() has
rd_rel populated. There's no code that constructs a Relation with rd_rel
== NULL and then locks it.

There's also one subtle improvement: the deferring version is more
correct than before in the load_relcache_init_file() case. The old code
had to recompute lockRelId after loading pg_internal.init because the
file might have been copied from another database by CREATE DATABASE —
baking in the wrong dbId. Computing MyDatabaseId on the fly makes that
recomputation unnecessary.

>> - 0005: Replaces the embedded partition key, descriptors, partition
>> qual, validity flag, and memory contexts with one lazily allocated
>> RelationPartitionInfo pointer.
>> => sizeof(RelationData) == 264 bytes
> 
> I haven't worked on partitioning, so I'm not fully confident that this
> has sufficiently low additional overhead to be worth applying.

I'll run a partitioned pgbench and report if I could measure any
regressions.

>> - 0006: Removes rd_fkeyvalid by using RELCACHE_FKEYLIST_NOT_LOADED as
>> the initial state of rd_fkeylist. NIL continues to mean that the list
>> was computed and no foreign keys were found. This patch is not strictly
>> needed because it currently doesn't further reduce the size. The same we
>> could with RelationPartitionInfo::partcheckvalid.
>> => sizeof(RelationData) == 264 bytes
> 
> I'm not a fan of this change.  Sentinel values *can* have their place,
> but I really don't like non-NULL values being used to signal "invalid"
> states, and seeing that it doesn't actually save any bytes I'd prefer
> to not add this complication.

The pointer itself has no invalid state. NULL is also a valid state.
This is why the extra flag is needed.

I'm in slight favor of keeping it because "is valid" booleans always
have the tendency to cause padding and I'm hopeful that we can further
strip down the struct so that the change is actually yielding a real saving.

I'm keeping the commit in the patch set for now, waiting for other
reviewers to chime in.

>> - 0008: Adds a static assertion that sizeof(RelationData) <= 256.
>> => sizeof(RelationData) == 256 bytes
> 
> I'm not a fan of this, because we generally don't add assertions on
> struct sizes unless it's critically important a struct remains the
> asserted size (or, in this case, doesn't become larger than that).
> In this case, I don't think it's critically important that the struct
> fits in the 256-byte aset bucket, given that relcache memory usage has
> never been capped, and a slab context would similarly do the trick for
> avoiding memory usage cliffs when the size of the struct is increased.
> 
>> Note that the necessity to arrive at 256 bytes stems from ASET's
>> allocation granularity being powers of two. To profit from further size
>> reductions of RelationData, we would need to use a SLAB memory context
>> because it's unlikely that we'll get to 128 bytes.

I've removed the patch because of changing to a slab memory context. See
comment below.

> Let's start with palloc-ing all RelationData into Slab contexts (like
> attached, tagged with .nocfbot to avoid your patch's CI).  This allows
> us to start saving bytes immediately, and immediately improves memory
> usage for every reduction in size so that the merits of each later
> patch can be evaluated separately.  This will be very useful if we
> can't agree on some of the changes that are necessary to reduce the
> size down to the next smaller aset size bucket.

Attached is patch 0002 that allocates all RelationData objects inside a
slab memory context. It's passing all tests together with all the other
patches.

I've also attached patch 0001 that removes two unnecessary checks for if
CacheMemoryContext is already initialized. This is no longer necessary
since #1aebc3618a0, #46287bd6602 and #d4d1885e42e. I wanted to get rid
of these checks so that I don't have to create the slab context in these
places as well.

Attached is the latest patch set rebased also on latest master. While
looking more closely at RelationData, I've realized that we can also
move rd_indexlist, rd_statlist, rd_pkindex, rd_toastoid and
rd_toastchunkidtype to the table union leg. As the index union leg is
currently bigger, that should yield some more savings. I'll give this a
try the next days.

--
David Geier

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
>>> - 0005: Replaces the embedded partition key, descriptors, partition
>>> qual, validity flag, and memory contexts with one lazily allocated
>>> RelationPartitionInfo pointer.
>>> => sizeof(RelationData) == 264 bytes

Since patch set v2, this happens in patch 0006. All patches moved by 1
because I added a new patch 0001 (use SLAB context for all RelationData
objects).

>> I haven't worked on partitioning, so I'm not fully confident that this
>> has sufficiently low additional overhead to be worth applying.
> 
> I'll run a partitioned pgbench and report if I could measure any
> regressions.

I ran pgbench with 1000 partitions and scale factor 1 to put maximum
pressure on planning which I assumed uses the relcache most:

pgbench -i -s 1 --partitions=1000 postgres
pgbench -c 1 -j 1 -T 60 -S -M simple postgres

I ran against master and my patch, while having turbo boost, frequency
scaling, CPU idle states, ASLR and hyper threading disabled. I used a
single client to further stabilize results. The runs are still a little
bit noisy but FWICS don't show a regression.

 TPS master | TPS patched
------------+------------
  46,633    |   46,488
  45,560    |   46,437
  46,445    |   45,866

I've also attached v3 which is v2 rebased on latest master. No other
changes.

--
David Geier

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Mon, 5 Oct 2026 at 13:48, David Geier  wrote:
>
> I've also attached v3 which is v2 rebased on latest master. No other
> changes.

Some high-level comments:

0003-0008: These need more commit description than they currently have.

0001:
Could you replace the conditional initializations with Assert()s that
the context is initialized?  That'll save any code that calls into
these functions too early.

0002: LGTM, though maybe an AllocRelationData() helper macro would
reduce the verbosity of each allocation, given that we're always
allocating into that one context.

0004:
I think this needs to introduce a field at the top level of
RelationData that indicates the variant of Relation that we're dealing
with.  Continuously dereferencing rel->rd_rel->relkind seems rather
expensive compared to "just" keeping track of another boolean (or
enum, char, or whatever type) at the front of the struct that
distinguishes the exact type of data contained, if we can afford to.

(It'll also make it easier to verify we're dealing with the right type
of Relation, as we won't have to Assert() two layers of indirection
deep)

> +++ relcache.c

I think this'll be better if it splits out the Table and Index parts
from RelationBuildDesc.

> +/*
> + * Field order within RelationData (and within each branch of the union
> + * further down) is chosen to minimize struct padding: pointer-sized
> + * (8-byte) fields are grouped first, followed by 4-byte fields, followed
> + * by 1-byte bool fields.  Don't reorder fields without re-checking that
> + * this packing is preserved.
> + */

I don't think this packing is necessarily better than "just" making
sure we order our fields in a way that introduces the fewest padding
bytes possible.  Also note that the patch doesn't actually group all
fields in that order, so the comment is already outdated.

0005:

The following change snippet:

> + * RelationGetLockRelId() derives the LockRelId to use for locking the
> + * relation from rd_id and rd_rel->relisshared, in case anything tries
> + * to lock the dummy relation.  We don't have a real OID for this fake
> + * entry, so use relNumber instead.  Note that this is fairly bogus
> + * since relNumber may be different from the relation's real OID.  It
> + * shouldn't really matter though.  In recovery, we are running by
> + * ourselves and can't have any lock conflicts.  While syncing, we
> + * already hold AccessExclusiveLock.  Set relisshared to match rlocator
> + * so that RelationGetLockRelId() derives the correct dbId for shared
> + * relations (InvalidOid); for non-shared relations it'll derive
> + * MyDatabaseId, which is correct whenever this is called from a real
> + * backend (e.g. while syncing) and simply irrelevant during recovery.
>   */
> - rel->rd_lockInfo.lockRelId.dbId = rlocator.dbOid;
> - rel->rd_lockInfo.lockRelId.relId = rlocator.relNumber;
> + rel->rd_id = rlocator.relNumber;
> + rel->rd_rel->relisshared = (rlocator.spcOid == GLOBALTABLESPACE_OID);

Shouldn't this test on rlocator.dbOid, or Assert() that the dbOid is
invalid when spcOid == GLOBALTABLESPACE_OID?  Asking, because the lock
code uses dbOid.


0006:

In RelationGetPartitionDesc(), and various other functions, it may
make sense to store rd_partdesc in a local variable, it'll save line
width whenever we're frequently checking its data.

0007: -1 on this patch; I don't think the cost/benefit of this change
in ergonomics is worth it.

0008: -1 on this patch, too: I don't think the byte savings are worth
these changes; especially given that this adds additional indirections
with more data dependencies on common paths.

It also adds a 2k line propgraphcmds.c without adding it to compile
targets for it in Makefile nor meson.build, was this a typo?


Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)


Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
Вложения:
On Tue, Oct 13, 2026 at 11:09 AM Matthias van de Meent
 wrote:
>
> On Mon, 5 Oct 2026 at 13:48, David Geier  wrote:
> >
> > I've also attached v3 which is v2 rebased on latest master. No other
> > changes.
>
> Some high-level comments:
>
> 0003-0008: These need more commit description than they currently have.
>
> 0001:
> Could you replace the conditional initializations with Assert()s that
> the context is initialized?  That'll save any code that calls into
> these functions too early.
>
> 0002: LGTM, though maybe an AllocRelationData() helper macro would
> reduce the verbosity of each allocation, given that we're always
> allocating into that one context.
>
> 0004:
> I think this needs to introduce a field at the top level of
> RelationData that indicates the variant of Relation that we're dealing
> with.  Continuously dereferencing rel->rd_rel->relkind seems rather
> expensive compared to "just" keeping track of another boolean (or
> enum, char, or whatever type) at the front of the struct that
> distinguishes the exact type of data contained, if we can afford to.
>
> (It'll also make it easier to verify we're dealing with the right type
> of Relation, as we won't have to Assert() two layers of indirection
> deep)
>
> > +++ relcache.c
>
> I think this'll be better if it splits out the Table and Index parts
> from RelationBuildDesc.
>
> > +/*
> > + * Field order within RelationData (and within each branch of the union
> > + * further down) is chosen to minimize struct padding: pointer-sized
> > + * (8-byte) fields are grouped first, followed by 4-byte fields, followed
> > + * by 1-byte bool fields.  Don't reorder fields without re-checking that
> > + * this packing is preserved.
> > + */
>
> I don't think this packing is necessarily better than "just" making
> sure we order our fields in a way that introduces the fewest padding
> bytes possible.  Also note that the patch doesn't actually group all
> fields in that order, so the comment is already outdated.
>
> 0005:
>
> The following change snippet:
>
> > + * RelationGetLockRelId() derives the LockRelId to use for locking the
> > + * relation from rd_id and rd_rel->relisshared, in case anything tries
> > + * to lock the dummy relation.  We don't have a real OID for this fake
> > + * entry, so use relNumber instead.  Note that this is fairly bogus
> > + * since relNumber may be different from the relation's real OID.  It
> > + * shouldn't really matter though.  In recovery, we are running by
> > + * ourselves and can't have any lock conflicts.  While syncing, we
> > + * already hold AccessExclusiveLock.  Set relisshared to match rlocator
> > + * so that RelationGetLockRelId() derives the correct dbId for shared
> > + * relations (InvalidOid); for non-shared relations it'll derive
> > + * MyDatabaseId, which is correct whenever this is called from a real
> > + * backend (e.g. while syncing) and simply irrelevant during recovery.
> >   */
> > - rel->rd_lockInfo.lockRelId.dbId = rlocator.dbOid;
> > - rel->rd_lockInfo.lockRelId.relId = rlocator.relNumber;
> > + rel->rd_id = rlocator.relNumber;
> > + rel->rd_rel->relisshared = (rlocator.spcOid == GLOBALTABLESPACE_OID);
>
> Shouldn't this test on rlocator.dbOid, or Assert() that the dbOid is
> invalid when spcOid == GLOBALTABLESPACE_OID?  Asking, because the lock
> code uses dbOid.
>
>
> 0006:
>
> In RelationGetPartitionDesc(), and various other functions, it may
> make sense to store rd_partdesc in a local variable, it'll save line
> width whenever we're frequently checking its data.
>
> 0007: -1 on this patch; I don't think the cost/benefit of this change
> in ergonomics is worth it.
>
> 0008: -1 on this patch, too: I don't think the byte savings are worth
> these changes; especially given that this adds additional indirections
> with more data dependencies on common paths.
>
> It also adds a 2k line propgraphcmds.c without adding it to compile
> targets for it in Makefile nor meson.build, was this a typo?
>
>
> Kind regards,
>
> Matthias van de Meent
> Databricks (https://www.databricks.com)
>
>

Hi David,
I tested v3 independently on Linux x86_64, based on 9dbc53591a2.  All
eight attachments apply there without context changes.  I concentrated
on v3 0001-0006, following the cost/benefit concerns already raised by
Matthias about 0007 and 0008.
I found a predicate-locking crash introduced by the union in 0004.  The
predicate code uses rd_index (and, with 0008, RelationGetIndex()) to
decide whether a Relation is an index.  For a rule-bearing table,
rd_rules occupies the same union storage, so that test can interpret a
RuleLock as index metadata.
This reproduces with 0001-0006; 0008 is not required.  A minimal case is:

  CREATE TABLE t (a int PRIMARY KEY);
  CREATE RULE r AS ON INSERT TO t DO ALSO SELECT 1;
  BEGIN ISOLATION LEVEL SERIALIZABLE;
  INSERT INTO t VALUES (1);
  TRUNCATE t;
In a cassert build, TRUNCATE aborts at
CheckTableForSerializableConflictIn().  At that point relkind is 'r',
and rd_rules and the overlaid rd_index contain the same non-NULL address.
The server process exits with SIGABRT.  The unpatched baseline passes the
same pg_regress test.
The first attached patch adds RelationIsIndex(), based on relkind, and
uses it at the three predicate-locking classification sites.  The second
adds the pg_regress test.  Both ordinary and partitioned indexes remain
covered by the predicate.

I also reproduced an ERROR-path problem from 0006 using an injection
point at its new RelationPartitionInfo allocation inside
RelationRebuildRelation().  After an ALTER TABLE added a column to a
partitioned table, the injected ERROR occurred after the descriptor swap.
Rollback restored the two-column catalog state, but the same backend kept
the three-column descriptor and then reported:

  could not find inherited attribute "key_added"

An equivalent general swap window exists without this series.  The v3
regression is specifically that 0006 adds an allocation failure point to
the region.  I did not observe or claim a real OOM.

The third patch allocates destination partition metadata before the swap
and before reparenting a completed partition-key context.  It also avoids
reading table-side partition metadata for index relations.  With the
allocation moved before the swap, an ERROR leaves the old descriptor intact
and marked invalid; the next lookup rebuilds it normally after rollback.
Ten repeated subtransaction failures, partitioned indexes, and
debug_discard_caches=1 also passed without an external invalidation.

Finally, the init-file loader reconstructs index access fields but does
not reset rd_indexprs, rd_indpred, rd_exclops, rd_exclprocs, or
rd_exclstrats.  Those are serialized process pointers whose contents are
supposed to be initialized lazily.  The fourth patch resets the five
fields without changing the init-file format.  I did not find a reachable
failure with current catalog indexes, so I regard this as an
initialization correctness hazard rather than a demonstrated SQL crash.

On Linux, sizeof(RelationData) is 496 bytes at the baseline, 272 through
0006 and 0007, and 264 through 0008.  Under the same 8 KiB Slab setup,
0006 and 0007 both used 302 blocks and 2,474,160 total bytes for a workload
loading 8,731 relations.  This supports the limited-benefit point already
made in the review discussion.

One additional issue: original v3 0008 does not build on this base because
execReplication.c still has two rd_index references.  I did not repair it
silently or use that configuration for runtime results.

Validation was on Linux 6.17 x86_64 with GCC 13.3 and Clang 18.1.  GCC
cassert and release check-world passed (240 core regression and 133
isolation tests).  Clang ASan/UBSan core and isolation suites also passed.

Attachments:

  0001: classify indexes by relkind in predicate locking
  0002: add the rule-bearing SERIALIZABLE regression test
  0003: keep partition-info allocations outside descriptor swaps
  0004: reset lazy index pointers after init-file loading

Regards,
Haibo

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
> 0003-0008: These need more commit description than they currently have.

Updated commit messages, including sizeof(RelationData).

> 0001:
> Could you replace the conditional initializations with Assert()s that
> the context is initialized?  That'll save any code that calls into
> these functions too early.

Done.

> 0002: LGTM, though maybe an AllocRelationData() helper macro would
> reduce the verbosity of each allocation, given that we're always
> allocating into that one context.

Done.

> 0004:
> I think this needs to introduce a field at the top level of
> RelationData that indicates the variant of Relation that we're dealing
> with.  Continuously dereferencing rel->rd_rel->relkind seems rather
> expensive compared to "just" keeping track of another boolean (or
> enum, char, or whatever type) at the front of the struct that
> distinguishes the exact type of data contained, if we can afford to.
> 
> (It'll also make it easier to verify we're dealing with the right type
> of Relation, as we won't have to Assert() two layers of indirection
> deep)

I would prefer to not do that. I like that now we have a single source
of truth and adding such a field would be a bunch of code churn.
Performance-wise the extra indirection doesn't matter. It's not accessed
anywhere in way that it's expensive relative to all the other stuff
happening. The pgbench I ran support that claim.

> I think this'll be better if it splits out the Table and Index parts> from RelationBuildDesc.

I'm not sure what you're exactly after here. Can you share some more
details please?

>> +/*
>> + * Field order within RelationData (and within each branch of the union
>> + * further down) is chosen to minimize struct padding: pointer-sized
>> + * (8-byte) fields are grouped first, followed by 4-byte fields, followed
>> + * by 1-byte bool fields.  Don't reorder fields without re-checking that
>> + * this packing is preserved.
>> + */
> 
> I don't think this packing is necessarily better than "just" making
> sure we order our fields in a way that introduces the fewest padding
> bytes possible.  Also note that the patch doesn't actually group all
> fields in that order, so the comment is already outdated.

Agreed. Also I somehow lost a commit before creating the patch set.
Previously, adding the unions and doing the packing was two commits. I
split the commit again and did the packing such that we reach the
smallest struct size while minimizing the number of code lines moved. I
also removed the comment.

> 0005:
> 
> The following change snippet:
> 
>> + * RelationGetLockRelId() derives the LockRelId to use for locking the
>> + * relation from rd_id and rd_rel->relisshared, in case anything tries
>> + * to lock the dummy relation.  We don't have a real OID for this fake
>> + * entry, so use relNumber instead.  Note that this is fairly bogus
>> + * since relNumber may be different from the relation's real OID.  It
>> + * shouldn't really matter though.  In recovery, we are running by
>> + * ourselves and can't have any lock conflicts.  While syncing, we
>> + * already hold AccessExclusiveLock.  Set relisshared to match rlocator
>> + * so that RelationGetLockRelId() derives the correct dbId for shared
>> + * relations (InvalidOid); for non-shared relations it'll derive
>> + * MyDatabaseId, which is correct whenever this is called from a real
>> + * backend (e.g. while syncing) and simply irrelevant during recovery.
>>   */
>> - rel->rd_lockInfo.lockRelId.dbId = rlocator.dbOid;
>> - rel->rd_lockInfo.lockRelId.relId = rlocator.relNumber;
>> + rel->rd_id = rlocator.relNumber;
>> + rel->rd_rel->relisshared = (rlocator.spcOid == GLOBALTABLESPACE_OID);
> 
> Shouldn't this test on rlocator.dbOid, or Assert() that the dbOid is
> invalid when spcOid == GLOBALTABLESPACE_OID?  Asking, because the lock
> code uses dbOid.

Yes. Added an assertion and changed it to use test on rlocator.dbOid.

> 0006:
> 
> In RelationGetPartitionDesc(), and various other functions, it may
> make sense to store rd_partdesc in a local variable, it'll save line
> width whenever we're frequently checking its data.

rd_partdesc got moved into RelationPartitionInfo and is now called
partdesc. I'm assuming you meant RelationData::rd_partinfo?

I went through all places where it's used frequently and stored it in a
local variable.

> 0007: -1 on this patch; I don't think the cost/benefit of this change
> in ergonomics is worth it.
> 
> 0008: -1 on this patch, too: I don't think the byte savings are worth
> these changes; especially given that this adds additional indirections
> with more data dependencies on common paths.

With the latest patch set these two patches no longer reduce the struct
size. Fine by me to exclude them for now. Removed from the latest patch set.

> It also adds a 2k line propgraphcmds.c without adding it to compile
> targets for it in Makefile nor meson.build, was this a typo?

My bad. That happened by accident somehow when rebasing on master.
Removed in the new patch set.


I'm sending the new patch set, including the changes to address above
review comments, in my reply to Haibo's review mail.

--
David Geier


Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
Hi Haibo,

Thanks for your review and kudos for providing test cases and fixes.
Much appreciated.

> I tested v3 independently on Linux x86_64, based on 9dbc53591a2.  All
> eight attachments apply there without context changes.  I concentrated
> on v3 0001-0006, following the cost/benefit concerns already raised by
> Matthias about 0007 and 0008.

I've removed 0007 and 0008 from the new patch set.

> I found a predicate-locking crash introduced by the union in 0004.  The
> predicate code uses rd_index (and, with 0008, RelationGetIndex()) to
> decide whether a Relation is an index.  For a rule-bearing table,
> rd_rules occupies the same union storage, so that test can interpret a
> RuleLock as index metadata.
> This reproduces with 0001-0006; 0008 is not required.  A minimal case is:
> 
>   CREATE TABLE t (a int PRIMARY KEY);
>   CREATE RULE r AS ON INSERT TO t DO ALSO SELECT 1;
>   BEGIN ISOLATION LEVEL SERIALIZABLE;
>   INSERT INTO t VALUES (1);
>   TRUNCATE t;
> In a cassert build, TRUNCATE aborts at
> CheckTableForSerializableConflictIn().  At that point relkind is 'r',
> and rd_rules and the overlaid rd_index contain the same non-NULL address.
> The server process exits with SIGABRT.  The unpatched baseline passes the
> same pg_regress test.
> The first attached patch adds RelationIsIndex(), based on relkind, and> uses it at the three predicate-locking classification sites.  The second
> adds the pg_regress test.  Both ordinary and partitioned indexes remain
> covered by the predicate.

Fixed the problem using your patch. I don't think we should include the
test cases as it's very specific. Opinions?

> I also reproduced an ERROR-path problem from 0006 using an injection
> point at its new RelationPartitionInfo allocation inside
> RelationRebuildRelation().  After an ALTER TABLE added a column to a
> partitioned table, the injected ERROR occurred after the descriptor swap.
> Rollback restored the two-column catalog state, but the same backend kept
> the three-column descriptor and then reported:
> 
>   could not find inherited attribute "key_added"

Good catch!

> An equivalent general swap window exists without this series.  The v3
> regression is specifically that 0006 adds an allocation failure point to
> the region.  I did not observe or claim a real OOM.
> 
> The third patch allocates destination partition metadata before the swap
> and before reparenting a completed partition-key context.  It also avoids
> reading table-side partition metadata for index relations.  With the
> allocation moved before the swap, an ERROR leaves the old descriptor intact
> and marked invalid; the next lookup rebuilds it normally after rollback.
> Ten repeated subtransaction failures, partitioned indexes, and
> debug_discard_caches=1 also passed without an external invalidation.

Fixed the problem using your patch.

> Finally, the init-file loader reconstructs index access fields but does
> not reset rd_indexprs, rd_indpred, rd_exclops, rd_exclprocs, or
> rd_exclstrats.  Those are serialized process pointers whose contents are
> supposed to be initialized lazily.  The fourth patch resets the five
> fields without changing the init-file format.  I did not find a reachable
> failure with current catalog indexes, so I regard this as an
> initialization correctness hazard rather than a demonstrated SQL crash.

Fixed as well. Additionally moved into the else branch of the check

if (!RelationIsIndex(rel))

so that all code that resets lazily built fields is in one place.

> On Linux, sizeof(RelationData) is 496 bytes at the baseline, 272 through
> 0006 and 0007, and 264 through 0008.  Under the same 8 KiB Slab setup,
> 0006 and 0007 both used 302 blocks and 2,474,160 total bytes for a workload
> loading 8,731 relations.  This supports the limited-benefit point already
> made in the review discussion.

With the latest patch set (excluding 0007 and 0008), we go from 496
bytes on master to 248 bytes.

> One additional issue: original v3 0008 does not build on this base because
> execReplication.c still has two rd_index references.  I did not repair it
> silently or use that configuration for runtime results.

Removed in latest patch set.


Attached is v4 of the patch set.

Beyond that:

1. Bumped RELCACHE_INIT_FILEMAGIC in any patch that makes structural
changes to struct RelationData, so that PostgreSQL rebuilds old init
files if necessary.

2. Moved many more members that are relation-only to the corresponding
union leg.

3. Moved members related to partitioning out of the relation-only table
leg because indexes can be partitioned as well.

--
David Geier

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Fri, 16 Oct 2026 at 15:02, David Geier  wrote:
> > 0004:
> > I think this needs to introduce a field at the top level of
> > RelationData that indicates the variant of Relation that we're dealing
> > with.  Continuously dereferencing rel->rd_rel->relkind seems rather
> > expensive compared to "just" keeping track of another boolean (or
> > enum, char, or whatever type) at the front of the struct that
> > distinguishes the exact type of data contained, if we can afford to.
> >
> > (It'll also make it easier to verify we're dealing with the right type
> > of Relation, as we won't have to Assert() two layers of indirection
> > deep)
>
> I would prefer to not do that. I like that now we have a single source
> of truth and adding such a field would be a bunch of code churn.

What specifically would need a bunch of code churn?  The paths we're
dealing with shouldn't need much (if any) changes in that regard.  One
reason to do this is to make it simpler to add another variant to the
union, if/when we figure out how to split the larger of [table-like,
index-like] relations further.

> Performance-wise the extra indirection doesn't matter. It's not accessed
> anywhere in way that it's expensive relative to all the other stuff
> happening. The pgbench I ran support that claim.

Sure, but for debugging and for interpretability I do think that it
makes more sense to have an indicator which of the two variants
should/can be accessed that is stored in the Relation itself. It'll
also simplify the condition (from two OR-ed options to just one) and
will make adding future variants (if any) simpler by allowing using
switch() blocks when we need to handle generic Relations.

> > I think this'll be better if it splits out the Table and Index parts> from RelationBuildDesc.
>
> I'm not sure what you're exactly after here. Can you share some more
> details please?

I meant that the code of RelationBuildDesc would be easier to read and
understand if we split the code that fills in the shared fields from
the code that fills in the index variant of the union and from the
code that fills in the non-index parts of the union, instead of mixing
those. That doesn't need to be in a different function per se, but
could also just be a better vertical grouping with a singular if/else
block.

> > 0005:
> > 0006:
> >
> > In RelationGetPartitionDesc(), and various other functions, it may
> > make sense to store rd_partdesc in a local variable, it'll save line
> > width whenever we're frequently checking its data.
>
> rd_partdesc got moved into RelationPartitionInfo and is now called
> partdesc. I'm assuming you meant RelationData::rd_partinfo?

Yes

> I went through all places where it's used frequently and stored it in a
> local variable.

Thanks.


Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)


Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
Вложения:
Hi,

> From: David Geier 
> Date: Wed, 2 Sep 2026 14:06:21 +0200
> Subject: [PATCH v4 3/7] Move RelationData to an internal header
> 
> Move the definition of RelationData into utils/rel_internal.h.  Otherwise,
> gen_node_support.pl cannot process rel.h after the anonymous unions are
> introduced by the following commit, because the script does not support
> parsing anonymous unions.

I really dislike this.  Why not do it the other way around, and put the
one struct that gen_node_support.pl wants in a separate file instead?
As in the attached WIP.  New file name TBD, of course.

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"El Maquinismo fue proscrito so pena de cosquilleo hasta la muerte"
(Ijon Tichy en Viajes, Stanislaw Lem)

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
Haibo Yan <tristan.yim@gmail.com>
Дата:
On Fri, Oct 16, 2026 at 6:02 AM David Geier  wrote:
>
> Hi Haibo,
>
> Thanks for your review and kudos for providing test cases and fixes.
> Much appreciated.
>
> > I tested v3 independently on Linux x86_64, based on 9dbc53591a2.  All
> > eight attachments apply there without context changes.  I concentrated
> > on v3 0001-0006, following the cost/benefit concerns already raised by
> > Matthias about 0007 and 0008.
>
> I've removed 0007 and 0008 from the new patch set.
>
> > I found a predicate-locking crash introduced by the union in 0004.  The
> > predicate code uses rd_index (and, with 0008, RelationGetIndex()) to
> > decide whether a Relation is an index.  For a rule-bearing table,
> > rd_rules occupies the same union storage, so that test can interpret a
> > RuleLock as index metadata.
> > This reproduces with 0001-0006; 0008 is not required.  A minimal case is:
> >
> >   CREATE TABLE t (a int PRIMARY KEY);
> >   CREATE RULE r AS ON INSERT TO t DO ALSO SELECT 1;
> >   BEGIN ISOLATION LEVEL SERIALIZABLE;
> >   INSERT INTO t VALUES (1);
> >   TRUNCATE t;
> > In a cassert build, TRUNCATE aborts at
> > CheckTableForSerializableConflictIn().  At that point relkind is 'r',
> > and rd_rules and the overlaid rd_index contain the same non-NULL address.
> > The server process exits with SIGABRT.  The unpatched baseline passes the
> > same pg_regress test.
> > The first attached patch adds RelationIsIndex(), based on relkind, and> uses it at the three predicate-locking classification sites.  The second
> > adds the pg_regress test.  Both ordinary and partitioned indexes remain
> > covered by the predicate.
>
> Fixed the problem using your patch. I don't think we should include the
> test cases as it's very specific. Opinions?
>
> > I also reproduced an ERROR-path problem from 0006 using an injection
> > point at its new RelationPartitionInfo allocation inside
> > RelationRebuildRelation().  After an ALTER TABLE added a column to a
> > partitioned table, the injected ERROR occurred after the descriptor swap.
> > Rollback restored the two-column catalog state, but the same backend kept
> > the three-column descriptor and then reported:
> >
> >   could not find inherited attribute "key_added"
>
> Good catch!
>
> > An equivalent general swap window exists without this series.  The v3
> > regression is specifically that 0006 adds an allocation failure point to
> > the region.  I did not observe or claim a real OOM.
> >
> > The third patch allocates destination partition metadata before the swap
> > and before reparenting a completed partition-key context.  It also avoids
> > reading table-side partition metadata for index relations.  With the
> > allocation moved before the swap, an ERROR leaves the old descriptor intact
> > and marked invalid; the next lookup rebuilds it normally after rollback.
> > Ten repeated subtransaction failures, partitioned indexes, and
> > debug_discard_caches=1 also passed without an external invalidation.
>
> Fixed the problem using your patch.
>
> > Finally, the init-file loader reconstructs index access fields but does
> > not reset rd_indexprs, rd_indpred, rd_exclops, rd_exclprocs, or
> > rd_exclstrats.  Those are serialized process pointers whose contents are
> > supposed to be initialized lazily.  The fourth patch resets the five
> > fields without changing the init-file format.  I did not find a reachable
> > failure with current catalog indexes, so I regard this as an
> > initialization correctness hazard rather than a demonstrated SQL crash.
>
> Fixed as well. Additionally moved into the else branch of the check
>
> if (!RelationIsIndex(rel))
>
> so that all code that resets lazily built fields is in one place.
>
> > On Linux, sizeof(RelationData) is 496 bytes at the baseline, 272 through
> > 0006 and 0007, and 264 through 0008.  Under the same 8 KiB Slab setup,
> > 0006 and 0007 both used 302 blocks and 2,474,160 total bytes for a workload
> > loading 8,731 relations.  This supports the limited-benefit point already
> > made in the review discussion.
>
> With the latest patch set (excluding 0007 and 0008), we go from 496
> bytes on master to 248 bytes.
>
> > One additional issue: original v3 0008 does not build on this base because
> > execReplication.c still has two rd_index references.  I did not repair it
> > silently or use that configuration for runtime results.
>
> Removed in latest patch set.
>
>
> Attached is v4 of the patch set.
>
> Beyond that:
>
> 1. Bumped RELCACHE_INIT_FILEMAGIC in any patch that makes structural
> changes to struct RelationData, so that PostgreSQL rebuilds old init
> files if necessary.
>
> 2. Moved many more members that are relation-only to the corresponding
> union leg.
>
> 3. Moved members related to partitioning out of the relation-only table
> leg because indexes can be partitioned as well.
>
> --
> David Geier

Hi David,

I took a closer look at the relation-kind-specific field overlay
introduced by patch 0004, particularly the relcache accessors and
initialization paths affected by the new union.

I found one API compatibility regression and two minor issues worth
considering for v5.

1. RelationGetIndexExpressions(), RelationGetDummyIndexExpressions(),
   and RelationGetIndexPredicate()

RelationGetIndexExpressions() and RelationGetIndexPredicate()
explicitly document that they return NIL for non-index relations.
The new union changes this behavior because several index-specific
fields overlap with table-specific cache fields:

  rd_indexprs   / rd_pkattr
  rd_indpred    / rd_idattr
  rd_indextuple / rd_rulescxt

With the table caches populated, these functions can return
incorrectly typed pointers or encounter errors. In some builds,
the invalid access can also cause a backend crash.

I reproduced this using a small C test extension with real
Relation objects:

  - Master: NIL for all tested non-index relations.
  - Original v4: incorrect non-NIL results, ERRORs, or crashes.
  - Fixed v4: NIL for all tested non-index relations.

RelationGetDummyIndexExpressions() is also affected by the
rd_indextuple overlap. Although its comment does not explicitly
promise NIL for non-index relations, that was its previous behavior.

The minimal fix is to add the following check at the beginning
of all three functions:

    if (!RelationIsIndex(relation))
        return NIL;

I also checked the core callers and found no path that passes
a non-index Relation to these functions. Therefore, this appears
to be an API compatibility regression for backend C callers,
rather than a bug reachable through ordinary SQL.

2. RelationCacheInitializePhase3()

The condition checks rd_tableam before checking the relation kind.
For indexes, rd_tableam overlaps with rd_indcollation.

Reversing the condition would avoid reading the inactive union
member. I found no observable correctness issue here.

3. RelationBuildDesc()

The unconditional initialization of rd_fkeylist, rd_fkeyvalid,
and rd_toastchunkidtype also writes to storage used by
index-specific fields.

These writes currently appear harmless because the allocation
is zero-initialized and the index fields are initialized later.
Guarding these assignments with !RelationIsIndex() would make
the union usage clearer and less fragile.

I validated the proposed changes on Linux/GCC and macOS/Clang.
The targeted tests passed with the fixes, as did the regression
and isolation suites. The Linux fixed-v4 build also passed
check-world with TAP tests enabled.

Overall, the series looks good to me with the API regression
addressed. The other two changes are minor cleanups.

Thanks,
Haibo


Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
>> Move the definition of RelationData into utils/rel_internal.h.  Otherwise,
>> gen_node_support.pl cannot process rel.h after the anonymous unions are
>> introduced by the following commit, because the script does not support
>> parsing anonymous unions.
> 
> I really dislike this.  Why not do it the other way around, and put the
> one struct that gen_node_support.pl wants in a separate file instead?
> As in the attached WIP.  New file name TBD, of course.
That's indeed nicer.

I had moved struct RelationData to rel_internal.h as a quick workaround
when I started to be able to make progress without bothering. Now it's
time to fix this properly.

We can do what you suggest, or alternatively, teach gen_node_support.pl
to skip anonymous structs/unions in non-node structs. Then we can keep
all code as before in rel.h. See attached patch.

Once we settle on how to go forward, I'll update the main patch set.

--
David Geier

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
Thanks for taking another look.

> I took a closer look at the relation-kind-specific field overlay
> introduced by patch 0004, particularly the relcache accessors and
> initialization paths affected by the new union.
> 
> I found one API compatibility regression and two minor issues worth
> considering for v5.
> 
> 1. RelationGetIndexExpressions(), RelationGetDummyIndexExpressions(),
>    and RelationGetIndexPredicate()
> 
> RelationGetIndexExpressions() and RelationGetIndexPredicate()
> explicitly document that they return NIL for non-index relations.
> The new union changes this behavior because several index-specific
> fields overlap with table-specific cache fields:
> 
>   rd_indexprs   / rd_pkattr
>   rd_indpred    / rd_idattr
>   rd_indextuple / rd_rulescxt
> 
> With the table caches populated, these functions can return
> incorrectly typed pointers or encounter errors. In some builds,
> the invalid access can also cause a backend crash.
> 
> I reproduced this using a small C test extension with real
> Relation objects:
> 
>   - Master: NIL for all tested non-index relations.
>   - Original v4: incorrect non-NIL results, ERRORs, or crashes.
>   - Fixed v4: NIL for all tested non-index relations.
> 
> RelationGetDummyIndexExpressions() is also affected by the
> rd_indextuple overlap. Although its comment does not explicitly
> promise NIL for non-index relations, that was its previous behavior.
> 
> The minimal fix is to add the following check at the beginning
> of all three functions:
> 
>     if (!RelationIsIndex(relation))
>         return NIL;

Changed all three functions as suggested by you.

> 2. RelationCacheInitializePhase3()
> 
> The condition checks rd_tableam before checking the relation kind.
> For indexes, rd_tableam overlaps with rd_indcollation.
> 
> Reversing the condition would avoid reading the inactive union
> member. I found no observable correctness issue here.

Changed.

> 3. RelationBuildDesc()
> 
> The unconditional initialization of rd_fkeylist, rd_fkeyvalid,
> and rd_toastchunkidtype also writes to storage used by
> index-specific fields.
> 
> These writes currently appear harmless because the allocation
> is zero-initialized and the index fields are initialized later.
> Guarding these assignments with !RelationIsIndex() would make
> the union usage clearer and less fragile.

Changed.

I'll soon send the updated patch set in reply to Matthias mail.

--
David Geier


Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Fri, 16 Oct 2026 at 15:02, David Geier  wrote:
>
> Attached is v4 of the patch set.

0002:

Though I suggested the macro, I'm very much open to changing the name
to something better than AllocRelationData().

> @@ -6301,7 +6324,8 @@ load_relcache_init_file(bool shared)
>   rels = repalloc_array(rels, Relation, max_rels);
>   }
>
> - rel = rels[num_rels++] = (Relation) palloc(len);
> + rel = rels[num_rels++] = (Relation)
> + MemoryContextAlloc(RelationSlabContext, len);
>

This should probably check that len == sizeof(RelationData), and then
just use the AllocRelationData() macro used everywhere else.

0003: I agree with Alvaro's comment; if moving ForeignKeyCacheInfo to
its own header would also solve the issue then that's preferred.

0004:

> Table-like relations and indexes use disjoint sets of cached metadata.  Put
> those fields in an anonymous union so each relcache entry pays only for the
> larger set instead of both sets.

I'd write that as

[...] pays only for the larger of both sets, instead of the sum of both sets.


> +++ b/src/backend/storage/lmgr/predicate.c
> @@ -2558,7 +2558,7 @@ PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapsho
>     /*
>      * Return if this xact wrote it.
>      */
> -    if (relation->rd_index == NULL)
> +    if (!RelationIsIndex(relation))

You mentioned that the additional lookup is minimal, but I have to
disagree here.  In this case, non-indexes can go into a short path
that's now one indirection more expensive than before.  All the
changes from rd_index checks to RelationIsIndex() with higher
indirections may also be a sign that this is a common pattern that's
become more expensive.

> -    Assert(relation->rd_index == NULL); /* not an index relation */
> +    Assert(!RelationIsIndex(relation));

Let's not drop the comments in the refactoring.

> @@ -2658,9 +2669,9 @@ RelationRebuildRelation(Relation relation)

I think this should be treated similar to
RelationBuildDesc/RelationDestroyRelation: Have a common path for
non-union fields, and then a single code block (if+else, or
switch+cases) for each of the union's variants.

0005:

I think maybe we should put RelationPartitionInfo into a Slab
allocator, too, or somehow figure out how to reduce its size. It's
currently 8 pointers, plus 5 bytes of scalar fields and 3 bytes of
alignment. That's just a bit larger than Aset's 64-byte bucket
boundary, and I'd hate to waste 56 bytes /allocation in highly
partitioned workloads.

0006:
By splitting enabled/valid -bools away from their pointers, we're
reducing locality of lookups by a small margin, making accesses on
just those fields slightly more expensive if they're not found on the
same cache line.  I think the savings can still be worth it, but it's
something you may want to think about a bit more.

Nit:
> +    bool        pgstat_enabled; /* should relation stats be counted */
This is a pre-existing nit, but I'm not happy with the inconsistent
name of this field (and its sibling pgstat_info). All other fields are
rd_-prefixed, except these pgstat_-prefixed fields.

0007:
> +++ b/src/backend/access/nbtree/nbtutils.c
> +#include "storage/lmgr.h"

> +++ b/src/include/utils/rel.h
> +#include "miscadmin.h"

Why did we need add includes here, when both already should have
rel.h's full definitions included, and the changes are relevant only
for things that touch(ed) RelationData directly?


Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)


Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
>>> 0004:
>>> I think this needs to introduce a field at the top level of
>>> RelationData that indicates the variant of Relation that we're dealing
>>> with.  Continuously dereferencing rel->rd_rel->relkind seems rather
>>> expensive compared to "just" keeping track of another boolean (or
>>> enum, char, or whatever type) at the front of the struct that
>>> distinguishes the exact type of data contained, if we can afford to.
>>>
>>> (It'll also make it easier to verify we're dealing with the right type
>>> of Relation, as we won't have to Assert() two layers of indirection
>>> deep)
>>
>> I would prefer to not do that. I like that now we have a single source
>> of truth and adding such a field would be a bunch of code churn.
> 
> What specifically would need a bunch of code churn?  The paths we're
> dealing with shouldn't need much (if any) changes in that regard.  One
> reason to do this is to make it simpler to add another variant to the
> union, if/when we figure out how to split the larger of [table-like,
> index-like] relations further.
> 
>> Performance-wise the extra indirection doesn't matter. It's not accessed
>> anywhere in way that it's expensive relative to all the other stuff
>> happening. The pgbench I ran support that claim.
> 
> Sure, but for debugging and for interpretability I do think that it
> makes more sense to have an indicator which of the two variants
> should/can be accessed that is stored in the Relation itself. It'll
> also simplify the condition (from two OR-ed options to just one) and
> will make adding future variants (if any) simpler by allowing using
> switch() blocks when we need to handle generic Relations.

Took a stab at it in a new top commit so we can discuss before
integrating it throughout all existing commits.

>>> I think this'll be better if it splits out the Table and Index parts> from RelationBuildDesc.
>>
>> I'm not sure what you're exactly after here. Can you share some more
>> details please?
> 
> I meant that the code of RelationBuildDesc would be easier to read and
> understand if we split the code that fills in the shared fields from
> the code that fills in the index variant of the union and from the
> code that fills in the non-index parts of the union, instead of mixing
> those. That doesn't need to be in a different function per se, but
> could also just be a better vertical grouping with a singular if/else
> block.
Done. Now, first comes all shared initialization code, then
  if (RelationIsIndex())
with the two legs for index and non-index specific RelationData members.


I'll send out a new patch set once I've addressed the review comments in
your latest mail.

--
David Geier


Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
Hi Matthias!

Thanks for taking another look.

> Though I suggested the macro, I'm very much open to changing the name
> to something better than AllocRelationData().
> 
>> @@ -6301,7 +6324,8 @@ load_relcache_init_file(bool shared)
>>   rels = repalloc_array(rels, Relation, max_rels);
>>   }

I'm generally okay with the name. Maybe AllocRelcacheEntry() would be
better?

>> - rel = rels[num_rels++] = (Relation) palloc(len);
>> + rel = rels[num_rels++] = (Relation)
>> + MemoryContextAlloc(RelationSlabContext, len);
>>
> 
> This should probably check that len == sizeof(RelationData), and then
> just use the AllocRelationData() macro used everywhere else.

Changed to use AllocRelationData(). A few lines above there's already

if (len != sizeof(RelationData))
	goto read_failed;

Hence, no need for an assertion.

> 0003: I agree with Alvaro's comment; if moving ForeignKeyCacheInfo to
> its own header would also solve the issue then that's preferred.

I'm waiting for Alvaro's and Peter's reply before changing that part.

Any thoughts from your side regarding moving ForeignKeyCacheInfo into
its own header vs building support for anonymous structs/unions in
gen_node_support.pl?

> 0004:
> 
>> Table-like relations and indexes use disjoint sets of cached metadata.  Put
>> those fields in an anonymous union so each relcache entry pays only for the
>> larger set instead of both sets.
> 
> I'd write that as
> 
> [...] pays only for the larger of both sets, instead of the sum of both sets.

Done.

>> +++ b/src/backend/storage/lmgr/predicate.c
>> @@ -2558,7 +2558,7 @@ PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapsho
>>     /*
>>      * Return if this xact wrote it.
>>      */
>> -    if (relation->rd_index == NULL)
>> +    if (!RelationIsIndex(relation))
> 
> You mentioned that the additional lookup is minimal, but I have to
> disagree here.  In this case, non-indexes can go into a short path
> that's now one indirection more expensive than before.  All the
> changes from rd_index checks to RelationIsIndex() with higher
> indirections may also be a sign that this is a common pattern that's
> become more expensive.

Let's see how that works out. I had started to implement something but
let's better first clarify upfront some details:

Was your idea to simply store a char relkind in struct RelationData? Or
rather a bool is_index, or yet something else?

And then we would change RelationIsIndex() to read that field. Anything
else?

>> -    Assert(relation->rd_index == NULL); /* not an index relation */
>> +    Assert(!RelationIsIndex(relation));
> 
> Let's not drop the comments in the refactoring.

That was intentional. I thought with the new macro the code is as
expressive as the comment. I don't mind putting it back if you think it
improves readability.

>> @@ -2658,9 +2669,9 @@ RelationRebuildRelation(Relation relation)
> 
> I think this should be treated similar to
> RelationBuildDesc/RelationDestroyRelation: Have a common path for
> non-union fields, and then a single code block (if+else, or
> switch+cases) for each of the union's variants.

The function cannot be split into just three blocks because there some
dependencies but I streamlined the code flow somewhat without making the
diff impossible to review.

> 0005:
> 
> I think maybe we should put RelationPartitionInfo into a Slab
> allocator, too, or somehow figure out how to reduce its size. It's
> currently 8 pointers, plus 5 bytes of scalar fields and 3 bytes of
> alignment. That's just a bit larger than Aset's 64-byte bucket
> boundary, and I'd hate to waste 56 bytes /allocation in highly
> partitioned workloads.

That or we could - FWICS - remove partkeycxt because partkey is always
freed together with partkeycxt and we can recover the context via
GetMemoryChunkContext(partinfo->partkey).

That's less invasive but probably not as clean.

> 0006:
> By splitting enabled/valid -bools away from their pointers, we're
> reducing locality of lookups by a small margin, making accesses on
> just those fields slightly more expensive if they're not found on the
> same cache line.  I think the savings can still be worth it, but it's
> something you may want to think about a bit more.

When I tested if moving out the partition members causes regressions, I
also tested if moving away the booleans causes regressions. Back then I
couldn't measure any regression.

If we ever find a regression related to that we could always switch to
the sentinel pointer pattern. I know that you don't like that too much
but it would give us both.

> Nit:
>> +    bool        pgstat_enabled; /* should relation stats be counted */
> This is a pre-existing nit, but I'm not happy with the inconsistent
> name of this field (and its sibling pgstat_info). All other fields are
> rd_-prefixed, except these pgstat_-prefixed fields.

+1 but let's do that in a separate thread.

> 0007:
>> +++ b/src/backend/access/nbtree/nbtutils.c
>> +#include "storage/lmgr.h"
> 
>> +++ b/src/include/utils/rel.h
>> +#include "miscadmin.h"
> 
> Why did we need add includes here, when both already should have
> rel.h's full definitions included, and the changes are relevant only
> for things that touch(ed) RelationData directly?

* The lmgr.h include is unnecessary. Removed.
* The miscadmin.h include is necessary for MyDatabaseId.


I've also created a commitfest entry, see [1].

--
David Geier

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

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
"Yilin Zhang" <jiezhilove@126.com>
Дата:
At 2026-10-19 21:31:32, "David Geier" <geidav.pg@gmail.com> wrote:
>Hi Matthias!
>
>Thanks for taking another look.
>
...
>> 
>> This should probably check that len == sizeof(RelationData), and then
>> just use the AllocRelationData() macro used everywhere else.
>
>Changed to use AllocRelationData(). A few lines above there's already
>
>if (len != sizeof(RelationData))
>	goto read_failed;
>
>Hence, no need for an assertion.
>
>> 0003: I agree with Alvaro's comment; if moving ForeignKeyCacheInfo to
>> its own header would also solve the issue then that's preferred.
>
>I'm waiting for Alvaro's and Peter's reply before changing that part.
>
>Any thoughts from your side regarding moving ForeignKeyCacheInfo into
>its own header vs building support for anonymous structs/unions in
>gen_node_support.pl?
...
>* The lmgr.h include is unnecessary. Removed.
>* The miscadmin.h include is necessary for MyDatabaseId.
>
>
>I've also created a commitfest entry, see [1].
>
>--
>David Geier

Hi,
Thanks for your patches.
There is still a crash in the v5 patch series, similar to the predicate crash that Haibo already mentioned.
Minimal reproduction steps:

CREATE TABLE t(a int primary key, b text);
CREATE INDEX t_b_idx ON t(b);

SELECT pg_relation_is_updatable('t_b_idx'::regclass, false);
-- server closed the connection unexpectedly

SELECT pg_column_is_updatable('t_b_idx'::regclass, 1::int2, false);
-- server closed the connection unexpectedly

Please take this into consideration.


Best regards,
Yilin Zhang

Re: Reducing relcache memory usage 2: shrink sizeof(RelationData)

От:
David Geier <geidav.pg@gmail.com>
Дата:
Вложения:
Hi Yilin,

> There is still a crash in the v5 patch series, similar to the predicate
> crash that Haibo already mentioned.
> Minimal reproduction steps:
> 
> CREATE TABLE t(a int primary key, b text);
> CREATE INDEX t_b_idx ON t(b);
> 
> SELECT pg_relation_is_updatable('t_b_idx'::regclass, false);
> -- server closed the connection unexpectedly
> 
> SELECT pg_column_is_updatable('t_b_idx'::regclass, 1::int2, false);
> -- server closed the connection unexpectedly
> 
> Please take this into consideration.
Thanks for testing the patch!

The problem was that relation_is_updatable() accessed rel->rd_rules
without checking that the relcache entry is actually for a relation and
not for an index. Bailing for indexes fixes the crash:

/* Indexes are not updatable */
if (RelationIsIndex(rel))
{
	relation_close(rel, AccessShareLock);
	return 0;
}

Attached is patch set v6 with the fix.

--
David Geier
FAQ