Re: Reducing relcache memory usage: deduping index shapes

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

Re: Reducing relcache memory usage: deduping index shapes

От:
"Yilin Zhang" <jiezhilove@126.com>
Дата:
At 2026-09-08 17:55:36, "Matthias van de Meent" <boekewurm+postgres@gmail.com> wrote:
>Attached is v2 of the patchset. Changelist below:
>
>0001/0002: Unchanged.
>
>0003 (Deduplication):
>* New memory context "Relation shape cache" to hold all shape-related
>allocations and contexts,
>    This is a child context under CacheMemoryContext
>* Memory context per "relation shape" in the RelShapeHash
>    This allows faster freeing of all associated data
>* Optimized default shape entry data allocations per shape
>    The minimum is now down to 2 allocations, from >3. This is
>primarily useful once Proxy contexts are used;  Key data is still
>bulk-allocated.
>* Some varlena macro-related fixes.
>    Some SIZE/SIZE_EXHDR confusion and related issues, identified by
>the sanitizer CF builds.
>
>0004 (Proxy context):
>* Consistency checks have been adjusted, and sentinel checks have been
>introduced.
>* Code has been updated with aset as template for naming and flow
>  This should clean up David's comments.
>
>Name change from Proxy to anything else gets a 0-vote from me: I'd
>like to avoid the churn, but if people have strong feelings about it
>I'll go through the motions.
>
>
>0005 (Apply proxy):
>* Added Proxy to the new per-"index shape" contexts.
>
>
>Question for the crowd:  Most memory contexts often get a text
>identifier which describes their contents in more detail when we have
>many of the same name.  "index shape" contexts don't have a simple
>natural identifier.  Whilst they do have the shape key, formatting
>that into a name would be a bit of effort (and quite a bit of effort
>if we want to capture the whole key), and we'd spend more bytes per
>index shape.  Do we want/need this identifier even with the increase
>in memory usage?
>
>
>Kind regards,
>
>Matthias van de Meent


Hi,
Thanks for your patches.
I have some review comments regarding the code below:
v2-0003-Deduplicate-some-index-attributes-in-the-relcache.patch
@@ -2461,6 +2656,28 @@ RelationDestroyRelation(Relation relation, bool remember_tupdesc)
/* break mutual link with stats entry */
pgstat_unlink_relation(relation);

+ if (relation->rd_isvalid && relation->rd_indam)
+ {
+ Datum indclassDatum;
+ bool isnull;
+ oidvector *indclass;
+
+ Assert(relation->rd_indextuple != NULL);
+
+ indclassDatum = fastgetattr(relation->rd_indextuple,
+ Anum_pg_index_indclass,
+ GetPgIndexDescriptor(),
+ &isnull);
+ Assert(!isnull);
+
+ indclass = (oidvector *) DatumGetPointer(indclassDatum);
+
+ IndexSupportDeregister(indclass,
+ IndexRelationGetNumberOfKeyAttributes(relation),
+ relation->rd_indam->amsupport,
+ relation->rd_opcoptions);
+ }
relcache.c:
static void
RelationClearRelation(Relation relation)
{
Assert(RelationHasReferenceCountZero(relation));
Assert(!relation->rd_isnailed);

/*
* Relations created in the same transaction must never be removed, see
* RelationFlushRelation.
*/
Assert(relation->rd_createSubid == InvalidSubTransactionId);
Assert(relation->rd_firstRelfilelocatorSubid == InvalidSubTransactionId);
Assert(relation->rd_droppedSubid == InvalidSubTransactionId);

/* first mark it as invalid */
RelationInvalidateRelation(relation);

/* Remove it from the hash table */
RelationCacheDelete(relation);

/* And release storage */
RelationDestroyRelation(relation, false);
}

