postgres.git / summary / log / commit / refs

commit    4c271dc216065c8e6c99ba3097e831e6ef6cd9e1
Author:   Fujii Masao <fujii@postgresql.org>
Date:     Wed Nov 04 02:16:44 2026 +0000
First released in: 15.20, 16.16, 17.12, 18.7, 19.0

    Fix memory leaks when freeing WAL readers
    
    Commit 3f1ce97346 introduced a circular buffer for decoded WAL records,
    with separate allocations for records that do not fit in the buffer.
    However, XLogReaderFree() did not release separately allocated
    records remaining in the decode queue. In particular, the last record
    returned by XLogReadRecord() remains queued until released, so freeing
    the reader could leak that record.
    
    For many callers, the leaked memory is reclaimed when the containing
    memory context is reset or deleted. However, it can accumulate in
    long-lived contexts. For example, when checkpointing prepared
    transactions, XlogReadTwoPhaseData() creates a WAL reader, reads the
    PREPARE record, and frees the reader. Large PREPARE records can
    therefore leave allocations in checkpointer_context, which is not
    reset during normal operation. These allocations accumulate until
    an error resets the context or the checkpointer exits.
    
    Fix this by calling ResetDecoder() in XLogReaderFree() to release all
    separately allocated records in the queue. Do this before freeing the
    decode buffer, since the queue can also contain records stored in that
    buffer.
    
    Backpatch to v15, where the circular WAL decoding buffer was
    introduced.
    
    Author: Tomás Senart <ts@perfloop.ai>
    Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
    Discussion: https://postgr.es/m/CAEEBa3Uai8TGPd6P5SX_fzbu3KHMwSvu9WuqA8JPSPQ1RJR8fQ@mail.gmail.com
    Backpatch-through: 15


src/backend/access/transam/xlogreader.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/backend/access/transam/xlogreader.c b/src/backend/access/transam/xlogreader.c index 0cb719a67d6..452fdc06c7a 100644 --- a/src/backend/access/transam/xlogreader.c +++ b/src/backend/access/transam/xlogreader.c @@ -165,6 +165,9 @@ XLogReaderFree(XLogReaderState *state) if (state->seg.ws_file != -1) state->routine.segment_close(state); + /* Release queued records before freeing the decode buffer */ + ResetDecoder(state); + if (state->decode_buffer && state->free_decode_buffer) pfree(state->decode_buffer); @@ -1603,8 +1606,7 @@ WALRead(XLogReaderState *state, */ /* - * Private function to reset the state, forgetting all decoded records, if we - * are asked to move to a new read position. + * Forget all decoded records, freeing any oversized ones. */ static void ResetDecoder(XLogReaderState *state) [parent: 083d60e34ae0]