Re: [PATCH] Add NESTED_STATEMENTS option to EXPLAIN

From: Mohamed ALi <moali(dot)pg(at)gmail(dot)com>
To: Zsolt Parragi <zsolt(dot)parragi(at)percona(dot)com>
Cc: pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: Re: [PATCH] Add NESTED_STATEMENTS option to EXPLAIN
Date: 2026-05-17 16:45:40
Message-ID: CAGnOmWqNg0e4JDnti_B5PTfbpbFR18KkmczmrDKVXw-OMirbNg@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

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

Attachment Content-Type Size
test_output_all_v2.txt text/plain 63.6 KB
v2-0001-Add-NESTED_STATEMENTS-option-to-EXPLAIN.patch application/octet-stream 20.8 KB
comprehensive_nested_statements_test_v2.sql application/octet-stream 36.2 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Sami Imseih 2026-05-17 17:37:23 Re: Improve pg_stat_statements scalability
Previous Message Alexander Lakhin 2026-05-17 15:00:00 035_standby_logical_decoding might fail due to FATAL message lost inside libpq