pgsql: pg_stat_statements: Fix toplevel tracking across nesting levels

From: Michael Paquier <michael(at)paquier(dot)xyz>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: pg_stat_statements: Fix toplevel tracking across nesting levels
Date: 2026-10-27 06:27:58
Message-ID: E1xLaf8-00000000wON-2CZR@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

pg_stat_statements: Fix toplevel tracking across nesting levels

pg_stat_statements decides whether a query is toplevel from the
nesting level at the time each hook runs. A QueryDesc can outlive the
level it started at. For example, a cursor's query starts at level 1,
inside DECLARE, but if the cursor is closed implicitly at COMMIT,
ExecutorEnd runs at level 0. The entry created for the query at parse
analysis has toplevel = false, so ExecutorEnd misses it and stores a
duplicate with the raw query text and toplevel = true.

The same happens with track = top when another extension such as
auto_explain requests query instrumentation. ExecutorEnd stores the
query even though ExecutorStart did not track it.

PGSS is upgraded to save the nesting level in the extension state of the
QueryDesc when ExecutorStart() tracks a query. ExecutorEnd() then uses
it in place of the current level and skips the query if no state was
saved.

For now, only the nesting level is tracked in the private extension
state attached to QueryDesc by PGSS. auto_explain is not touched
either. All these pieces are left as future improvements.

No backpatch is done, due to the ABI changes required in QueryDesc.
This relies on the work done previously in e5d5d1ad1e3a.

Reported-by: Gaurav Singh <gaurav(dot)singh(at)yugabyte(dot)com>
Author: Sami Imseih <samimseih(at)gmail(dot)com>
Author: Michael Paquier <michael(at)paquier(dot)xyz>
Discussion: https://postgr.es/m/CAEcQ1bZrgwKsauC=03otebkLk77Zc_hYNjhTP3OUdpXs++u+BA@mail.gmail.com
Discussion: https://postgr.es/m/CAA5RZ0v281uwSudcFrY8BymSRDM4J6PAHfzqg_9R+i7zWbTb2A@mail.gmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/23bf901fa5306b245e23ace52e5a6777ea08bed6

Modified Files
--------------
.../pg_stat_statements/expected/level_tracking.out | 25 +++++++++++++
contrib/pg_stat_statements/pg_stat_statements.c | 43 +++++++++++++++++++++-
contrib/pg_stat_statements/sql/level_tracking.sql | 11 ++++++
src/tools/pgindent/typedefs.list | 1 +
4 files changed, 78 insertions(+), 2 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message David Rowley 2026-10-27 06:46:35 pgsql: Disallow NOT NULL NO INHERIT constraints on partitioned tables
Previous Message Michael Paquier 2026-10-27 06:09:45 pgsql: Add custom extension states to QueryDesc