pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Temp schema drop leaves an inconsistent state behind
8+ messages / 4 participants
[nested] [flat]

* Temp schema drop leaves an inconsistent state behind
@ 2026-09-18 16:02  Marko Grujic <marko.grujic@enterprisedb.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Marko Grujic @ 2026-09-18 16:02 UTC (permalink / raw)
  To: pgsql-hackers; +Cc: Marko Grujic <markoog@gmail.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: download all (2 files, .tar.gz)

0001-Fix-crash-in-pg_identify_object-when-an-object-s-sch.patch (application/octet-stream, 1.7K) download From c09f6ce853eee2cf9778a8c9ac0ee1100ca068d1 Mon Sep 17 00:00:00 2001 From: Marko Grujic <markoog@gmail.com> Date: Fri, 18 Sep 2026 16:20:40 +0200 Subject: [PATCH 1/2] Fix crash in pg_identify_object() when an object's schema is missing Add a NULL-check so that quote_identifier doesn't try to deref a NULL pointer and segfault. Also fix strlist_to_textarray to correctly handle NULL items too. --- src/backend/catalog/objectaddress.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c index d3eee732062..71efd3928e0 100644 --- a/src/backend/catalog/objectaddress.c +++ b/src/backend/catalog/objectaddress.c @@ -4379,15 +4379,17 @@ pg_identify_object(PG_FUNCTION_ARGS) objidentity = getObjectIdentity(&address, true); /* schema name */ + nulls[1] = true; if (OidIsValid(schema_oid) && objidentity) { - const char *schema = quote_identifier(get_namespace_name(schema_oid)); + char *nspname = get_namespace_name(schema_oid); - values[1] = CStringGetTextDatum(schema); - nulls[1] = false; + if (nspname != NULL) + { + values[1] = CStringGetTextDatum(quote_identifier(nspname)); + nulls[1] = false; + } } - else - nulls[1] = true; /* object name */ if (objname && objidentity) @@ -6248,11 +6250,15 @@ strlist_to_textarray(List *list) if (name) { + datums[j] = CStringGetTextDatum(name); nulls[j] = false; - datums[j++] = CStringGetTextDatum(name); } else + { + datums[j] = (Datum) 0; nulls[j] = true; + } + j++; } MemoryContextSwitchTo(oldcxt); base-commit: 311df1dc0392f06973cf98eac51d63cb007267ce -- 2.54.0 (Apple Git-157)
0002-Reset-myTempNamespace-when-the-temp-schema-has-been-.patch (application/octet-stream, 5.1K) download From 4e543da40b6880e90dc266a740c28de4d09539a9 Mon Sep 17 00:00:00 2001 From: Marko Grujic <markoog@gmail.com> Date: Fri, 18 Sep 2026 16:28:02 +0200 Subject: [PATCH 2/2] Reset myTempNamespace when the temp schema has been dropped Otherwise dropping of the temp schema leaves the system in an inconsistent place, whereby the NS OID doesn't exist in the system catalogs, but the static variables are pointing to one. --- src/backend/catalog/namespace.c | 32 ++++++++++++++++++++++++++- src/test/regress/expected/temp.out | 35 ++++++++++++++++++++++++++++++ src/test/regress/sql/temp.sql | 21 ++++++++++++++++++ 3 files changed, 87 insertions(+), 1 deletion(-) diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c index 0647a198dea..f2480509e80 100644 --- a/src/backend/catalog/namespace.c +++ b/src/backend/catalog/namespace.c @@ -204,6 +204,9 @@ static Oid myTempToastNamespace = InvalidOid; static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId; +/* Have we registered RemoveTempRelationsCallback for this session yet? */ +static bool myTempNamespaceCleanupRegistered = false; + /* * This is the user's textual search path specification --- it's the value * of the GUC variable 'search_path'. @@ -4439,6 +4442,26 @@ AccessTempTableNamespace(bool force) */ MyXactFlags |= XACT_FLAGS_ACCESSEDTEMPNAMESPACE; + /* + * Nothing stops this session, or any superuser, from dropping pg_temp_N + * while the session is still using it, so reset myTempNamespace in case + * it no longer exists. + */ + if (OidIsValid(myTempNamespace) && + !SearchSysCacheExists1(NAMESPACEOID, + ObjectIdGetDatum(myTempNamespace))) + { + myTempNamespace = InvalidOid; + myTempToastNamespace = InvalidOid; + myTempNamespaceSubID = InvalidSubTransactionId; + + /* Reset the temporary namespace flag in MyProc. */ + MyProc->tempNamespaceId = InvalidOid; + + baseSearchPathValid = false; /* need to rebuild list */ + searchPathCacheValid = false; + } + /* * If the caller attempting to access a temporary schema expects the * creation of the namespace to be pending and should be enforced, then go @@ -4594,7 +4617,14 @@ AtEOXact_Namespace(bool isCommit, bool parallel) if (myTempNamespaceSubID != InvalidSubTransactionId && !parallel) { if (isCommit) - before_shmem_exit(RemoveTempRelationsCallback, 0); + { + /* register the callback only once per session */ + if (!myTempNamespaceCleanupRegistered) + { + before_shmem_exit(RemoveTempRelationsCallback, 0); + myTempNamespaceCleanupRegistered = true; + } + } else { myTempNamespace = InvalidOid; diff --git a/src/test/regress/expected/temp.out b/src/test/regress/expected/temp.out index a50c7ae88a9..476e312e352 100644 --- a/src/test/regress/expected/temp.out +++ b/src/test/regress/expected/temp.out @@ -566,3 +566,38 @@ SELECT count(*), max(a) max_a, min(a) min_a, max(cnt) max_cnt FROM test_temp; -- cleanup DROP FUNCTION test_temp_pin(int, int); +-- Check that dropping the temp schema doesn't leave an inconsistent state +\c - +BEGIN; +CREATE TEMP TABLE test_temp_t1(f1 int); +SELECT pg_my_temp_schema()::regnamespace AS mytempschema \gset +DROP SCHEMA :mytempschema CASCADE; +NOTICE: drop cascades to table test_temp_t1 +CREATE TEMP TABLE test_temp_t2(f1 int); +SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE oid = pg_my_temp_schema()) + AS temp_schema_exists; + temp_schema_exists +-------------------- + t +(1 row) + +COMMIT; +-- the same, with the drop in a later transaction +SELECT pg_my_temp_schema()::regnamespace AS mytempschema \gset +DROP SCHEMA :mytempschema CASCADE; +NOTICE: drop cascades to table test_temp_t2 +CREATE TEMP TABLE test_temp_t3(f1 int); +SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE oid = pg_my_temp_schema()) + AS temp_schema_exists; + temp_schema_exists +-------------------- + t +(1 row) + +SELECT count(*) AS orphans FROM pg_class c + WHERE NOT EXISTS (SELECT 1 FROM pg_namespace n WHERE n.oid = c.relnamespace); + orphans +--------- + 0 +(1 row) + diff --git a/src/test/regress/sql/temp.sql b/src/test/regress/sql/temp.sql index d50472ddced..7d7e18ce8c8 100644 --- a/src/test/regress/sql/temp.sql +++ b/src/test/regress/sql/temp.sql @@ -418,3 +418,24 @@ SELECT count(*), max(a) max_a, min(a) min_a, max(cnt) max_cnt FROM test_temp; -- cleanup DROP FUNCTION test_temp_pin(int, int); + + +-- Check that dropping the temp schema doesn't leave an inconsistent state +\c - +BEGIN; +CREATE TEMP TABLE test_temp_t1(f1 int); +SELECT pg_my_temp_schema()::regnamespace AS mytempschema \gset +DROP SCHEMA :mytempschema CASCADE; +CREATE TEMP TABLE test_temp_t2(f1 int); +SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE oid = pg_my_temp_schema()) + AS temp_schema_exists; +COMMIT; + +-- the same, with the drop in a later transaction +SELECT pg_my_temp_schema()::regnamespace AS mytempschema \gset +DROP SCHEMA :mytempschema CASCADE; +CREATE TEMP TABLE test_temp_t3(f1 int); +SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE oid = pg_my_temp_schema()) + AS temp_schema_exists; +SELECT count(*) AS orphans FROM pg_class c + WHERE NOT EXISTS (SELECT 1 FROM pg_namespace n WHERE n.oid = c.relnamespace); -- 2.54.0 (Apple Git-157)
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Temp schema drop leaves an inconsistent state behind
@ 2026-09-22 03:54  Manu <manuelreyesbravo@gmail.com>
  parent: Marko Grujic <marko.grujic@enterprisedb.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Manu @ 2026-09-22 03:54 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org; +Cc: Marko Grujic <marko.grujic@enterprisedb.com>; Marko Grujic <markoog@gmail.com>; Michael Paquier <michael@paquier.xyz>

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].  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] https://www.postgresql.org/message-id/CAKYtNAr9Zq%3D1-ww4etHo-VCC-k120YxZy5OS01VkaLPaDbv2tg%40mail.g...