The IndexSupportDeregister() cleanup inside RelationDestroyRelation() cannot be executed,
since relation->rd_isvalid = false has already been set in RelationInvalidateRelation().
Entries in RelShapeCache cannot be removed.
Is this inconsistent with your design?
Run with the SQL below:
CREATE TABLE m (a int);
INSERT INTO m SELECT g FROM generate_series(1,500) g;
CREATE INDEX mi ON m USING brin (a int4_bloom_ops (false_positive_rate = 0.00100000)); DROP INDEX mi;
CREATE INDEX mi ON m USING brin (a int4_bloom_ops (false_positive_rate = 0.00100100)); DROP INDEX mi;
CREATE INDEX mi ON m USING brin (a int4_bloom_ops (false_positive_rate = 0.00100200)); DROP INDEX mi;
CREATE INDEX mi ON m USING brin (a int4_bloom_ops (false_positive_rate = 0.00100300)); DROP INDEX mi;
...
When constructed in this way, the number of potential RelShapeCache entries may grow far larger than expected.



Best regards,
Yilin Zhang


Re: Reducing relcache memory usage: deduping index shapes

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
Вложения:
On Thu, 17 Sept 2026 at 11:56, Yilin Zhang  wrote:
>
> At 2026-09-08 17:55:36, "Matthias van de Meent"  wrote:
>
> >Attached is v2 of the patchset. Changelist below:
>
> Hi,
> Thanks for your patches.
> I have some review comments regarding the code below:

Thank you for the review!

[...]
> The IndexSupportDeregister() cleanup inside RelationDestroyRelation() cannot be executed,
> since relation->rd_isvalid = false has already been set in RelationInvalidateRelation().
> Entries in RelShapeCache cannot be removed.
> Is this inconsistent with your design?

Yes, that's a bug.

Attached is version 3, which fixes that bug, does a little more
cleanup, and moves some non-critical optimizations into their own
patch.

Changelist:

0001: Unchanged
0002: Some cosmetic changes, but nothing material
0003:
* Cleaned up a compilerwarnings complaint
* Moved some changes that do bulk allocations in shapectx to 0006
* cosmetic fixes
0004/0005:
* Unchanged
0006:
* Some small changes to IndexSupportInitialize to bulk-allocate into
the Proxy context.
    This saves 3x sizeof(ProxyChunk) memory. Not huge, but every bit
counts when catalogs get to huge sizes.
    These were previously added in v2's 0003.

Kind regards,

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

Re: Reducing relcache memory usage: deduping index shapes

От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Wed, 7 Oct 2026 at 11:01, Matthias van de Meent
 wrote:
> 0004/0005:
> * Unchanged

I had a conversation with Andres about the Proxy context. He mentioned
that he gave it that name when he was experimenting with making it
work by putting the allocation in another memory context. I mentioned
using the "Direct" name, and he suggested "System", which I agreed was
a good name. We then agreed that we shouldn't call the .c file
system.c. systemcxt.c is likely ok.

Another review of 0004:

1. You could probably get rid of the allocSize variable in ProxyContextCreate()

2. struct ProxyBlock could use a few comments.

3. README:

* proxy.c (ProxyContext) is best suited for those use cases that require
  long-lived allocations, with minimal allocation traffic, and generally
  very few allocations; such as relcache's 'index info' contexts.

It might be worth mentioning how it works here as that'll help explain
to the reader why it's best suited for those cases. Maybe something
like:

* systemcxt.c (SystemContext) has no concept of grouping several allocations
* into blocks like many of the other allocators do.  Each palloc() results in
* a malloc(), and each pfree() results in a free(), therefore, this isn't
* suitable for cases that require many allocations.  The most suitable use
* cases are for contexts that require very few and long-lived allocations.
* The context header is also small, so this can be suitable when a large
* number of contexts are required.

Because we're getting so many context types now, I feel it's more
important than ever to have a central place that gives enough
information about each to allow someone to select the one that suits
their needs best.

4. The following existing text claims there are "three" other
allocators, but the patch makes that false since it introduces another
one:

aset.c (AllocSetContext) is our default general-purpose allocator.  Three other
allocator types also exist which are special-purpose:

5. In ProxyRealloc(), can you clarify the following comment to mention
"When the size is being increased, randomize the new portion".

 /* randomize the newly allocated memory */
#ifdef RANDOMIZE_ALLOCATED_MEMORY
if (block->sz < blksize)
randomize_mem(((char *) block) + block->sz, blksize - block->sz);
#endif

