Files
pg_stat_monitor/regression/sql/top_query.sql
Zsolt Parragi 5f8b716ef6 PG-2005: Do not keep unnecessary entries in the query stack
PGSM support nested query tracking, and it has to track the current SQL
call stack for this feature to work. But it incorrectly tracked all
previous queries executed within the current top level statement instead
o only the currently active queries.

This was easily visible for example with a FOR LOOP in a user function,
but could be also reproduced in many other ways.

There's also an issue that the related assertion, that compares the
length of the list with the max_stack_depth is incorrect. The stack
depth limits the size of the postgres stack for the C code, not the
number of nested SQL statements.

For now this commit leaves these assertions as-is, as while they are not
technically correct, these at least provide some kind of check on the
nesting depth. Maybe it would make sense to remove them in the future,
but for now, it could be a useful sanity check for testing the actual
fix - we shouldn't hit this assertion anymore with the changes in this
commit.

As for the actual fix, with the changes in this commit pgsm removes list
entries after we finished working on them. At that point we persisted
everything we needed already into the shared memory, and no longer need
the entries in the process local list. This is also true for the
duplicated query string, which if needed was already copied to the
shared memory.
2025-11-12 11:15:37 +01:00

38 lines
760 B
PL/PgSQL

CREATE EXTENSION pg_stat_monitor;
SET pg_stat_monitor.pgsm_track='all';
SELECT pg_stat_monitor_reset();
CREATE OR REPLACE FUNCTION add(int, int) RETURNS INTEGER AS
$$
BEGIN
return (select $1 + $2);
END; $$ language plpgsql;
CREATE OR REPLACE FUNCTION add2(int, int) RETURNS INTEGER AS
$$
BEGIN
return add($1,$2);
END;
$$ language plpgsql;
SELECT add2(1,2);
SELECT query, top_query FROM pg_stat_monitor ORDER BY query COLLATE "C";
-- make sure that we handle nested queries correctly
BEGIN;
DO $$
DECLARE
i int;
BEGIN
-- default stack limit is 2000kB, 50000 is much larger than that
FOR i IN 1..50000 LOOP
EXECUTE format('SELECT %s', i);
END LOOP;
END;
$$;
COMMIT;
SELECT pg_stat_monitor_reset();
DROP EXTENSION pg_stat_monitor;