postgres_fdw: transaction mode inheritance corner cases

Started by Fujii Masao3 months ago23 messageshackers
Jump to latest
#1Fujii Masao
masao.fujii@gmail.com

Hi,

Commit de28140ded8 introduced transaction mode inheritance in
postgres_fdw, but I found several potential issues with it.

We should add this as PostgreSQL 19 Open Item?

(1) READ ONLY does not take effect for an existing cursor

DECLARE initializes the foreign scan and opens the remote transaction.
FETCH reuses that connection without calling begin_remote_xact(), so
a subsequent mode change is not propagated to the remote server.

In the following example, the query executed by FETCH runs in READ WRITE
mode on the remote server even though the local transaction is READ ONLY:

BEGIN;
DECLARE c CURSOR FOR SELECT * FROM ft;
SET TRANSACTION READ ONLY;
FETCH ALL FROM c;
COMMIT;

(2) READ WRITE and NOT DEFERRABLE are not always inherited

begin_remote_xact() adds READ ONLY and DEFERRABLE when applicable,
but does not explicitly specify READ WRITE or NOT DEFERRABLE. Those
modes therefore depend on the defaults on the remote server.

This seems to conflict with the postgres_fdw docs:

The remote transaction is opened in the same read/write mode as the
local transaction: if the local transaction is READ ONLY, the remote
transaction is opened in READ ONLY mode, otherwise it is opened in READ
WRITE mode.

(3) DEFERRABLE breaks queries against PostgreSQL 9.0 and older

When the remote server is PostgreSQL 9.0 or older, the remote
START TRANSACTION can fail with a syntax error at DEFERRABLE, since
that option is not supported there. Since the docs still says that
read-only access is supported back to PostgreSQL 8.1, this case
should be handled.

(4) A loopback query can wait indefinitely after switching to READ ONLY

BEGIN ISOLATION LEVEL SERIALIZABLE READ WRITE DEFERRABLE;
SELECT * FROM t;
SET TRANSACTION READ ONLY;
SELECT * FROM ft;
ROLLBACK;

In this example, the foreign SELECT waits indefinitely.

The local transaction remains READ WRITE in SSI after taking its first
snapshot. The remote READ ONLY DEFERRABLE transaction waits for the
local transaction to finish before obtaining a safe snapshot, while the
local transaction waits for the remote query.

I'm not sure whether this is something we should fix or just consider an
operational mistake, but I wanted to share the case.

(5) Deferred remote triggers can write after switching to READ ONLY

pgfdw_xact_callback() sends COMMIT without synchronizing the
read-only mode, so a deferred trigger on the remote server can still run
in READ WRITE mode.

BEGIN;
INSERT INTO ft VALUES (...);
SET TRANSACTION READ ONLY;
COMMIT;

Regards,

--
Fujii Masao

#2Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Fujii Masao (#1)
Re: postgres_fdw: transaction mode inheritance corner cases

On Thu, Sep 10, 2026 at 9:34 AM Fujii Masao <masao.fujii@gmail.com> wrote:

Commit de28140ded8 introduced transaction mode inheritance in
postgres_fdw, but I found several potential issues with it.

Thanks for the report! Will look into the issues.

We should add this as PostgreSQL 19 Open Item?

I added this to the open item list.

Best regards,
Etsuro Fujita

#3Nathan Bossart
nathandbossart@gmail.com
In reply to: Etsuro Fujita (#2)
Re: postgres_fdw: transaction mode inheritance corner cases

[RMT hat]

On Thu, Sep 10, 2026 at 06:24:55PM +0900, Etsuro Fujita wrote:

On Thu, Sep 10, 2026 at 9:34 AM Fujii Masao <masao.fujii@gmail.com> wrote:

Commit de28140ded8 introduced transaction mode inheritance in
postgres_fdw, but I found several potential issues with it.

Thanks for the report! Will look into the issues.

We should add this as PostgreSQL 19 Open Item?

I added this to the open item list.

Will these issues be fixed before code freeze for 19beta4 on Saturday?
Does commit de28140ded8 need to be reverted?

--
nathan

#4Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Nathan Bossart (#3)
Re: postgres_fdw: transaction mode inheritance corner cases

On Thu, Sep 17, 2026 at 12:44 AM Nathan Bossart
<nathandbossart@gmail.com> wrote:

On Thu, Sep 10, 2026 at 06:24:55PM +0900, Etsuro Fujita wrote:

On Thu, Sep 10, 2026 at 9:34 AM Fujii Masao <masao.fujii@gmail.com> wrote:

Commit de28140ded8 introduced transaction mode inheritance in
postgres_fdw, but I found several potential issues with it.

Thanks for the report! Will look into the issues.

We should add this as PostgreSQL 19 Open Item?

I added this to the open item list.

Will these issues be fixed before code freeze for 19beta4 on Saturday?
Does commit de28140ded8 need to be reverted?

Unfortunately, I don’t think I will be able to fix these by then. I'm
planning to propose (the first version of) a fix next week as soon as
possible.

Best regards,
Etsuro Fujita

#5Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Fujii Masao (#1)
Re: postgres_fdw: transaction mode inheritance corner cases

On Thu, Sep 10, 2026 at 9:34 AM Fujii Masao <masao.fujii@gmail.com> wrote:

(1) READ ONLY does not take effect for an existing cursor

DECLARE initializes the foreign scan and opens the remote transaction.
FETCH reuses that connection without calling begin_remote_xact(), so
a subsequent mode change is not propagated to the remote server.

Fixed.

(2) READ WRITE and NOT DEFERRABLE are not always inherited

begin_remote_xact() adds READ ONLY and DEFERRABLE when applicable,
but does not explicitly specify READ WRITE or NOT DEFERRABLE. Those
modes therefore depend on the defaults on the remote server.

Fixed.

(3) DEFERRABLE breaks queries against PostgreSQL 9.0 and older

When the remote server is PostgreSQL 9.0 or older, the remote
START TRANSACTION can fail with a syntax error at DEFERRABLE, since
that option is not supported there. Since the docs still says that
read-only access is supported back to PostgreSQL 8.1, this case
should be handled.

Fixed.

(4) A loopback query can wait indefinitely after switching to READ ONLY

BEGIN ISOLATION LEVEL SERIALIZABLE READ WRITE DEFERRABLE;
SELECT * FROM t;
SET TRANSACTION READ ONLY;
SELECT * FROM ft;
ROLLBACK;

In this example, the foreign SELECT waits indefinitely.

The local transaction remains READ WRITE in SSI after taking its first
snapshot. The remote READ ONLY DEFERRABLE transaction waits for the
local transaction to finish before obtaining a safe snapshot, while the
local transaction waits for the remote query.

I'm not sure whether this is something we should fix or just consider an
operational mistake, but I wanted to share the case.

This is expected behavior, so I would say it would be that mistake.

(5) Deferred remote triggers can write after switching to READ ONLY

pgfdw_xact_callback() sends COMMIT without synchronizing the
read-only mode, so a deferred trigger on the remote server can still run
in READ WRITE mode.

Fixed.

Attached is a patch for that. I will add test cases for these in the
next version.

Best regards,
Etsuro Fujita

Attachments:

t253733_5
postgres_fdw-Fix-corner-cases-in-xact-mode-inh-v1.patchapplication/octet-stream; name=postgres_fdw-Fix-corner-cases-in-xact-mode-inh-v1.patchDownload+101-16
#6Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Etsuro Fujita (#5)
Re: postgres_fdw: transaction mode inheritance corner cases

On Wed Sep 30, 2026 at 7:45 AM -03, Etsuro Fujita wrote:

Attached is a patch for that. I will add test cases for these in the
next version.

Hi, thanks for the patch! I tested it and I think that I may have found
two issues:

1: read-write local transactions can no longer query a hot standby

If I create a foreign server pointing to a standby, sending an explicit
READ WRITE makes the standby reject the remote START TRANSACTION. A
plain SELECT from a foreign table on a standby now fails, including in
autocommit, because the local transaction is read-write by default. It
works on unpatched master.

Repro:

-- on the primary (port 5433 is running a standby server)
create extension postgres_fdw;
create table t(a int);
insert into t values (1),(2);
create server sb foreign data wrapper postgres_fdw
options (dbname 'postgres', port '5433');
create user mapping for current_user server sb;
create foreign table fsb(a int) server sb options (table_name 't');

select * from fsb;
ERROR: 0A000: cannot set transaction read-write mode during recovery
CONTEXT: remote SQL command: START TRANSACTION ISOLATION LEVEL REPEATABLE READ READ WRITE NOT DEFERRABLE

begin read only;
select * from fsb; -- works
commit;

I'm not sure how much common is querying a standby through postgres_fdw,
but I've already seen some cases, so I'm wondering if this needs some
handling, what do you think?

2: a foreign cursor first fetched in a rolled-back savepoint breaks at COMMIT

Repro:

begin; declare c cursor for select * from ft;
savepoint s1; fetch 1 from c; rollback to s1;
fetch all from c; commit;
ERROR: 34000: cursor "c1" does not exist
CONTEXT: remote SQL command: CLOSE c1

This also works on unpatched master. There, the remote cursor is created
lazily at the first FETCH, without a remote savepoint, so it lives at
remote level 1 and survives ROLLBACK TO s1. With the patch, the new
begin_remote_xact() call in create_cursor opens a remote SAVEPOINT s2
and creates the cursor inside it. ROLLBACK TO s1 then destroys the
remote cursor while the local side still thinks it exists.

If the first FETCH happens before the savepoint, the same script works
with the patch. I think the remote cursor needs to be created at the
level where the scan started, or the remote/local cursor state needs to
be reconciled some other way.

Also, I didn't tested this case but on execute_foreign_modify and
direct-modify results are read without going through
begin_remote_xact(). So I'm wondering if a volatile function that runs
SET TRANSACTION READ ONLY in the middle of a single INSERT ... SELECT
f() could bypass the sync.

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

#7Nikolay Samokhvalov
nik@postgres.ai
In reply to: Matheus Alcantara (#6)
Re: postgres_fdw: transaction mode inheritance corner cases

On Wed, Sep 30, 2026 at 11:27 AM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

With the patch, the new begin_remote_xact() call in create_cursor opens a
remote SAVEPOINT s2 and creates the cursor inside it. ROLLBACK TO s1 then
destroys the remote cursor while the local side still thinks it exists.

Thanks, Matheus. My AI harness for testing reproduced this on
REL_19_STABLE at 9e73b209 with Etsuro's v1 patch and prepared the
attached incremental patch. It declares the remote cursor before
advancing the remote savepoint level, then synchronizes the transaction
mode before FETCH. The second FETCH fails with 34000 on v1 and succeeds
with this patch.

The postgres_fdw suite passes (4/4). This does not address the hot
standby case, which needs a separate fix.

Nik

Attachments:

v1-0001-postgres_fdw-preserve-outer-cursors-on-rollback.patchapplication/x-patch; name=v1-0001-postgres_fdw-preserve-outer-cursors-on-rollback.patchDownload+41-15
#8Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Matheus Alcantara (#6)
Re: postgres_fdw: transaction mode inheritance corner cases

On Thu, Oct 1, 2026 at 3:27 AM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

1: read-write local transactions can no longer query a hot standby

Ah, I think this is too restrictive, so I changed my mind; I'd like to
propose to keep the current behavior and instead modify the
documentation like this:

2: a foreign cursor first fetched in a rolled-back savepoint breaks at COMMIT

Repro:

begin; declare c cursor for select * from ft;
savepoint s1; fetch 1 from c; rollback to s1;
fetch all from c; commit;
ERROR: 34000: cursor "c1" does not exist
CONTEXT: remote SQL command: CLOSE c1

This also works on unpatched master. There, the remote cursor is created
lazily at the first FETCH, without a remote savepoint, so it lives at
remote level 1 and survives ROLLBACK TO s1. With the patch, the new
begin_remote_xact() call in create_cursor opens a remote SAVEPOINT s2
and creates the cursor inside it. ROLLBACK TO s1 then destroys the
remote cursor while the local side still thinks it exists.

Reproduced here. I think your analysis is correct, but I noticed that
this is an existing issue in postgres_fdw even in v18 and older. Here
is an example:

begin;
declare c cursor for select * from ft1;
savepoint s;
select * from ft1;
a | b
---+---
1 | 1
2 | 2
(2 rows)

fetch 2 from c;
a | b
---+---
1 | 1
2 | 2
(2 rows)

rollback to s;
release savepoint s;
commit;
ERROR: cursor "c1" does not exist
CONTEXT: remote SQL command: CLOSE c1

Also, I didn't tested this case but on execute_foreign_modify and
direct-modify results are read without going through
begin_remote_xact(). So I'm wondering if a volatile function that runs
SET TRANSACTION READ ONLY in the middle of a single INSERT ... SELECT
f() could bypass the sync.

DML statements are prevented on the local server if in READ ONLY mode,
so those functions are never run in that mode. No?

Thanks for the review!

Best regards,
Etsuro Fujita

#9Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Nikolay Samokhvalov (#7)
Re: postgres_fdw: transaction mode inheritance corner cases

On Fri, Oct 2, 2026 at 1:47 AM Nikolay Samokhvalov <nik@postgres.ai> wrote:

On Wed, Sep 30, 2026 at 11:27 AM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

With the patch, the new begin_remote_xact() call in create_cursor opens a
remote SAVEPOINT s2 and creates the cursor inside it. ROLLBACK TO s1 then
destroys the remote cursor while the local side still thinks it exists.

Thanks, Matheus. My AI harness for testing reproduced this on
REL_19_STABLE at 9e73b209 with Etsuro's v1 patch and prepared the
attached incremental patch. It declares the remote cursor before
advancing the remote savepoint level, then synchronizes the transaction
mode before FETCH. The second FETCH fails with 34000 on v1 and succeeds
with this patch.

Will look into the patch. Thanks!

Best regards,
Etsuro Fujita

#10Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Etsuro Fujita (#8)
Re: postgres_fdw: transaction mode inheritance corner cases

On Fri, Oct 2, 2026 at 2:30 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:

On Thu, Oct 1, 2026 at 3:27 AM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

1: read-write local transactions can no longer query a hot standby

Ah, I think this is too restrictive, so I changed my mind; I'd like to
propose to keep the current behavior and instead modify the
documentation like this:

Sorry I forgot this example:

Local READ ONLY transactions propagate their read-only mode to remote
sessions. (This is also applied to subtransactions.) Note that this
does not prevent login triggers executed on remote servers from
writing.
Also, local DEFERRABLE transactions propagate their deferrable mode to
remote sessions. (This is only applied to remote servers 9.1 and
newer.)

Best regards,
Etsuro Fujita

#11Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Etsuro Fujita (#9)
Re: postgres_fdw: transaction mode inheritance corner cases

On Fri, Oct 2, 2026 at 2:32 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:

On Fri, Oct 2, 2026 at 1:47 AM Nikolay Samokhvalov <nik@postgres.ai> wrote:

My AI harness for testing reproduced this on
REL_19_STABLE at 9e73b209 with Etsuro's v1 patch and prepared the
attached incremental patch. It declares the remote cursor before
advancing the remote savepoint level, then synchronizes the transaction
mode before FETCH. The second FETCH fails with 34000 on v1 and succeeds
with this patch.

Will look into the patch.

I think the patch assumes that create_cursor() is called at the same
transaction nesting depth as the local cursor, but that doesn't always
hold; for eg, the case I showed yesterday, that doesn't hold, so it
still fails. So it's a partial solution as proposed. Rather than
complicating the code, I'd like to propose to fix this by just
disallowing first fetching of a cursor within a deeper subtransaction
than it was created in. Here is an updated version for that. This is
an existing issue, so I split it into two:

* v2-0001-Fix-open-cursor-handling.patch
This addresses the existing issue by disallowing the fetching (and the
issue #1 reported by Fujii-san as a side effect).

* v2-0002-Fix-xact-prop-issues.patch
This addresses the remaining issues #2, #3 and #5 reported by
Fujii-san (#4 is not a bug). I will add test cases next.

Best regards,
Etsuro Fujita

Attachments:

t253733_11
v2-0001-Fix-open-cursor-handling.patchapplication/octet-stream; name=v2-0001-Fix-open-cursor-handling.patchDownload+77-10
v2-0002-Fix-xact-prop-issues.patchapplication/octet-stream; name=v2-0002-Fix-xact-prop-issues.patchDownload+54-15
#12Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Etsuro Fujita (#11)
Re: postgres_fdw: transaction mode inheritance corner cases

On Fri Oct 2, 2026 at 12:54 PM -03, Etsuro Fujita wrote:

On Fri, Oct 2, 2026 at 2:32 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:

On Fri, Oct 2, 2026 at 1:47 AM Nikolay Samokhvalov <nik@postgres.ai> wrote:

My AI harness for testing reproduced this on
REL_19_STABLE at 9e73b209 with Etsuro's v1 patch and prepared the
attached incremental patch. It declares the remote cursor before
advancing the remote savepoint level, then synchronizes the transaction
mode before FETCH. The second FETCH fails with 34000 on v1 and succeeds
with this patch.

Will look into the patch.

I think the patch assumes that create_cursor() is called at the same
transaction nesting depth as the local cursor, but that doesn't always
hold; for eg, the case I showed yesterday, that doesn't hold, so it
still fails. So it's a partial solution as proposed. Rather than
complicating the code, I'd like to propose to fix this by just
disallowing first fetching of a cursor within a deeper subtransaction
than it was created in. Here is an updated version for that. This is
an existing issue, so I split it into two:

* v2-0001-Fix-open-cursor-handling.patch
This addresses the existing issue by disallowing the fetching (and the
issue #1 reported by Fujii-san as a side effect).

* v2-0002-Fix-xact-prop-issues.patch
This addresses the remaining issues #2, #3 and #5 reported by
Fujii-san (#4 is not a bug). I will add test cases next.

Thanks for the v2 patches! I tested them and the hot standby issue is
fixed by 0002, and the deferred trigger case works as expected. I found
two problems with 0001, 0002 looks good to me.

1: the check in 0001 doesn't cover sibling savepoints

Since created_at only keeps the nesting depth, a cursor declared in one
savepoint and first fetched in a sibling savepoint at the same depth
passes the check:

begin;
savepoint s1;
declare c cursor for select * from ft;
release s1;
savepoint s2;
fetch 1 from c;
rollback to s2;
fetch all from c;
commit;
ERROR: 34000: cursor "c1" does not exist
CONTEXT: remote SQL command: CLOSE c1

2: it rejects cases that work on master

A PL/pgSQL refcursor that is opened outside an exception block and first
fetched inside it works on master, but fails with 0001 with the new
error. It also fails if the exception handler swallows errors: the new
error is hidden inside the block, the portal is left failed, and the
later fetch outside the block fails with a confusing 'portal "<unnamed
portal 2>" cannot be run'. On master this works because no remote
savepoint exists yet, so the remote cursor is created at remote level 1.
If we keep this restriction, I'm wondering if needs a documentation note
and a release note, what do you think?

I'm attaching a prototype 0003 on top of 0001 and 0002 that fixes both
issues that I've mention. The idea is that the real problem is not the
local nesting depth, but whether the remote savepoint depth at the time
of the DECLARE is deeper than the level where the local cursor lives,
since rolling back a remote savepoint at or below that depth destroys
the remote cursor. So 0003 declares the remote cursor before
synchronizing the remote savepoint level, and raises the error only if
the current remote depth is deeper than the level of the local cursor.
To know that level it records the subtransaction ID and the nesting
level when the scan is created; if that subtransaction was already
released, it conservatively assumes the cursor lives at the top level.
With this, the cases above work, and your earlier example, where another
scan advances the remote savepoint level before the first fetch, still
errors. The postgres_fdw tests pass, and I adjusted the cursor tests of
0001 accordingly.

It's a prototype, I haven't tested the async path beyond the existing
tests. What do you think?

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

Attachments:

t253733_12
v2-0001-Fix-open-cursor-handling.patchtext/plain; charset=utf-8; name=v2-0001-Fix-open-cursor-handling.patchDownload+77-10
v2-0002-Fix-xact-prop-issues.patchtext/plain; charset=utf-8; name=v2-0002-Fix-xact-prop-issues.patchDownload+54-15
v2-0003-Refine-open-cursor-handling.patchtext/plain; charset=utf-8; name=v2-0003-Refine-open-cursor-handling.patchDownload+110-13
#13Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Matheus Alcantara (#12)
Re: postgres_fdw: transaction mode inheritance corner cases

On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

On Fri Oct 2, 2026 at 12:54 PM -03, Etsuro Fujita wrote:

Here is an updated version for that. This is
an existing issue, so I split it into two:

* v2-0001-Fix-open-cursor-handling.patch
This addresses the existing issue by disallowing the fetching (and the
issue #1 reported by Fujii-san as a side effect).

* v2-0002-Fix-xact-prop-issues.patch
This addresses the remaining issues #2, #3 and #5 reported by
Fujii-san (#4 is not a bug). I will add test cases next.

Thanks for the v2 patches! I tested them and the hot standby issue is
fixed by 0002, and the deferred trigger case works as expected. I found
two problems with 0001, 0002 looks good to me.

Thanks for reviewing!

I added the test cases to 0002. Attached is a new version of the
patch. (It actually doesn't depend on 0001, so I'm only attaching
0002.) I will push/backpatch the new version first if no objections
from others.

As for 0001, I also noticed problem #1 after sending the email...
0001 is an existing issue, so I will return to it, including your
patch, after closing this open item. Thanks for the patch!

Best regards,
Etsuro Fujita

Attachments:

t253733_13
v3-0002-Fix-xact-prop-issues.patchapplication/octet-stream; name=v3-0002-Fix-xact-prop-issues.patchDownload+106-23
#14Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Etsuro Fujita (#13)
Re: postgres_fdw: transaction mode inheritance corner cases

On Sat, Oct 3, 2026 at 9:04 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:

On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

On Fri Oct 2, 2026 at 12:54 PM -03, Etsuro Fujita wrote:

Here is an updated version for that. This is
an existing issue, so I split it into two:

* v2-0001-Fix-open-cursor-handling.patch
This addresses the existing issue by disallowing the fetching (and the
issue #1 reported by Fujii-san as a side effect).

* v2-0002-Fix-xact-prop-issues.patch
This addresses the remaining issues #2, #3 and #5 reported by
Fujii-san (#4 is not a bug). I will add test cases next.

Thanks for the v2 patches! I tested them and the hot standby issue is
fixed by 0002, and the deferred trigger case works as expected. I found
two problems with 0001, 0002 looks good to me.

I added the test cases to 0002. Attached is a new version of the
patch. (It actually doesn't depend on 0001, so I'm only attaching
0002.) I will push/backpatch the new version first if no objections
from others.

Done.

As for 0001, I also noticed problem #1 after sending the email...
0001 is an existing issue, so I will return to it, including your
patch, after closing this open item.

I closed it and added the existing issue to Live issues.

Best regards,
Etsuro Fujita

#15Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Etsuro Fujita (#14)
Re: postgres_fdw: transaction mode inheritance corner cases

On 05/10/26 05:22, Etsuro Fujita wrote:

On Sat, Oct 3, 2026 at 9:04 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:

On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

On Fri Oct 2, 2026 at 12:54 PM -03, Etsuro Fujita wrote:

Here is an updated version for that. This is
an existing issue, so I split it into two:

* v2-0001-Fix-open-cursor-handling.patch
This addresses the existing issue by disallowing the fetching (and the
issue #1 reported by Fujii-san as a side effect).

* v2-0002-Fix-xact-prop-issues.patch
This addresses the remaining issues #2, #3 and #5 reported by
Fujii-san (#4 is not a bug). I will add test cases next.

Thanks for the v2 patches! I tested them and the hot standby issue is
fixed by 0002, and the deferred trigger case works as expected. I found
two problems with 0001, 0002 looks good to me.

I added the test cases to 0002. Attached is a new version of the
patch. (It actually doesn't depend on 0001, so I'm only attaching
0002.) I will push/backpatch the new version first if no objections
from others.

Done.

As for 0001, I also noticed problem #1 after sending the email...
0001 is an existing issue, so I will return to it, including your
patch, after closing this open item.

I closed it and added the existing issue to Live issues.

Thank you!

Are you still planning to review 0001 and 0003 on this thread or
should I start a new one to discuss these patches?

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

#16Nikolay Samokhvalov
nik@postgres.ai
In reply to: Matheus Alcantara (#12)
Re: postgres_fdw: transaction mode inheritance corner cases

On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

So 0003 declares the remote cursor before
synchronizing the remote savepoint level, and raises the error only if
the current remote depth is deeper than the level of the local cursor.

There is another case 0003 misses: parameter evaluation
can open a remote savepoint after create_cursor() checks the depth.

With 0001 and 0003 on REL_19_STABLE at a2148471, run this in a fresh
cursor_min database. Pass its socket directory and port as psql
variables sock and port:

create extension postgres_fdw;

create table t (id int);
insert into t values (1);

create server s foreign data wrapper postgres_fdw options (dbname
'cursor_min', host :'sock', port :'port');
create user mapping for current_user server s;
create foreign table ft (id int) server s options (table_name 't',
fetch_size '1');
create foreign table fa (id int) server s options (table_name 't');

begin;
declare c cursor for select * from ft where id = (select id from fa limit 1);
savepoint sp;
fetch c;
rollback to sp;
fetch c;
commit;

With 0001 alone, the first fetch is rejected by its depth check. With
0003, it returns 1, but the second fetch fails after rollback: cursor
"c2" does not exist. On clean REL_19_STABLE, the second fetch returns
no rows and commit succeeds.

The subquery becomes an initplan for the outer scan's $1 parameter.
process_query_params() runs it after the depth check. Its scan opens a
remote savepoint, so the outer cursor is declared inside it and removed
by rollback to sp.

Nik

#17Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Matheus Alcantara (#15)
Re: postgres_fdw: transaction mode inheritance corner cases

On Tue, Oct 6, 2026 at 9:21 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

On 05/10/26 05:22, Etsuro Fujita wrote:

As for 0001, I also noticed problem #1 after sending the email...
0001 is an existing issue, so I will return to it, including your
patch, after closing this open item.

I closed it and added the existing issue to Live issues.

Are you still planning to review 0001 and 0003 on this thread or
should I start a new one to discuss these patches?

Will do on this thread. It has been added to Live issues [1]https://wiki.postgresql.org/wiki/PostgreSQL_19_Open_Items#Live_issues ("Open
cursors querying postgres_fdw foreign tables not handled properly"),
so I think it's better to keep using it rather than creating a new
thread, for easier management.

Best regards,
Etsuro Fujita

[1]: https://wiki.postgresql.org/wiki/PostgreSQL_19_Open_Items#Live_issues

#18Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Matheus Alcantara (#12)
Re: postgres_fdw: transaction mode inheritance corner cases

On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

1: the check in 0001 doesn't cover sibling savepoints

Since created_at only keeps the nesting depth, a cursor declared in one
savepoint and first fetched in a sibling savepoint at the same depth
passes the check:

begin;
savepoint s1;
declare c cursor for select * from ft;
release s1;
savepoint s2;
fetch 1 from c;
rollback to s2;
fetch all from c;
commit;
ERROR: 34000: cursor "c1" does not exist
CONTEXT: remote SQL command: CLOSE c1

As I said upthread, I noticed this after sending the patch.

2: it rejects cases that work on master

A PL/pgSQL refcursor that is opened outside an exception block and first
fetched inside it works on master, but fails with 0001 with the new
error. It also fails if the exception handler swallows errors: the new
error is hidden inside the block, the portal is left failed, and the
later fetch outside the block fails with a confusing 'portal "<unnamed
portal 2>" cannot be run'. On master this works because no remote
savepoint exists yet, so the remote cursor is created at remote level 1.

This isn't great; I think we should support this as much as possible.

I'm attaching a prototype 0003 on top of 0001 and 0002 that fixes both
issues that I've mention. The idea is that the real problem is not the
local nesting depth, but whether the remote savepoint depth at the time
of the DECLARE is deeper than the level where the local cursor lives,
since rolling back a remote savepoint at or below that depth destroys
the remote cursor. So 0003 declares the remote cursor before
synchronizing the remote savepoint level, and raises the error only if
the current remote depth is deeper than the level of the local cursor.
To know that level it records the subtransaction ID and the nesting
level when the scan is created; if that subtransaction was already
released, it conservatively assumes the cursor lives at the top level.

As demonstrated by Nikolay, the 0003 patch doesn't guarantee the
local/remote cursor-level synchronization, still causing an error:
"cursor "cN" does not exist", which isn't good. In addition to that,
I think the proposed handling using the subtransaction ID makes the
fetchability of remote cursors restrictive, reducing the compatibility
with the previous behavior than necessary. So sorry, I don't think
0003 is the right way to go.

I updated the 0001 patch to suppress the "cursor "cN" does not exist"
error while keeping the previous behavior as much as possible,
allowing cursors opened before a savepoint to be first fetched after
that savepoint. Attached is an updated patch. I'm wondering if the
patch should be master-only, though, because 1) it is rather
large/invasive and 2) there is no field report about this open-cursor
issue IIRC. Anyway I'll add more test cases next.

Best regards,
Etsuro Fujita

Attachments:

t253733_18
v3-0001-Fix-open-cursor-handling.patchapplication/octet-stream; name=v3-0001-Fix-open-cursor-handling.patchDownload+336-12
#19Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Etsuro Fujita (#18)
Re: postgres_fdw: transaction mode inheritance corner cases

On Tue Oct 13, 2026 at 11:54 AM -03, Etsuro Fujita wrote:

I'm attaching a prototype 0003 on top of 0001 and 0002 that fixes both
issues that I've mention. The idea is that the real problem is not the
local nesting depth, but whether the remote savepoint depth at the time
of the DECLARE is deeper than the level where the local cursor lives,
since rolling back a remote savepoint at or below that depth destroys
the remote cursor. So 0003 declares the remote cursor before
synchronizing the remote savepoint level, and raises the error only if
the current remote depth is deeper than the level of the local cursor.
To know that level it records the subtransaction ID and the nesting
level when the scan is created; if that subtransaction was already
released, it conservatively assumes the cursor lives at the top level.

As demonstrated by Nikolay, the 0003 patch doesn't guarantee the
local/remote cursor-level synchronization, still causing an error:
"cursor "cN" does not exist", which isn't good. In addition to that,
I think the proposed handling using the subtransaction ID makes the
fetchability of remote cursors restrictive, reducing the compatibility
with the previous behavior than necessary. So sorry, I don't think
0003 is the right way to go.

No problem, thanks for the feedback! I agree with you and Nikolay about
the initplan case, I was checking the depth too early.

I updated the 0001 patch to suppress the "cursor "cN" does not exist"
error while keeping the previous behavior as much as possible,
allowing cursors opened before a savepoint to be first fetched after
that savepoint. Attached is an updated patch. I'm wondering if the
patch should be master-only, though, because 1) it is rather
large/invasive and 2) there is no field report about this open-cursor
issue IIRC. Anyway I'll add more test cases next.

Thanks for the new patch version.

I tested v3-0001, the postgres_fdw tests pass and it fixes all the
"cursor does not exist" failures that I could reproduce, including
Nikolay's initplan case and the sibling savepoint case. But while stress
testing it I found two cases that crash the server.

1: crash on a cursor over a pushed-down join

create_cursor() uses RelationGetRelationName(fsstate->rel) in the new
error, but fsstate->rel is NULL when the scan is for a pushed-down join
or aggregate:

create table t(a int);
insert into t values (1),(2),(3),(4);
create foreign table ft(a int) server loopback options (table_name 't');
create foreign table ft2(a int) server loopback options (table_name 't');

alter server loopback options (add use_remote_estimate 'true');
analyze t;
begin;
declare c cursor for select ft.a from ft join ft2 on ft.a = ft2.a order by 1;
savepoint s; fetch 1 from c; rollback to s;
fetch 1 from c;
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.

2: stale ForeignScanHash entries after a failed portal

An entry is removed only by postgresEndForeignScan or when the
subtransaction that created the scan aborts (or at transaction end). But
if an error happens while the scan of an outer-level cursor is fetched
inside a savepoint, the portal is marked failed and the executor doesn't
call EndForeignScan, so the entry is left pointing to memory that is
freed later. See it:

begin;
declare c cursor for select 1/(a-3) from ft order by a;
fetch 1 from c;
savepoint s2; fetch 5 from c;
-- ERROR: division by zero
rollback to s2;
close c;
savepoint s3; select 1; release s3;
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.

The subtransaction callback dereferences node->fdw_state of the freed
node. If I stop after "rollback to s2" and just commit, I get "WARNING:
ForeignScan node 0x... still existing". If I close the cursor and run
more foreign queries in the same transaction, I get "ERROR: duplicate
ForeignScan node" (presumably a new scan reuses the freed address) and
then a crash. I get the same WARNING with a PL/pgSQL refcursor fetched
inside an exception block.

Some other things that look inconsistent to me:

3: the check for "can't scan anymore" throws away rows that are already
in the local buffer. For example, "declare c; savepoint s; fetch 1 from
c; rollback to s; fetch all from c" works on master, because the first
fetch already brought the whole result into memory (for small results),
but fails with v3-0001 with 'cannot scan foreign table "ft" anymore',
even though no remote access is needed. The same happens with a PL/pgSQL
refcursor first fetched inside an exception block that raises and is
caught, then fetched again outside. This works on master but fails now,
and if the handler swallows the new error, the portal is left failed and
a retry loop gets 'portal "<unnamed portal 1>" cannot be run' on the
following iterations.

4: I haven't tested this, but reading the code, scan_allowed is never
set back to true, even if a rescan with changed parameters would create
a fresh cursor anyway.

5: I think the error could use ERRCODE_INVALID_CURSOR_STATE with a
detail explaining that the remote cursor was removed by rolling back a
savepoint, instead of ERRCODE_FEATURE_NOT_SUPPORTED, and that the
WARNING about leftover scans at commit should go away since, as in 2, a
failed portal can legitimately leave a scan behind at that point.

6: fs_level and cursor_level track two different things and there is no
comment saying that, and I think the hash table needs a comment
explaining why it exists.

I think that 1 and 2 are easy to fix on top of what you have. For 2, the
scan can register a memory context reset callback on the executor's
memory context in postgresBeginForeignScan, which removes its hash entry
when that memory is freed, even if EndForeignScan is never called. For
1, the error just shouldn't assume there is a single relation, for
example by using a generic message when fsstate->rel is NULL. I tried
this locally and it fixes both crashes, and the postgres_fdw tests pass.
I also added regression tests for both, and I checked that they crash
the server without the fix.

If you want, I can send a v4 with these changes that I've mention.

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

#20Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Matheus Alcantara (#19)
Re: postgres_fdw: transaction mode inheritance corner cases

On Thu, Oct 15, 2026 at 1:13 AM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

I tested v3-0001, the postgres_fdw tests pass and it fixes all the
"cursor does not exist" failures that I could reproduce, including
Nikolay's initplan case and the sibling savepoint case. But while stress
testing it I found two cases that crash the server.

Thanks for reviewing!

1: crash on a cursor over a pushed-down join

create_cursor() uses RelationGetRelationName(fsstate->rel) in the new
error, but fsstate->rel is NULL when the scan is for a pushed-down join
or aggregate:

Good catch!

2: stale ForeignScanHash entries after a failed portal

An entry is removed only by postgresEndForeignScan or when the
subtransaction that created the scan aborts (or at transaction end). But
if an error happens while the scan of an outer-level cursor is fetched
inside a savepoint, the portal is marked failed and the executor doesn't
call EndForeignScan, so the entry is left pointing to memory that is
freed later. See it:

I couldn't reproduce this in my environment. Could you provide the
reproducer in more detail including the foreign table definition, the
postgres_fdw options, ...?

Some other things that look inconsistent to me:

3: the check for "can't scan anymore" throws away rows that are already
in the local buffer. For example, "declare c; savepoint s; fetch 1 from
c; rollback to s; fetch all from c" works on master, because the first
fetch already brought the whole result into memory (for small results),
but fails with v3-0001 with 'cannot scan foreign table "ft" anymore',
even though no remote access is needed. The same happens with a PL/pgSQL
refcursor first fetched inside an exception block that raises and is
caught, then fetched again outside. This works on master but fails now,
and if the handler swallows the new error, the portal is left failed and
a retry loop gets 'portal "<unnamed portal 1>" cannot be run' on the
following iterations.

I thought it might be confusing to users that postgres_fdw would
behave differently depending on the fetch_size setting, but as pointed
out by you, that would lead to less compatibility with the previous
behavior. Will remove this restriction.

4: I haven't tested this, but reading the code, scan_allowed is never
set back to true, even if a rescan with changed parameters would create
a fresh cursor anyway.

Will remove this restriction as well.

5: I think the error could use ERRCODE_INVALID_CURSOR_STATE with a
detail explaining that the remote cursor was removed by rolling back a
savepoint, instead of ERRCODE_FEATURE_NOT_SUPPORTED, and that the
WARNING about leftover scans at commit should go away since, as in 2, a
failed portal can legitimately leave a scan behind at that point.

I'm not sure. I think this is rather an implementation restriction in
postgres_fdw, so I don't think that ERRCODE_FEATURE_NOT_SUPPORTED is a
bad choice. I agree with improving the error message, though.

6: fs_level and cursor_level track two different things and there is no
comment saying that, and I think the hash table needs a comment
explaining why it exists.

Will do.

I think that 1 and 2 are easy to fix on top of what you have. For 2, the
scan can register a memory context reset callback on the executor's
memory context in postgresBeginForeignScan, which removes its hash entry
when that memory is freed, even if EndForeignScan is never called. For
1, the error just shouldn't assume there is a single relation, for
example by using a generic message when fsstate->rel is NULL. I tried
this locally and it fixes both crashes, and the postgres_fdw tests pass.
I also added regression tests for both, and I checked that they crash
the server without the fix.

If you want, I can send a v4 with these changes that I've mention.

Thanks for working on the fix! It would be great if you share it.

Best regards,
Etsuro Fujita

#21Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Etsuro Fujita (#20)
#22Etsuro Fujita
etsuro.fujita@gmail.com
In reply to: Matheus Alcantara (#21)
#23Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Etsuro Fujita (#22)