I just didn't find the current comment that informative since the
blocks are being swapped around, it takes a bit of study to see what's
meant to be going on there.

6. ProxyReset(). The following Assert() should be using
PROXY_CONTEXTSIZE as that's what ProxyContextCreate() set it to.  It
just so happens to work because the size of the struct is already a
multiple of 8 bytes. Perhaps there are some systems where it won't
work.

Assert(ctx->header.mem_allocated == sizeof(ProxyContext));

David


Re: Reducing relcache memory usage: deduping index shapes

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
Вложения:
On Mon, 12 Oct 2026 at 13:35, David Rowley  wrote:
>
> On Wed, 7 Oct 2026 at 11:01, Matthias van de Meent
>  wrote:
> > 0004/0005:
> > * Unchanged
>
> I had a conversation with Andres about the Proxy context. He mentioned
> that he gave it that name when he was experimenting with making it
> work by putting the allocation in another memory context. I mentioned
> using the "Direct" name, and he suggested "System", which I agreed was
> a good name. We then agreed that we shouldn't call the .c file
> system.c. systemcxt.c is likely ok.
Thanks for the review.

I've renamed the context type and file names accordingly.

> Another review of 0004:
>
> 1. You could probably get rid of the allocSize variable in ProxyContextCreate()

Done.

> 2. struct ProxyBlock could use a few comments.

Done.

> 3. README:
[...]
> It might be worth mentioning how it works here as that'll help explain
> to the reader why it's best suited for those cases. Maybe something
> like:
[...]
> Because we're getting so many context types now, I feel it's more
> important than ever to have a central place that gives enough
> information about each to allow someone to select the one that suits
> their needs best.

Adjusted, WDYT?

> 4. The following existing text claims there are "three" other
> allocators, but the patch makes that false since it introduces another
> one:

Adjusted; "three" has been replaced with "several other"

> 5. In ProxyRealloc(), can you clarify the following comment to mention
> "When the size is being increased, randomize the new portion".

Adjusted.

> 6. ProxyReset(). The following Assert() should be using
> PROXY_CONTEXTSIZE as that's what ProxyContextCreate() set it to.  It
> just so happens to work because the size of the struct is already a
> multiple of 8 bytes. Perhaps there are some systems where it won't
> work.

Done.

-----

Attached is v4, which has the following changes:

0001-0002: Unmodified

0003:
* Renamed "Proxy" memory context type to System,
* various other changes to align with David's review
0004/0005: Adjust for Proxy -> System /SystemCxt rename

Kind regards,

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

Re: Reducing relcache memory usage: deduping index shapes

От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Вложения:
On Tue, 13 Oct 2026 at 07:22, Matthias van de Meent
 wrote:
> 0004/0005: Adjust for Proxy -> System /SystemCxt rename

Here's a delta patch with various fixups for v4-0003

* Fixed inconsistent references to systemcxt.c file in README (In some
places this was spelt systemctx.c)
* Ended up renaming the file to systemctx.c (we're not very consistent
in general between cxt and ctx. MemoryContextMethodID enum uses ctx,
so I followed that example)
* Changed function names from SystemCxt* to SystemContext*. The struct
was called SystemContext. I felt the need to have consistency.
* Added missing accounting of mem_allocated in SystemContextRealloc().
* size_t is unsigned, so the format specifier for printf is %zu, not %zd
* Fixed bug in SystemContextRealloc() which would leak the old block
on realloc() failure. The dlist_delete_from_thoroughly() can't be
moved to after the realloc() as the dlist_member_check() can't access
the old block. The best I could come up with is just doing
dlist_push_tail() on the old block on failed realloc().  aset.c
doesn't have this issue as it doesn't use dlist and adjusts the linked
list pointers manually.
* Updated outdated references to the old "Proxy" name, one in comments
and some in typedefs.list
* Fixed incorrect direct use of sizeof(SystemContext) in
SystemContextCheck() (Similar to prior mistake in ProxyReset()).
* Renamed ExternalChunkGetBlock() macro to ChunkGetBlock().  Old name
would lead you to believe some chunks were not external.
* Added BlockGetChunk() and updated 3 places doing manual memory
address calculations.
* Fixed weird calculation of parameter in sentinel_ok() call. (I'm
aware of aset.c, slab.c and generation.c do this too, but it's still
weird)
* Added missing valgrind macros in SystemContextCheck(). Valgrind was
warning about accessing the MemoryChunk fields during the check.
* Adjusted README to mention the large per-chunk header being one
reason why cases that require many allocations aren't a good fit.
* Various comment adjustments.

