I'm currently processing various internal reports about slow
pg_upgrades. One of the points on the list is the
get_rel_infos_query() is sometimes slow. The report said the query
took 64.32 seconds for 100k tables. I was unable to get the EXPLAIN
output.

I was given the attached 03_get_rel_infos_100k_tables.sql script,
which I suspect was AI-generated from a "reverse engineer this issue"
type prompt as the script manually hacks reltuples and relpages to 1
for pg_class, pg_index, and pg_namespace. I see no reason why those
would ever be that low, but I understand that the stats can be
outdated because autovacuum doesn't run on the target instance during
the upgrade.

I was told that SET enable_nestloop=0; fixed the problem for them, but
don't know if that was a poorly chosen parameterized nested loop, or a
non-parameterized one. Playing around with the query, I did see a
Nested Loop -> Memoize plan gets chosen sometimes with 0 cache hits,
but I found it to be barely any faster when I disabled nested loops.

I took a semi-blind attempt at trying to make this better by rewriting
the query. The attached orig.sql is the current query, david1.sql and
david2.sql are my own rewrites. david2.sql is faster under normal
circumstances, but david1.sql is not far behind. When I manually
adjust reltuples and relpages to 1, david1.sql performs much better
than everything else.

Claude also had a go. Unremarkable, but attached.

With the 100k tables created, I get this:

$ pgbench -n -f orig.sql -T 30 postgres | grep latency
latency average = 1316.328 ms
$ pgbench -n -f david1.sql -T 30 postgres | grep latency
latency average = 1151.022 ms
$ pgbench -n -f david2.sql -T 30 postgres | grep latency
latency average = 972.317 ms
$ pgbench -n -f claude.sql -T 30 postgres | grep latency
latency average = 1248.452 ms
$ psql postgres
postgres=# SET allow_system_table_mods = on;
  UPDATE pg_class
     SET relpages = 1, reltuples = 1
   WHERE oid IN ('pg_class'::regclass, 'pg_index'::regclass,
'pg_namespace'::regclass);
SET
UPDATE 3
postgres=# \q
$ pgbench -n -f orig.sql -T 30 postgres | grep latency
latency average = 41942.072 ms
$ pgbench -n -f david1.sql -T 30 postgres | grep latency
latency average = 2129.235 ms
$ pgbench -n -f david2.sql -T 30 postgres | grep latency
latency average = 37895.051 ms
$ pgbench -n -f claude.sql -T 30 postgres | grep latency
latency average = 42849.882 ms

I was thinking I'd just patchify the david1.sql and put that in
get_rel_infos_query().

Anyone have any different ideas or objections?

David

Attachment: 03_get_rel_infos_100k_tables.sql
Description: Binary data

Attachment: orig.sql
Description: Binary data

Attachment: david1.sql
Description: Binary data

Attachment: david2.sql
Description: Binary data

Attachment: claude.sql
Description: Binary data

Reply via email to