Fix memory leak in pgoutput with relation attribute map
authorMichael Paquier <[email protected]>
Mon, 30 Dec 2024 04:33:59 +0000 (13:33 +0900)
committerMichael Paquier <[email protected]>
Mon, 30 Dec 2024 04:33:59 +0000 (13:33 +0900)
pgoutput caches the attribute map of a relation, that is free()'d only
when validating a RelationSyncEntry.  However, this code path is not
taken when calling any of the SQL functions able to do some logical
decoding, like pg_logical_slot_{get,peek}_changes(), leaking some memory
into CacheMemoryContext on repeated calls.

To address this, a relation's attribute map is allocated in
PGOutputData's cachectx, free()'d at the end of the execution of these
SQL functions when logical decoding ends.  This is available down to 15.
v13 and v14 have a similar leak, which will be dealt with later.

Reported-by: Masahiko Sawada
Author: Vignesh C
Reviewed-by: Hou Zhijie
Discussion: https://postgr.es/m/CAD21AoDkAhQVSukOfH3_reuF-j4EU0-HxMqU3dU+bSTxsqT14Q@mail.gmail.com
Discussion: https://postgr.es/m/CALDaNm1hewNAsZ_e6FF52a=9drmkRJxtEPrzCB6-9mkJyeBBqA@mail.gmail.com
Backpatch-through: 15

src/backend/replication/pgoutput/pgoutput.c

index c9ae239aa4ecc98db82533cf0172fb94add44d34..32b74bb47527f9af0640a17612a5de19dff15dca 100644 (file)
@@ -1179,8 +1179,8 @@ init_tuple_slot(PGOutputData *data, Relation relation,
        TupleDesc   indesc = RelationGetDescr(relation);
        TupleDesc   outdesc = RelationGetDescr(ancestor);
 
-       /* Map must live as long as the session does. */
-       oldctx = MemoryContextSwitchTo(CacheMemoryContext);
+       /* Map must live as long as the logical decoding context. */
+       oldctx = MemoryContextSwitchTo(data->cachectx);
 
        entry->attrmap = build_attrmap_by_name_if_req(indesc, outdesc, false);