Regards,
Manu

Attachments:

nocfbot-restore-temp-namespace-on-abort.diff.txt (text/plain, 5.8K) download diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c index f2480509e80..9d2053a9d50 100644 --- a/src/backend/catalog/namespace.c +++ b/src/backend/catalog/namespace.c @@ -207,6 +207,17 @@ static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId; /* Have we registered RemoveTempRelationsCallback for this session yet? */ static bool myTempNamespaceCleanupRegistered = false; +/* + * The temp namespace we forgot because it seemed to be gone, and the + * subtransaction in which we did that. If that subtransaction aborts, the + * DROP SCHEMA that made it disappear may be rolled back with it, so we go + * back to the namespace we had. + */ +static Oid forgottenTempNamespace = InvalidOid; +static Oid forgottenTempToastNamespace = InvalidOid; +static SubTransactionId forgottenTempNamespaceCreateSubID = InvalidSubTransactionId; +static SubTransactionId forgottenTempNamespaceSubID = InvalidSubTransactionId; + /* * This is the user's textual search path specification --- it's the value * of the GUC variable 'search_path'. @@ -4451,6 +4462,14 @@ AccessTempTableNamespace(bool force) !SearchSysCacheExists1(NAMESPACEOID, ObjectIdGetDatum(myTempNamespace))) { + if (forgottenTempNamespaceSubID == InvalidSubTransactionId) + { + forgottenTempNamespace = myTempNamespace; + forgottenTempToastNamespace = myTempToastNamespace; + forgottenTempNamespaceCreateSubID = myTempNamespaceSubID; + forgottenTempNamespaceSubID = GetCurrentSubTransactionId(); + } + myTempNamespace = InvalidOid; myTempToastNamespace = InvalidOid; myTempNamespaceSubID = InvalidSubTransactionId; @@ -4600,6 +4619,32 @@ InitTempTableNamespace(void) searchPathCacheValid = false; } +/* + * Go back to the temp namespace that AccessTempTableNamespace() forgot, + * because the (sub)transaction that forgot it, abortingSubid, is aborting. + * If that namespace was created within abortingSubid, its creation is being + * rolled back too, and there is nothing to go back to. + */ +static void +RestoreForgottenTempNamespace(SubTransactionId abortingSubid) +{ + if (forgottenTempNamespaceCreateSubID == InvalidSubTransactionId || + forgottenTempNamespaceCreateSubID < abortingSubid) + { + myTempNamespace = forgottenTempNamespace; + myTempToastNamespace = forgottenTempToastNamespace; + myTempNamespaceSubID = forgottenTempNamespaceCreateSubID; + MyProc->tempNamespaceId = forgottenTempNamespace; + baseSearchPathValid = false; /* need to rebuild list */ + searchPathCacheValid = false; + } + + forgottenTempNamespace = InvalidOid; + forgottenTempToastNamespace = InvalidOid; + forgottenTempNamespaceCreateSubID = InvalidSubTransactionId; + forgottenTempNamespaceSubID = InvalidSubTransactionId; +} + /* * End-of-transaction cleanup for namespaces. */ @@ -4646,6 +4691,18 @@ AtEOXact_Namespace(bool isCommit, bool parallel) myTempNamespaceSubID = InvalidSubTransactionId; } + if (forgottenTempNamespaceSubID != InvalidSubTransactionId && !parallel) + { + if (isCommit) + { + forgottenTempNamespace = InvalidOid; + forgottenTempToastNamespace = InvalidOid; + forgottenTempNamespaceCreateSubID = InvalidSubTransactionId; + forgottenTempNamespaceSubID = InvalidSubTransactionId; + } + else + RestoreForgottenTempNamespace(TopSubTransactionId); + } } /* @@ -4686,6 +4743,18 @@ AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid, MyProc->tempNamespaceId = InvalidOid; } } + + if (forgottenTempNamespaceSubID == mySubid) + { + if (isCommit) + { + forgottenTempNamespaceSubID = parentSubid; + if (forgottenTempNamespaceCreateSubID == mySubid) + forgottenTempNamespaceCreateSubID = parentSubid; + } + else + RestoreForgottenTempNamespace(mySubid); + } } /* diff --git a/src/test/regress/expected/temp.out b/src/test/regress/expected/temp.out index 476e312e352..92b61c09e25 100644 --- a/src/test/regress/expected/temp.out +++ b/src/test/regress/expected/temp.out @@ -601,3 +601,38 @@ SELECT count(*) AS orphans FROM pg_class c 0 (1 row) +-- if the drop is rolled back, the session keeps its temp schema and tables +INSERT INTO test_temp_t3 VALUES (1), (2), (3); +SELECT pg_my_temp_schema()::regnamespace AS mytempschema \gset +BEGIN; +DROP SCHEMA :mytempschema CASCADE; +NOTICE: drop cascades to table test_temp_t3 +CREATE TEMP TABLE test_temp_t4(f1 int); +ROLLBACK; +SELECT count(*) FROM test_temp_t3; + count +------- + 3 +(1 row) + +BEGIN; +SAVEPOINT sp; +DROP SCHEMA :mytempschema CASCADE; +NOTICE: drop cascades to table test_temp_t3 +CREATE TEMP TABLE test_temp_t4(f1 int); +ROLLBACK TO sp; +CREATE TEMP TABLE test_temp_t5(f1 int); +COMMIT; +SELECT count(*) FROM test_temp_t3; + count +------- + 3 +(1 row) + +SELECT pg_my_temp_schema()::regnamespace = :'mytempschema'::regnamespace + AS same_temp_schema; + same_temp_schema +------------------ + t +(1 row) + diff --git a/src/test/regress/sql/temp.sql b/src/test/regress/sql/temp.sql index 7d7e18ce8c8..95e41865242 100644 --- a/src/test/regress/sql/temp.sql +++ b/src/test/regress/sql/temp.sql @@ -439,3 +439,22 @@ SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE oid = pg_my_temp_schema()) AS temp_schema_exists; SELECT count(*) AS orphans FROM pg_class c WHERE NOT EXISTS (SELECT 1 FROM pg_namespace n WHERE n.oid = c.relnamespace); + +-- if the drop is rolled back, the session keeps its temp schema and tables +INSERT INTO test_temp_t3 VALUES (1), (2), (3); +SELECT pg_my_temp_schema()::regnamespace AS mytempschema \gset +BEGIN; +DROP SCHEMA :mytempschema CASCADE; +CREATE TEMP TABLE test_temp_t4(f1 int); +ROLLBACK; +SELECT count(*) FROM test_temp_t3; +BEGIN; +SAVEPOINT sp; +DROP SCHEMA :mytempschema CASCADE; +CREATE TEMP TABLE test_temp_t4(f1 int); +ROLLBACK TO sp; +CREATE TEMP TABLE test_temp_t5(f1 int); +COMMIT; +SELECT count(*) FROM test_temp_t3; +SELECT pg_my_temp_schema()::regnamespace = :'mytempschema'::regnamespace + AS same_temp_schema;
temp_schema_drop_cases.sql.txt (text/plain, 5.0K) download -- Cases around DROP SCHEMA of the session's own pg_temp_N. -- Run as a superuser in a scratch database: psql -X -f temp_schema_drop_cases.sql -- Each case starts a new session (\c -). "expected" is master's behavior, -- or what should happen where master is broken. \set VERBOSITY terse \pset footer off \echo \echo == 1. drop committed, then other temp objects \echo expected: all created, nothing pointing to a missing schema \echo (master: errors, and rows left in pg_class/pg_type) \c - CREATE TEMP TABLE z(a int); SELECT pg_my_temp_schema()::regnamespace AS s \gset DROP SCHEMA :s CASCADE; CREATE TYPE pg_temp.ty AS (a int); CREATE DOMAIN pg_temp.dom AS int; CREATE FUNCTION pg_temp.eq3(int, int) RETURNS bool LANGUAGE sql AS 'SELECT $1 = $2'; CREATE OPERATOR pg_temp.=== (LEFTARG = int, RIGHTARG = int, FUNCTION = pg_temp.eq3); CREATE TEMP TABLE ser(id serial PRIMARY KEY, b int); CREATE INDEX ON ser(b); CREATE STATISTICS pg_temp.st ON id, b FROM ser; SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE oid = pg_my_temp_schema()) AS temp_schema_exists, (SELECT count(*) FROM pg_class c WHERE NOT EXISTS (SELECT 1 FROM pg_namespace n WHERE n.oid = c.relnamespace)) AS dangling_class, (SELECT count(*) FROM pg_type t WHERE NOT EXISTS (SELECT 1 FROM pg_namespace n WHERE n.oid = t.typnamespace)) AS dangling_type; \echo \echo == 2. drop rolled back \echo expected: keep has 3 rows, before and after the next CREATE TEMP TABLE \c - CREATE TEMP TABLE keep(a int); INSERT INTO keep VALUES (1), (2), (3); SELECT pg_my_temp_schema()::regnamespace AS s \gset BEGIN; DROP SCHEMA :s CASCADE; CREATE TEMP TABLE t(a int); ROLLBACK; SELECT count(*) AS keep_rows FROM keep; CREATE TEMP TABLE t2(a int); SELECT count(*) AS keep_rows FROM keep; \echo \echo == 3. drop undone by ROLLBACK TO SAVEPOINT \echo expected: keep has 3 rows, before and after the next CREATE TEMP TABLE \c - CREATE TEMP TABLE keep(a int); INSERT INTO keep VALUES (1), (2), (3); SELECT pg_my_temp_schema()::regnamespace AS s \gset BEGIN; SAVEPOINT sp; DROP SCHEMA :s CASCADE; CREATE TEMP TABLE t(a int); ROLLBACK TO sp; COMMIT; SELECT count(*) AS keep_rows FROM keep; CREATE TEMP TABLE t2(a int); SELECT count(*) AS keep_rows FROM keep; \echo \echo == 4. temp schema created, dropped and rolled back in one transaction \echo expected: c has 1 row, temp schema exists \c - BEGIN; CREATE TEMP TABLE a(x int); SELECT pg_my_temp_schema()::regnamespace AS s \gset DROP SCHEMA :s CASCADE; CREATE TEMP TABLE b(x int); ROLLBACK; CREATE TEMP TABLE c(x int); INSERT INTO c VALUES (1); SELECT count(*) AS c_rows, EXISTS (SELECT 1 FROM pg_namespace WHERE oid = pg_my_temp_schema()) AS temp_schema_exists; \echo \echo == 5. drop committed, then an aborted CREATE TEMP TABLE, then another \echo expected: c has 1 row, temp schema exists (master: it doesn't) \c - CREATE TEMP TABLE a(x int); SELECT pg_my_temp_schema()::regnamespace AS s \gset DROP SCHEMA :s CASCADE; BEGIN; CREATE TEMP TABLE b(x int); ROLLBACK; CREATE TEMP TABLE c(x int); INSERT INTO c VALUES (1); SELECT count(*) AS c_rows, EXISTS (SELECT 1 FROM pg_namespace WHERE oid = pg_my_temp_schema()) AS temp_schema_exists; \echo \echo == 6. drop undone by ROLLBACK TO an outer savepoint, a savepoint released in between \echo expected: keep has 3 rows \c - CREATE TEMP TABLE keep(x int); INSERT INTO keep VALUES (1), (2), (3); SELECT pg_my_temp_schema()::regnamespace AS s \gset BEGIN; SAVEPOINT a; SAVEPOINT b; DROP SCHEMA :s CASCADE; SAVEPOINT c; CREATE TEMP TABLE t(x int); RELEASE c; ROLLBACK TO b; CREATE TEMP TABLE t2(x int); COMMIT; SELECT count(*) AS keep_rows FROM keep; \echo \echo == 7. drop released from a savepoint, then the transaction rolled back \echo expected: keep has 3 rows, before and after the next CREATE TEMP TABLE \c - CREATE TEMP TABLE keep(x int); INSERT INTO keep VALUES (1), (2), (3); SELECT pg_my_temp_schema()::regnamespace AS s \gset BEGIN; SAVEPOINT a; DROP SCHEMA :s CASCADE; CREATE TEMP TABLE t(x int); RELEASE a; ROLLBACK; SELECT count(*) AS keep_rows FROM keep; CREATE TEMP TABLE t3(x int); SELECT count(*) AS keep_rows FROM keep; \echo \echo == 8. a table whose pg_namespace row is gone, and a same-named table in public \echo expected: no crash; the round trip must not land on public.x \echo (master: pg_identify_object crashes, and the round trip returns public.x) \echo This one deletes a catalog row: run it in a database you can throw away. \c - CREATE SCHEMA gone; CREATE TABLE gone.x(a int); CREATE TABLE public.x(b text); SELECT oid AS xoid FROM pg_class WHERE relnamespace = 'gone'::regnamespace AND relname = 'x' \gset SET allow_system_table_mods = on; DELETE FROM pg_namespace WHERE nspname = 'gone'; RESET allow_system_table_mods; SELECT :xoid AS gone_x_oid, 'public.x'::regclass::oid AS public_x_oid; SELECT (pg_identify_object_as_address('pg_class'::regclass, :xoid, 0)).object_names; SELECT objid AS round_trip_oid FROM pg_get_object_address('table', (pg_identify_object_as_address('pg_class'::regclass, :xoid, 0)).object_names, '{}'); SELECT pg_identify_object('pg_class'::regclass, :xoid, 0);
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Temp schema drop leaves an inconsistent state behind
@ 2026-09-24 07:48  Jim Jones <jim.jones@uni-muenster.de>
  parent: Manu <manuelreyesbravo@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Jim Jones @ 2026-09-24 07:48 UTC (permalink / raw)
  To: Manu <manuelreyesbravo@gmail.com>; pgsql-hackers@lists.postgresql.org; +Cc: Marko Grujic <marko.grujic@enterprisedb.com>; Marko Grujic <markoog@gmail.com>; Michael Paquier <michael@paquier.xyz>

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








^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Temp schema drop leaves an inconsistent state behind
@ 2026-09-24 14:28  Manu <manuelreyesbravo@gmail.com>
  parent: Jim Jones <jim.jones@uni-muenster.de>
  0 siblings, 1 reply; 8+ messages in thread

From: Manu @ 2026-09-24 14:28 UTC (permalink / raw)
  To: Jim Jones <jim.jones@uni-muenster.de>; pgsql-hackers@lists.postgresql.org; +Cc: Marko Grujic <marko.grujic@enterprisedb.com>; Marko Grujic <markoog@gmail.com>; Michael Paquier <michael@paquier.xyz>

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.txt (text/plain, 915B) download diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c index f2480509e80..83a1c659b46 100644 --- a/src/backend/catalog/namespace.c +++ b/src/backend/catalog/namespace.c @@ -4232,8 +4243,15 @@ preprocessNamespacePath(const char *searchPath, Oid roleid, } else if (strcmp(curname, "pg_temp") == 0) { - /* pg_temp --- substitute temp namespace, if any */ - if (OidIsValid(myTempNamespace)) + /* + * pg_temp --- substitute temp namespace, if any. It may have + * been dropped while this session was using it; then treat it as + * not created yet, so that creating an object through the search + * path goes through AccessTempTableNamespace() and gets a new one. + */ + if (OidIsValid(myTempNamespace) && + SearchSysCacheExists1(NAMESPACEOID, + ObjectIdGetDatum(myTempNamespace))) oidlist = lappend_oid(oidlist, myTempNamespace); else {
nocfbot-temp-schema-search-path-tests.txt (text/plain, 17.5K) download # Temp schema dropped by its own session: objects created through the # search path (no TEMP keyword, no pg_temp. qualification). # Builds, all on d39fda1cc40, --enable-cassert unless noted: # master control # p7321 + 0001 and 0002 # p7321f + 0001, 0002 and nocfbot-restore-temp-namespace-on-abort.diff (22-09) # p7321f-nc the same as p7321f, without --enable-cassert # "+ search-path check": nocfbot-search-path-dropped-temp-namespace.diff on top ======== first_after_drop.sh (one fresh cluster per statement) #!/usr/bin/env bash # Each kind of object as the FIRST statement after the own temp schema is # dropped, pg_temp first in search_path, no TEMP keyword, one session each. # Prints whether the new object's schema exists and the orphan count. # first_after_drop.sh (runs master, p7321, p7321f) set -u D=$(cd "$(dirname "$0")" && pwd) STMTS=( "create sequence x" "create table x (a int)" "create view x as select 1 as a" "create table x as select 1 as a" "create materialized view x as select 1 as a" "create type x as (a int)" "create type x as enum ('a')" "create domain x as int" "create function x() returns int language sql as 'select 1'" "create temp sequence x" "create sequence if not exists x" "create sequence pg_temp.x" "create table pg_temp.x as select 1 as a" "create materialized view pg_temp.x as select 1 as a" "create domain pg_temp.x as int" "create function pg_temp.x() returns int language sql as 'select 1'" ) # A fresh cluster for every statement: a crash in one case must not leak into # the next, and orphan counts must not include leftovers of earlier sessions. TPL=/tmp/claude-1000/f7321.tpl for N in ${BUILDS:-master p7321 p7321f}; do I=i-$N/bin export PGPORT=55327 PGHOST=/tmp PGDATABASE=postgres rm -rf "$TPL"; "$I/initdb" -D "$TPL" -A trust --no-sync > /dev/null printf "port = %s\nunix_socket_directories = '/tmp'\nlogging_collector = off\n" $PGPORT >> "$TPL/postgresql.conf" echo "################ $N" for s in "${STMTS[@]}"; do PGD=$(mktemp -d /tmp/claude-1000/f7321.XXXX); cp -a "$TPL/." "$PGD/" "$I/pg_ctl" -D "$PGD" -l "$PGD/server.log" -w start > /dev/null r=$("$I/psql" -X -qAt 2>&1 <<SQL \set ON_ERROR_STOP off \set VERBOSITY terse create temp table t(); select format('drop schema %I cascade', nspname) from pg_namespace where oid = pg_my_temp_schema() \gexec set search_path = pg_temp, public; $s; select 'orphans=' || ((select count(*) from pg_class c where not exists (select 1 from pg_namespace n where n.oid = c.relnamespace)) + (select count(*) from pg_type y where not exists (select 1 from pg_namespace n where n.oid = y.typnamespace)) + (select count(*) from pg_proc p where not exists (select 1 from pg_namespace n where n.oid = p.pronamespace))) || ' my_temp_schema_exists=' || exists (select 1 from pg_namespace where oid = pg_my_temp_schema()); SQL ) if grep -q 'terminated by signal' "$PGD/server.log"; then r="CRASH: $(grep -m1 -oE 'TRAP: .*' "$PGD/server.log" | cut -c1-150)" fi printf ' %-62s %s\n' "$s" "$(echo "$r" | grep -vE '^(NOTICE|$)' | sed 's/.*ERROR: */ERROR: /' | tr '\n' ' ')" "$I/pg_ctl" -D "$PGD" -m immediate stop > /dev/null 2>&1 cp "$PGD/server.log" "/tmp/claude-1000/f7321.$N.$(echo "$s" | tr -c 'a-z' '_' | cut -c1-30).log" rm -rf "$PGD" done done ======== results before the search-path check ################ master create sequence x orphans=1 my_temp_schema_exists=false create table x (a int) orphans=3 my_temp_schema_exists=false create view x as select 1 as a orphans=3 my_temp_schema_exists=false create table x as select 1 as a orphans=3 my_temp_schema_exists=false create materialized view x as select 1 as a orphans=3 my_temp_schema_exists=false create type x as (a int) orphans=3 my_temp_schema_exists=false create type x as enum ('a') ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create domain x as int ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create function x() returns int language sql as 'select 1' ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create temp sequence x orphans=1 my_temp_schema_exists=false create sequence pg_temp.x orphans=1 my_temp_schema_exists=false create table pg_temp.x as select 1 as a orphans=3 my_temp_schema_exists=false create materialized view pg_temp.x as select 1 as a orphans=3 my_temp_schema_exists=false create domain pg_temp.x as int ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create function pg_temp.x() returns int language sql as 'select 1' ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false ################ p7321 create sequence x orphans=1 my_temp_schema_exists=false create table x (a int) orphans=0 my_temp_schema_exists=true create view x as select 1 as a orphans=0 my_temp_schema_exists=true create table x as select 1 as a orphans=3 my_temp_schema_exists=false create materialized view x as select 1 as a CRASH: TRAP: failed Assert("relation->rd_backend != INVALID_PROC_NUMBER"), File: "p7321/src/backend/utils/cache/relcache.c", Line: 1189, PI create type x as (a int) orphans=0 my_temp_schema_exists=true create type x as enum ('a') ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create domain x as int ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create function x() returns int language sql as 'select 1' ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create temp sequence x orphans=0 my_temp_schema_exists=true create sequence pg_temp.x orphans=0 my_temp_schema_exists=true create table pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create materialized view pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create domain pg_temp.x as int orphans=0 my_temp_schema_exists=true create function pg_temp.x() returns int language sql as 'select 1' orphans=0 my_temp_schema_exists=true ################ p7321f create sequence x orphans=1 my_temp_schema_exists=false create table x (a int) orphans=0 my_temp_schema_exists=true create view x as select 1 as a orphans=0 my_temp_schema_exists=true create table x as select 1 as a orphans=3 my_temp_schema_exists=false create materialized view x as select 1 as a CRASH: TRAP: failed Assert("relation->rd_backend != INVALID_PROC_NUMBER"), File: "p7321f/src/backend/utils/cache/relcache.c", Line: 1189, P create type x as (a int) orphans=0 my_temp_schema_exists=true create type x as enum ('a') ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create domain x as int ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create function x() returns int language sql as 'select 1' ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create temp sequence x orphans=0 my_temp_schema_exists=true create sequence pg_temp.x orphans=0 my_temp_schema_exists=true create table pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create materialized view pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create domain pg_temp.x as int orphans=0 my_temp_schema_exists=true create function pg_temp.x() returns int language sql as 'select 1' orphans=0 my_temp_schema_exists=true ################ p7321f-nc create sequence x orphans=1 my_temp_schema_exists=false create table x (a int) orphans=0 my_temp_schema_exists=true create view x as select 1 as a orphans=0 my_temp_schema_exists=true create table x as select 1 as a orphans=3 my_temp_schema_exists=false create materialized view x as select 1 as a orphans=3 my_temp_schema_exists=true create type x as (a int) orphans=0 my_temp_schema_exists=true create type x as enum ('a') ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create domain x as int ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create function x() returns int language sql as 'select 1' ERROR: referenced schema was concurrently dropped orphans=0 my_temp_schema_exists=false create temp sequence x orphans=0 my_temp_schema_exists=true create sequence pg_temp.x orphans=0 my_temp_schema_exists=true create table pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create materialized view pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create domain pg_temp.x as int orphans=0 my_temp_schema_exists=true create function pg_temp.x() returns int language sql as 'select 1' orphans=0 my_temp_schema_exists=true (added later, same script) master create sequence if not exists x orphans=1 my_temp_schema_exists=false p7321f-nc create sequence if not exists x orphans=0 my_temp_schema_exists=true ======== results with the search-path check ################ p7321 create sequence x orphans=0 my_temp_schema_exists=true create table x (a int) orphans=0 my_temp_schema_exists=true create view x as select 1 as a orphans=0 my_temp_schema_exists=true create table x as select 1 as a orphans=0 my_temp_schema_exists=true create materialized view x as select 1 as a orphans=0 my_temp_schema_exists=true create type x as (a int) orphans=0 my_temp_schema_exists=true create type x as enum ('a') orphans=0 my_temp_schema_exists=true create domain x as int orphans=0 my_temp_schema_exists=true create function x() returns int language sql as 'select 1' orphans=0 my_temp_schema_exists=true create temp sequence x orphans=0 my_temp_schema_exists=true create sequence if not exists x orphans=0 my_temp_schema_exists=true create sequence pg_temp.x orphans=0 my_temp_schema_exists=true create table pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create materialized view pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create domain pg_temp.x as int orphans=0 my_temp_schema_exists=true create function pg_temp.x() returns int language sql as 'select 1' orphans=0 my_temp_schema_exists=true ################ p7321f + search-path check create sequence x orphans=0 my_temp_schema_exists=true create table x (a int) orphans=0 my_temp_schema_exists=true create view x as select 1 as a orphans=0 my_temp_schema_exists=true create table x as select 1 as a orphans=0 my_temp_schema_exists=true create materialized view x as select 1 as a orphans=0 my_temp_schema_exists=true create type x as (a int) orphans=0 my_temp_schema_exists=true create type x as enum ('a') orphans=0 my_temp_schema_exists=true create domain x as int orphans=0 my_temp_schema_exists=true create function x() returns int language sql as 'select 1' orphans=0 my_temp_schema_exists=true create temp sequence x orphans=0 my_temp_schema_exists=true create sequence if not exists x orphans=0 my_temp_schema_exists=true create sequence pg_temp.x orphans=0 my_temp_schema_exists=true create table pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create materialized view pg_temp.x as select 1 as a orphans=0 my_temp_schema_exists=true create domain pg_temp.x as int orphans=0 my_temp_schema_exists=true create function pg_temp.x() returns int language sql as 'select 1' orphans=0 my_temp_schema_exists=true ======== rollback_searchpath.sql -- The rollback cases of the review, but with the new object created through -- the search path (no TEMP keyword), which is the path the search-path -- check adds. Expected as on master: keep still has its 3 rows. \set ON_ERROR_STOP off \set VERBOSITY terse \pset footer off \echo '=== R1 DROP SCHEMA + CREATE SEQUENCE (no TEMP), ROLLBACK' \c set search_path = pg_temp, public; create temp table keep(a int); insert into keep values (1), (2), (3); select pg_my_temp_schema()::regnamespace as tmp \gset begin; drop schema :tmp cascade; create sequence s_r1; rollback; select count(*) as keep_rows from keep; create sequence s_after; select count(*) as keep_rows_after_next_create from keep; \echo '=== R2 the same, ROLLBACK TO SAVEPOINT' \c set search_path = pg_temp, public; create temp table keep(a int); insert into keep values (1), (2), (3); select pg_my_temp_schema()::regnamespace as tmp \gset begin; savepoint sp; drop schema :tmp cascade; create table t_r2 (a int); rollback to savepoint sp; commit; select count(*) as keep_rows from keep; create table t_after (a int); select count(*) as keep_rows_after_next_create from keep; \echo '=== R3 committed drop, then CREATE SEQUENCE (no TEMP) twice' \c set search_path = pg_temp, public; create temp table t(); select pg_my_temp_schema()::regnamespace as tmp \gset drop schema :tmp cascade; create sequence s1; create sequence s2; select count(*) as orphans from pg_class c where not exists (select 1 from pg_namespace n where n.oid = c.relnamespace); select count(distinct relnamespace) as schemas_used from pg_class where relname in ('s1', 's2'); ======== its output: master, then p7321f + search-path check ######## master === R1 DROP SCHEMA + CREATE SEQUENCE (no TEMP), ROLLBACK keep_rows 3 keep_rows_after_next_create 3 === R2 the same, ROLLBACK TO SAVEPOINT keep_rows 3 keep_rows_after_next_create 3 === R3 committed drop, then CREATE SEQUENCE (no TEMP) twice orphans 2 schemas_used 1 ######## p7321f === R1 DROP SCHEMA + CREATE SEQUENCE (no TEMP), ROLLBACK keep_rows 3 keep_rows_after_next_create 3 === R2 the same, ROLLBACK TO SAVEPOINT keep_rows 3 keep_rows_after_next_create 3 === R3 committed drop, then CREATE SEQUENCE (no TEMP) twice orphans 0 schemas_used 1 ======== with the search-path check: make check, isolation, the review cases, Jim case == review cases (temp_schema_drop_cases.sql), p7321f + search-path check vs the p7321f run of 22-09 IDENTICAL to the 22-09 p7321f run == jim cases + pg_dump relname | relpersistence | schema_exists s | t | t orphan_class | orphan_type | orphan_proc 0 | 0 | 0 === J2 CREATE TABLE and CREATE VIEW, no TEMP keyword relname | relkind | relpersistence | schema_exists tt | r | t | t vv | v | t | t orphan_class | orphan_type 0 | 0 === J3 non-relation objects: type, function, domain orphan_class | orphan_type | orphan_proc 0 | 0 | 0 === J4 control: same as J1 but with the TEMP keyword relname | relpersistence | schema_exists s | t | t orphan_class 0 relname | relnamespace s5 | public DROP SEQUENCE relname | relpersistence | schema_exists s6 | t | t orphan_class 0 pg_dump: OK == make check / isolation # All 239 tests passed. # All 133 tests passed.
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Temp schema drop leaves an inconsistent state behind
@ 2026-09-25 01:48  Michael Paquier <michael@paquier.xyz>
  parent: Manu <manuelreyesbravo@gmail.com>
  0 siblings, 2 replies; 8+ messages in thread

From: Michael Paquier @ 2026-09-25 01:48 UTC (permalink / raw)
  To: Manu <manuelreyesbravo@gmail.com>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; pgsql-hackers@lists.postgresql.org; Marko Grujic <marko.grujic@enterprisedb.com>; Marko Grujic <markoog@gmail.com>

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

Attachments:

  signature.asc (application/pgp-signature, 832B) download

^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Temp schema drop leaves an inconsistent state behind
@ 2026-09-25 03:19  Manu <manuelreyesbravo@gmail.com>
  parent: Michael Paquier <michael@paquier.xyz>
  1 sibling, 0 replies; 8+ messages in thread

From: Manu @ 2026-09-25 03:19 UTC (permalink / raw)
  To: Michael Paquier <michael@paquier.xyz>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; Marko Grujic <marko.grujic@enterprisedb.com>; Marko Grujic <markoog@gmail.com>; pgsql-hackers@lists.postgresql.org

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






^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Temp schema drop leaves an inconsistent state behind
@ 2026-09-25 08:38  Marko Grujic <marko.grujic@enterprisedb.com>
  parent: Michael Paquier <michael@paquier.xyz>
  1 sibling, 1 reply; 8+ messages in thread

From: Marko Grujic @ 2026-09-25 08:38 UTC (permalink / raw)
  To: Michael Paquier <michael@paquier.xyz>; Jim Jones <jim.jones@uni-muenster.de>; pgsql-hackers@lists.postgresql.org; +Cc: Manu <manuelreyesbravo@gmail.com>; Marko Grujic <markoog@gmail.com>

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






^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Temp schema drop leaves an inconsistent state behind
@ 2026-09-25 12:09  Jim Jones <jim.jones@uni-muenster.de>
  parent: Marko Grujic <marko.grujic@enterprisedb.com>
  0 siblings, 0 replies; 8+ messages in thread

From: Jim Jones @ 2026-09-25 12:09 UTC (permalink / raw)
  To: Marko Grujic <marko.grujic@enterprisedb.com>; Michael Paquier <michael@paquier.xyz>; pgsql-hackers@lists.postgresql.org; +Cc: Manu <manuelreyesbravo@gmail.com>; Marko Grujic <markoog@gmail.com>

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







^ permalink  raw  reply  [nested|flat] 8+ messages in thread


end of thread, other threads:[~2026-09-25 12:09 UTC | newest]

Thread overview: 8+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-09-18 16:02 Temp schema drop leaves an inconsistent state behind Marko Grujic <marko.grujic@enterprisedb.com>
2026-09-22 03:54 ` Manu <manuelreyesbravo@gmail.com>
2026-09-24 07:48   ` Jim Jones <jim.jones@uni-muenster.de>
2026-09-24 14:28     ` Manu <manuelreyesbravo@gmail.com>
2026-09-25 01:48       ` Michael Paquier <michael@paquier.xyz>
2026-09-25 03:19         ` Manu <manuelreyesbravo@gmail.com>
2026-09-25 08:38         ` Marko Grujic <marko.grujic@enterprisedb.com>
2026-09-25 12:09           ` Jim Jones <jim.jones@uni-muenster.de>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox