Re: [PATCH] Add NESTED_STATEMENTS option to EXPLAIN
Mohamed ALi <moali.pg@gmail.com>
From: Mohamed ALi <moali.pg@gmail.com>
To: Zsolt Parragi <zsolt.parragi@percona.com>
Cc: pgsql-hackers@lists.postgresql.org
Date: 2026-05-17T16:45:40Z
Lists: pgsql-hackers
Attachments
- test_output_all_v2.txt (text/plain)
- v2-0001-Add-NESTED_STATEMENTS-option-to-EXPLAIN.patch (application/octet-stream) patch v2-0001
- comprehensive_nested_statements_test_v2.sql (application/octet-stream)
Hi Zsolt,
Attached is v2 of the patch which fixes all three issues:
1. Error during EXPLAIN (e.g., division by zero):
- Root cause: hooks were not removed on the error path.
- Fix: wrapped EXPLAIN execution in PG_TRY/PG_FINALLY to guarantee
hook removal and cleanup regardless of errors.
2. Nested EXPLAIN crash:
- Root cause: static globals overwritten by the inner EXPLAIN.
- Fix: added a reentrancy guard — if nested tracking is already
active, the inner EXPLAIN skips hook installation entirely.
3. Memory leak (TopMemoryContext):
- Root cause: allocating captured plans in TopMemoryContext with no
cleanup on error.
- Fix: replaced TopMemoryContext with a dedicated memory context
("Nested EXPLAIN plans") that is created at the start and deleted
in PG_FINALLY — freeing everything at once on both success and
error paths.
The v2 patch passes the regression test suite (245 subtests, 0 failures)
and a comprehensive 19-test script covering the original functionality
plus the three bug scenarios, memory leak verification, and a stress
test with 50 nested statements.
Attachments:
1- v2-0001-Add-NESTED_STATEMENTS-option-to-EXPLAIN.patch
2- comprehensive_nested_statements_test_v2.sql
3- test_output_all_v2.txt
Mohamed Ali
AWS RDS