Memory leak in pg_stat_statements when query text file contains invalid encoding
Memory leak in pg_stat_statements when query text file contains invalid encoding
От:
Gaurav Singh <gaurav.singh@yugabyte.com>
Дата:
I have 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 held LWLock.PostgreSQL version: Discovered against PostgreSQL 15.12, verified also present in PG18(installed via homebrew). The affected code path in pg_stat_statements_internal() is unchanged between these versions.Platform: macOS 15.7.3 (aarch64).Steps to reproduce:
- Enable pg_stat_statements and populate it with a large number of structurally unique queries (I used 2000 unique CTE-based queries with identifiers padded to 63 characters each). This creates a query text file of approximately 600 KB.
- Corrupt the query text file by injecting a null byte at an arbitrary offset (I used byte offset 500). This can be done with: printf '\x00' | dd of=<data_directory>/pg_stat_tmp/pgss_query_texts.stat bs=1 seek=500 count=1 conv=notrunc
- Verify that querying pg_stat_statements now returns: ERROR: invalid byte sequence for encoding "UTF8": 0x00
- In a single psql session, repeatedly query pg_stat_statements (I ran SELECT count() FROM pg_stat_statements 2000 times) while monitoring the backend process RSS using ps -o rss= -p <backend_pid>.
- 0 seconds: 67 MB
- 8 seconds: 153 MB
- 20 seconds: 370 MB
- 38 seconds: 739 MB
- 50 seconds: 1028 MB
- 54 seconds: 1251 MB