Memory leak in pg_stat_statements when qtext file contains invalid encoding - Mailing list pgsql-bugs

From Gaurav Singh
Subject Memory leak in pg_stat_statements when qtext file contains invalid encoding
Date
Msg-id CAEcQ1bYR9s4eQLFDjzzJHU8fj-MTbmRpW-9J-r2gsCn+HEsynw@mail.gmail.com
Whole thread Raw
Responses Re: Memory leak in pg_stat_statements when qtext file contains invalid encoding
List pgsql-bugs
I've found a memory leak in contrib/pg_stat_statements that occurs when the query text file (pgss_query_texts.stat) contains an invalid byte sequence. Each call to pg_stat_statements leaks the entire malloc'd file buffer and fails to release the LWLock.PostgreSQL version: Discovered against PG 15.12, verified also present in PG 18 (HEAD as of 2026-03-26). The code path is unchanged between versions.Platform: macOS 15.7.3 (aarch64).Although the cause of corruption inpgss_query_texts.statis unknownwe have seen this twice. Similar cases were found online.Eg:ERROR: invalid byte sequence for encoding "UTF8": 0x00 in pg_stat_statements - Database Administrators Stack Exchange.How to reproduce:
Output I got:RSS grows linearly with each failing query. With a ~600 KB qtext file and 2000 iterations, the backend's RSS grew by approximately 1.2 GB:
Leak per error is approximately equal to the qtext file size (~600 KB), confirming the file buffer is leaked on every call.
Output I expected:RSS should remain approximately constant. Each call should either succeed or fail cleanly without leaking memory. The LWLock should always be released.Root cause:
  • In pg_stat_statements_internal(), the function acquires pgss->lock and may malloc a file buffer via qtext_load_file().
  • Later, pg_any_to_server() is called inside the hash iteration loop.
  • If the qtext file contains an invalid encoding, pg_any_to_server calls ereport(ERROR) which longjmps out of the function.
  • The cleanup code at the bottom of the function is never reached
On every subsequent call, the malloc'd buffer (the entire file contents) is leaked, and the LWLock release is also skipped.Proposed fix:Wrap the hash iteration loop in PG_TRY/PG_FINALLY so that the lock release and buffer free happen even on the error path:

Gaurav Singh

pgsql-bugs by date:

Previous
From: Vishal Prasanna
Date:
Subject: RE: [BUG] Assert failure in ReorderBufferReturnTXN during logical decoding due to leaked specinsert change
Next
From: Gaurav Singh
Date:
Subject: Memory leak in pg_stat_statements when query text file contains invalid encoding