I spent some time running this under Valgrind, accessing the memory of
a chunk made by SystemContextAlloc() and another after doing
SystemContextRealloc() on a chunk. Valgrind is correctly giving me
warnings when I access the byte before the pointer and when I access
the sentinel byte manually. I don't see any warnings when I access
bytes that are valid to access.

I'm not aware of any other issues.

David

Re: Reducing relcache memory usage: deduping index shapes

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
Вложения:
On Wed, 14 Oct 2026 at 09:28, David Rowley  wrote:
>
> On Tue, 13 Oct 2026 at 07:22, Matthias van de Meent
>  wrote:
> > 0004/0005: Adjust for Proxy -> System /SystemCxt rename
>
> Here's a delta patch with various fixups for v4-0003

Thanks, attached is the adjusted patch series as v5, now again
including "rel.h: const-ify opclass-related fields of RelationData",
which I'd accidentally left out in v4.  This should make CFBot happy
again.

[lots of review changes]
> * Various comment adjustments.

Applied, thanks!

> I spent some time running this under Valgrind, accessing the memory of
> a chunk made by SystemContextAlloc() and another after doing
> SystemContextRealloc() on a chunk. Valgrind is correctly giving me
> warnings when I access the byte before the pointer and when I access
> the sentinel byte manually. I don't see any warnings when I access
> bytes that are valid to access.
>
> I'm not aware of any other issues.

Thanks for the review!


Kind regards,

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

Re: Reducing relcache memory usage: deduping index shapes

От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Wed, 14 Oct 2026 at 20:27, David Rowley  wrote:
> * Fixed bug in SystemContextRealloc() which would leak the old block
> on realloc() failure. The dlist_delete_from_thoroughly() can't be
> moved to after the realloc() as the dlist_member_check() can't access
> the old block. The best I could come up with is just doing
> dlist_push_tail() on the old block on failed realloc().  aset.c
> doesn't have this issue as it doesn't use dlist and adjusts the linked
> list pointers manually.

I'm a little disheartened here as I see you've gone and done exactly
what I said not to do. Maybe you didn't read the above text properly,
or maybe you didn't understand the issue I was talking about. If it's
the latter, then let me explain in more detail:

If you build with ILIST_DEBUG, dlist_delete_from_thoroughly() uses
dlist_member_check() to verify that the given node is actually in the
given list. This requires walking the linked list in a forward
direction, and to walk a linked list, we must access the "next"
pointer, which is stored inside the node's memory itself.  Since this
memory has likely just been free'd by realloc(), it's not valid to
walk the list at this point. Effectively, dlist_member_check()'s
cur->next could segfault.

If you think I'm wrong about this, then please explain here so we can review.

If you didn't like my change, then an alternative way to work around
the accessing of the free'd memory would be to:

-       dlist_delete_from_thoroughly(&ctx->allocations, &new_block->node);
+       dlist_delete_thoroughly(&new_block->node);

It's slightly less robust as we lose the validation that the node is
in the list.

David


Re: Reducing relcache memory usage: deduping index shapes

От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Вложения:
On Thu, 15 Oct 2026 at 12:00, David Rowley  wrote:
> I'm a little disheartened here as I see you've gone and done exactly
> what I said not to do. Maybe you didn't read the above text properly,
> or maybe you didn't understand the issue I was talking about. If it's
> the latter, then let me explain in more detail:

Please disregard the disheartened part as I just discovered I sent the
wrong patch :-(

Attached is what I meant to send. It applies to v4-0003. Now thinking
it might be less quirky to go with the
s/dlist_delete_from_thoroughly/dlist_delete_thoroughly/ fix.

David
FAQ