Temp schema drop leaves an inconsistent state behind

Started by Marko Grujic2 months ago8 messageshackers
Jump to latest
#1Marko Grujic
marko.grujic@enterprisedb.com

Hi, reporting two bugs I ran into, one breaking pg_dump and the other
leading to a segfault.

The setup (and the first bug) involves temp schema being dropped

postgres=# select version();
version
------------------------------------------------------------------------
PostgreSQL 20devel on aarch64-darwin, compiled by clang-16.0.0, 64-bit
(1 row)

postgres=# create temp table t1(a int);
CREATE TABLE
postgres=# \d t1;
Table "pg_temp_0.t1"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
a | integer | | |

postgres=# drop schema pg_temp_0 cascade;
NOTICE: drop cascades to table t1
DROP SCHEMA
postgres=# create temp table t2(a int);
CREATE TABLE
postgres=# \d t2;
Table ".t2"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
a | integer | | |
postgres=# select pg_my_temp_schema();
pg_my_temp_schema
-------------------
16409
(1 row)

Looke innocent enough, only a cosmetic issue where the temp schema isn't
shown in table display. The table itself seems to work just fine afterwards
(writes and reads)

postgres=# insert into t2 values (1), (2), (3);
INSERT 0 3
postgres=# select * from t2;
a
---
1
2
3
(3 rows)

However, trying to pg_dump that DB leads to an error

$ pg_dump -h 127.0.0.1 -p 7999 -d postgres
pg_dump: error: schema with OID 16409 does not exist

The namespace catalog entry is now gone because of the drop

postgres=# select 1 from pg_namespace where oid = 16409;
?column?
----------
(0 rows)

The reason it wasn't re-created is because the internal static variable
(myTempNamespace) is left holding the 16409 value internally.

The second bug, while independent of the first one in general, leans on the
same setup, and exposes an existing vulnerability in the pg_identify_object
function

postgres=# select oid from pg_class where relname = 't2' and relnamespace =
16409;
oid
-------
16414
(1 row)

postgres=# select pg_identify_object('pg_class'::regclass, 16414, 0);
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.

The backend logs:
LOG: client backend (PID 8145) was terminated by signal 11: Segmentation
fault: 11
DETAIL: Failed process was running: select
pg_identify_object('pg_class'::regclass, 16414, 0);

The problem is that the function doesn't giuard against get_namespace_name
returning NULL,
which quote_identifier then tries to dereference.

Attached are two patches that fix both (in reverse order, patch 1 for the
second bug, and patch 2 for the first one)

Thanks,
Marko

Attachments:

t253844_1
0001-Fix-crash-in-pg_identify_object-when-an-object-s-sch.patchapplication/octet-stream; name=0001-Fix-crash-in-pg_identify_object-when-an-object-s-sch.patchDownload+12-7
0002-Reset-myTempNamespace-when-the-temp-schema-has-been-.patchapplication/octet-stream; name=0002-Reset-myTempNamespace-when-the-temp-schema-has-been-.patchDownload+87-2
#2Manu
manuelreyesbravo@gmail.com
In reply to: Marko Grujic (#1)
Re: Temp schema drop leaves an inconsistent state behind

Hi Marko,

Marko Grujic <marko.grujic@enterprisedb.com> wrote:

The reason it wasn't re-created is because the internal static variable
(myTempNamespace) is left holding the 16409 value internally.

This came up in 2019-2020 [1]/messages/by-id/CAKYtNAr9Zq=1-ww4etHo-VCC-k120YxZy5OS01VkaLPaDbv2tg@mail.gmail.com. a052f6cbb84 forbade DROP SCHEMA on temp
schemas and was reverted (65192e02441) after Robert and Tom argued that
a superuser should be able to do it, and that code should cope with a
missing schema instead of crashing; 80d76be51cf then fixed autovacuum
that way. Michael pointed out the stale myTempNamespace in that thread,
but it was left as is, so your patches fill that gap in the direction
agreed there. (Cc'ing Michael for that reason.)

I tested them on master d39fda1cc40, with --enable-cassert, and master
without them as the control. Both reported problems are fixed, and 0002
covers more than tables. After dropping the own temp schema, on master
CREATE DOMAIN, CREATE FUNCTION and CREATE STATISTICS in pg_temp fail
with "referenced schema was concurrently dropped", while a composite
type and a temp table with a serial column and an index are created in
the missing schema: 9 rows in pg_class and pg_type point to it. With
0002, everything is created and nothing is left dangling. The same when another superuser session drops
the schema: on master that session leaves a pg_class row with a missing
schema behind when it exits; with 0002, it doesn't.

About 0001: the strlist_to_textarray() part is worth a line in the
commit message, because on master a NULL name is silently dropped from
the array, and that is worse than it looks. With a table whose
pg_namespace row is gone (I deleted it with allow_system_table_mods) and
another table of the same name in public,

pg_get_object_address('table',
(pg_identify_object_as_address('pg_class'::regclass, oid, 0)).object_names,
'{}')

resolves to public.x on master. With 0001 the names are {NULL,x} and it
fails with "name or argument lists may not contain nulls". On master,
pg_identify_object() on that table crashes too, as in your report.

One problem with 0002: if the DROP SCHEMA is rolled back, the session
loses its temp schema, and the next temp table empties it.

CREATE TEMP TABLE keep(a int);
INSERT INTO keep VALUES (1), (2), (3);
BEGIN;
DROP SCHEMA pg_temp_0 CASCADE;
CREATE TEMP TABLE t3(a int);
ROLLBACK;
SELECT count(*) FROM keep;
ERROR: relation "keep" does not exist

keep is still in pg_class, in pg_temp_0, but pg_my_temp_schema() is 0,
pg_temp is gone from the search path, and "SELECT * FROM pg_temp_0.keep"
fails with "cannot access temporary tables of other sessions". The next
CREATE TEMP TABLE goes through InitTempTableNamespace(), finds pg_temp_0,
takes it for a crashed backend's leftover, and RemoveTempRelations()
drops keep. It's the same with ROLLBACK TO SAVEPOINT. On master, keep
still has its 3 rows in both cases.

Nothing undoes the reset in AccessTempTableNamespace() on abort:
AtEOXact_Namespace() sees the myTempNamespaceSubID set by the new
InitTempTableNamespace() and forgets the new schema, but nothing brings
back the old one. The attached diff, on top of 0002, remembers the
forgotten schema and the subtransaction that forgot it, and puts it back
if that subtransaction aborts, unless the schema was created in it; on
subtransaction commit it moves to the parent, like myTempNamespaceSubID.
If the drop was committed earlier, what it puts back is still stale, and
the next access forgets it again. The diff adds both rollback cases to
your test in temp.sql, which fails with 0002 alone.

With it, those two cases behave as on master, and so do these:

- a temp schema created, dropped and rolled back in one transaction
- a committed drop, then an aborted CREATE TEMP TABLE, then another
- a drop undone by ROLLBACK TO an outer savepoint, with a savepoint
released in between
- a drop released from a savepoint, then the whole transaction rolled
back

0002 alone loses keep in the last two. make check (239) and isolation
(133) pass with 0001 and 0002, and with the diff on top; pgindent leaves
it unchanged.

The attached temp_schema_drop_cases.sql has all of the above as a plain
psql script, one case per session, with what each should return. Case 8
deletes a pg_namespace row, so it is meant for a scratch database. On
master cases 1, 5 and 8 fail (8 by crashing, as the last statement), with
0001 and 0002 cases 2, 3, 6 and 7, and with the diff none.

[1]: /messages/by-id/CAKYtNAr9Zq=1-ww4etHo-VCC-k120YxZy5OS01VkaLPaDbv2tg@mail.gmail.com

Regards,
Manu

Attachments:

nocfbot-restore-temp-namespace-on-abort.diff.txttext/plain; charset=utf-8Download+123-0
temp_schema_drop_cases.sql.txttext/plain; charset=utf-8Download
#3Jim Jones
jim.jones@uni-muenster.de
In reply to: Manu (#2)
Re: Temp schema drop leaves an inconsistent state behind

On 22/09/2026 05:54, Manu wrote:

The attached temp_schema_drop_cases.sql has all of the above as a plain
psql script, one case per session, with what each should return. Case 8
deletes a pg_namespace row, so it is meant for a scratch database. On
master cases 1, 5 and 8 fail (8 by crashing, as the last statement), with
0001 and 0002 cases 2, 3, 6 and 7, and with the diff none.

On top of that, a just dropped schema can still be used to create
temporary objects, which creates a pg_class orphan:

psql (20devel)
Type "help" for help.

postgres=# create temporary table t();
CREATE TABLE
postgres=# \d t
Table "pg_temp_54.t"
Column | Type | Collation | Nullable | Default
--------+------+-----------+----------+---------

postgres=# select pg_my_temp_schema();
pg_my_temp_schema
-------------------
17398
(1 row)

postgres=# drop schema pg_temp_54 cascade;
NOTICE: drop cascades to table t
DROP SCHEMA
postgres=# set search_path = pg_temp, public;
SET
postgres=# create sequence s;
CREATE SEQUENCE
postgres=# select relname, relpersistence, relnamespace from pg_class
where relname = 's';
relname | relpersistence | relnamespace
---------+----------------+--------------
s | t | 17398
(1 row)

The dropped schema (oid 17398) is still being used, so a concurrent
pg_dump will also fail:

$ pg_dump postgres
pg_dump: error: schema with OID 17398 does not exist

IIUC the problem is that activeCreationNamespace is used when the
relpersistence is not RELPERSISTENCE_TEMP. So with pg_temp first in
search_path, activeCreationNamespace is the dropped schema.

Thanks!

Best, Jim

#4Manu
manuelreyesbravo@gmail.com
In reply to: Jim Jones (#3)
Re: Temp schema drop leaves an inconsistent state behind

Hi Jim,

On top of that, a just dropped schema can still be used to create
temporary objects, which creates a pg_class orphan:

...

IIUC the problem is that activeCreationNamespace is used when the
relpersistence is not RELPERSISTENCE_TEMP. So with pg_temp first in
search_path, activeCreationNamespace is the dropped schema.

That's right, and 0002 does not cover it, nor does my diff on top of
it. I ran each kind of CREATE as the first statement after the drop,
with pg_temp first in search_path and no TEMP keyword, one fresh
cluster per statement, on master and with 0001+0002 (the rollback diff
gives the same results):

CREATE TABLE, CREATE VIEW, CREATE TYPE (composite)
master: orphaned; 0002: fine
CREATE SEQUENCE, CREATE TABLE AS
master: orphaned; 0002: orphaned
CREATE TYPE (enum), CREATE DOMAIN, CREATE FUNCTION
master and 0002: "referenced schema was concurrently dropped"
CREATE MATERIALIZED VIEW
master: orphaned; 0002: assertion failure

TRAP: failed Assert("relation->rd_backend != INVALID_PROC_NUMBER"),
File: "relcache.c", Line: 1189

reached from RefreshMatViewByOid() -> finish_heap_swap() ->
reindex_relation() -> relcache invalidation. Without assertions
the command succeeds, but the view is then unreachable ("relation
"x" does not exist") and orphaned. On master it is at least
usable.

With the pg_temp. qualification all of them work with 0002, which is
what I tested in my previous mail.

Why: 0002 resets myTempNamespace in AccessTempTableNamespace(), and
RangeVarGetCreationNamespace() only calls that when the relation is
already known to be temporary. Otherwise it takes
activeCreationNamespace, the dropped schema, and
RangeVarAdjustRelationPersistence() marks the relation temporary
afterwards. CREATE TABLE and CREATE VIEW look the namespace up twice,
the second time in DefineRelation(), when the relation is already
temporary, so they reach the reset. CREATE SEQUENCE looks it up only
in DefineRelation(). That gives a check: CREATE SEQUENCE IF NOT
EXISTS, which adds a lookup before DefineRelation(), comes out right
with 0002, and plain CREATE SEQUENCE does not. For the materialized
view the reset happens in the middle of the command: the view is
created in the dropped schema, and the REFRESH that fills it creates
the new heap through AccessTempTableNamespace(), which moves the
session to a new temp schema underneath it.

The attached diff, on top of 0002, checks in
preprocessNamespacePath() that myTempNamespace still exists before
putting it in the search path. If it doesn't, pg_temp is treated as
not created yet, as in a session that has not used it, so creating
through the search path goes through AccessTempTableNamespace(true)
and the reset in 0002. With it:

- all sixteen statements in the test (the ones above, CREATE SEQUENCE
IF NOT EXISTS, and five with the pg_temp. qualification) create the
object in a new temp schema, with no orphans and no assertion
failure, both with 0001+0002 alone and with the rollback diff;
- your case leaves no orphan, and pg_dump succeeds;
- the cases from my previous mail give the same output as before, and
so do their variants creating through the search path: after a
rolled-back drop, keep still has its rows;
- make check (239) and isolation (133) pass, with no new warnings.

The extra syscache lookup only runs when the search path is
recomputed. I did not add a regression test; your sequence case would
be the natural one next to the others in temp.sql.

The scripts and all the outputs are attached.

Regards,
Manu

Attachments:

nocfbot-search-path-dropped-temp-namespace.diff.txttext/plainDownload+9-2
nocfbot-temp-schema-search-path-tests.txttext/plainDownload
#5Michael Paquier
michael@paquier.xyz
In reply to: Manu (#4)
Re: Temp schema drop leaves an inconsistent state behind

On Thu, Sep 24, 2026 at 11:28:54AM -0300, Manu wrote:

On top of that, a just dropped schema can still be used to create
temporary objects, which creates a pg_class orphan:
IIUC the problem is that activeCreationNamespace is used when the
relpersistence is not RELPERSISTENCE_TEMP. So with pg_temp first in
search_path, activeCreationNamespace is the dropped schema.

All these actions are doable only under a superuser, and there is an
argument over the existing behavior being useful, for example to clean
up orphaned objects post-crash-recovery.

Superusers can do worse than that. For example issue a TRUNCATE on a
few catalogs like pg_database, with set allow_system_table_mods =
true. Now, that's much more interesting.

My point being: we did not care back then for the reasons given back
then related to superusers. Why should we care now? This discussion
was feeling as a waste of precious resources back then; it still feels
the same today.

That's right, and 0002 does not cover it, nor does my diff on top of
it. I ran each kind of CREATE as the first statement after the drop,
with pg_temp first in search_path and no TEMP keyword, one fresh
cluster per statement, on master and with 0001+0002 (the rollback diff
gives the same results):

This comment does not apply only to this thread, more to the recent
activities of this email address: note that most of your reviews,
being clearly AI-generated, are rather noisy (not all, but a large
majority), and sometimes miss the point while providing a sloppy
amount of confusing contents.
--
Michael

#6Manu
manuelreyesbravo@gmail.com
In reply to: Michael Paquier (#5)
Re: Temp schema drop leaves an inconsistent state behind

Hi Michael,

Michael Paquier <michael@paquier.xyz> wrote:

My point being: we did not care back then for the reasons given back
then related to superusers. Why should we care now?

Fair enough. It was settled back then, and I'll leave it there.

This comment does not apply only to this thread, more to the recent
activities of this email address: note that most of your reviews,
being clearly AI-generated, are rather noisy (not all, but a large
majority), and sometimes miss the point while providing a sloppy
amount of confusing contents.

Thanks for saying it plainly. Yes, I use AI tooling: it builds the
patched trees, runs the tests and collects the numbers, and every
result I post comes from those runs. Deciding what is worth posting
is my part, and here I got it wrong: I went into how to fix this
before weighing whether it should be fixed, which had already been
answered in 2019. I'll take myself off the commitfest entry, and
keep reviews short and to what a thread actually needs.

Regards,
Manu

#7Marko Grujic
marko.grujic@enterprisedb.com
In reply to: Michael Paquier (#5)
Re: Temp schema drop leaves an inconsistent state behind

Hi all, thanks for testing and commenting.

On Fri, Sep 25, 2026 at 3:48 AM Michael Paquier <michael@paquier.xyz> wrote:

All these actions are doable only under a superuser, and there is an
argument over the existing behavior being useful, for example to clean
up orphaned objects post-crash-recovery.

Superusers can do worse than that. For example issue a TRUNCATE on a
few catalogs like pg_database, with set allow_system_table_mods =
true. Now, that's much more interesting.

In that case the superuser is opting-in to something explicitly dangerous.

My point being: we did not care back then for the reasons given back
then related to superusers. Why should we care now? This discussion
was feeling as a waste of precious resources back then; it still feels
the same today.

I wasn't aware of those discussions, but unlike above, DROP SCHEMA
pg_temp_N looks innocent enough, yet it can break pg_dump (not to
mention the segfault) which seemed severe enough to me to warrant a fix.

Still if this is the consensus I don't mind leaving that as is.

That said I do think that the first part of the patch (0001, which fixes the
two identify-object functions) has merit on its own. If nothing else, then
at least to gracefully handle the existing behavior for temp schema drops.
I can post it separately with a regression test if there's interest.

Thanks,
Marko

#8Jim Jones
jim.jones@uni-muenster.de
In reply to: Marko Grujic (#7)
Re: Temp schema drop leaves an inconsistent state behind

On 25/09/2026 10:38, Marko Grujic wrote:

On Fri, Sep 25, 2026 at 3:48 AM Michael Paquier <michael@paquier.xyz> wrote:

All these actions are doable only under a superuser, and there is an
argument over the existing behavior being useful, for example to clean
up orphaned objects post-crash-recovery.

Superusers can do worse than that. For example issue a TRUNCATE on a
few catalogs like pg_database, with set allow_system_table_mods =
true. Now, that's much more interesting.

In that case the superuser is opting-in to something explicitly dangerous.

I think Michael is right, superusers can do all sort of destructive
things -- I keep falling into this trap as well. I guess the trick here
for superusers would be "don't mess with the catalog unless you know
what you're doing" :)

Best, Jim