postgres_fdw: transaction mode inheritance corner cases
postgres_fdw: transaction mode inheritance corner cases
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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Nathan Bossart <nathandbossart@gmail.com>
Дата:
[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 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Thu, Sep 17, 2026 at 12:44 AM Nathan Bossart 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 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
Re: postgres_fdw: transaction mode inheritance corner cases
On Thu, Sep 10, 2026 at 9:34 AM Fujii Masao 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
"Matheus Alcantara" <matheusssilv97@gmail.com>
Дата:
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
Re: postgres_fdw: transaction mode inheritance corner cases
On Wed, Sep 30, 2026 at 11:27 AM Matheus Alcantara 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Thu, Oct 1, 2026 at 3:27 AM Matheus Alcantara 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Fri, Oct 2, 2026 at 1:47 AM Nikolay Samokhvalov wrote: > On Wed, Sep 30, 2026 at 11:27 AM Matheus Alcantara > 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Fri, Oct 2, 2026 at 2:30 AM Etsuro Fujita wrote: > On Thu, Oct 1, 2026 at 3:27 AM Matheus Alcantara > 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
Re: postgres_fdw: transaction mode inheritance corner cases
On Fri, Oct 2, 2026 at 2:32 AM Etsuro Fujita wrote: > On Fri, Oct 2, 2026 at 1:47 AM Nikolay Samokhvalov 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
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 wrote: >> On Fri, Oct 2, 2026 at 1:47 AM Nikolay Samokhvalov 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 "" 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
Re: postgres_fdw: transaction mode inheritance corner cases
On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Sat, Oct 3, 2026 at 9:04 PM Etsuro Fujita wrote: > On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara > 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Matheus Alcantara <matheusssilv97@gmail.com>
Дата:
On 05/10/26 05:22, Etsuro Fujita wrote: > On Sat, Oct 3, 2026 at 9:04 PM Etsuro Fujita wrote: >> On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara >> 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Tue, Oct 6, 2026 at 9:21 PM Matheus Alcantara
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] ("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
Re: postgres_fdw: transaction mode inheritance corner cases
On Sat, Oct 3, 2026 at 6:38 PM Matheus Alcantara 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 " 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
"Matheus Alcantara" <matheusssilv97@gmail.com>
Дата:
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 "" 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
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Thu, Oct 15, 2026 at 1:13 AM Matheus Alcantara 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 "" 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
Re: postgres_fdw: transaction mode inheritance corner cases
On Fri Oct 16, 2026 at 9:10 AM -03, Etsuro Fujita wrote: >> 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, ...? > create extension postgres_fdw; create server loopback foreign data wrapper postgres_fdw options (dbname 'postgres', port '5432'); create user mapping for current_user server loopback; 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'); begin; declare c cursor for select 1 / (a - 3) from ft order by a; fetch 1 from c; savepoint s2; fetch 5 from c; rollback to s2; commit; After the COMMIT command it produces: WARNING: 01000: ForeignScan node 0x106019368 still existing LOCATION: AtEOXact_ForeignScan, postgres_fdw.c:4381 The details that matter are that the first "fetch 1" happens before the savepoint, so IIUC the scan and its cursor belong to the outer level, and that the error happens while fetching inside the savepoint. The expression 1 / (a - 3) is not pushed down, so the division by zero is raised locally while the scan returns rows, and the portal is left in the failed state. If I add this after "rollback to s2" and before "commit": close c; savepoint s3; select 1; release s3; the backend crashes in the subtransaction callback. > Thanks for working on the fix! It would be great if you share it. > I'm attaching the v4 patch. It is your v3-0001 plus the fixes from my previous email that you agree. Since you said you'd remove the restrictions of 3 and 4, and add the comments of 6, I went ahead and did them in this version. A few notes: - for 1, the error no longer uses the relation name when fsstate->rel is NULL. - for 2, every scan registers a memory context reset callback on its executor memory context, which removes its hash entry when that memory is freed, even if EndForeignScan is never called. I also removed the WARNING about leftover scans at commit, since a failed portal can legitimately leave one behind at that point. Please let me know if you disagree with that. - for 3 and 4, scan_allowed is replaced by a cursor_lost flag: when a savepoint rollback removes the remote cursor, the scan can still return the rows that are already in its buffer, and the error is only raised when a new remote fetch is needed. A rescan of such a scan either reuses what it has in memory or forgets the cursor so that the next fetch creates a new one. - for 5, I kept ERRCODE_FEATURE_NOT_SUPPORTED as you noted, and only improved the message. - for 6, I added the comments, and while doing it I dropped fs_level, since with the reset callback it wasn't needed anymore: the hash only holds the scan pointer and all the level tracking is in cursor_level. - I added tests for the pushed-down join, the failed portal case, a small fetch_size where more rows can't be fetched, the rescan of a scan with a lost cursor, sibling and nested savepoints, Nikolay's initplan case, a PL/pgSQL refcursor and an async scan. -- Matheus Alcantara EDB: https://www.enterprisedb.com
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Sat, Oct 17, 2026 at 12:57 AM Matheus Alcantara wrote: > On Fri Oct 16, 2026 at 9:10 AM -03, Etsuro Fujita wrote: > >> 2: stale ForeignScanHash entries after a failed portal > > 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, ...? > create extension postgres_fdw; > create server loopback foreign data wrapper postgres_fdw options (dbname 'postgres', port '5432'); > create user mapping for current_user server loopback; > 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'); > > begin; > declare c cursor for select 1 / (a - 3) from ft order by a; > fetch 1 from c; > savepoint s2; > fetch 5 from c; > rollback to s2; > commit; > > After the COMMIT command it produces: > > WARNING: 01000: ForeignScan node 0x106019368 still existing > LOCATION: AtEOXact_ForeignScan, postgres_fdw.c:4381 > > The details that matter are that the first "fetch 1" happens before the > savepoint, so IIUC the scan and its cursor belong to the outer level, > and that the error happens while fetching inside the savepoint. The > expression 1 / (a - 3) is not pushed down, so the division by zero is > raised locally while the scan returns rows, and the portal is left in > the failed state. If I add this after "rollback to s2" and before > "commit": > > close c; > savepoint s3; > select 1; > release s3; > > the backend crashes in the subtransaction callback. Thanks for the detailed information! I could reproduce this. I was testing using the wrong patch, sorry. > > Thanks for working on the fix! It would be great if you share it. > I'm attaching the v4 patch. It is your v3-0001 plus the fixes from my > previous email that you agree. Since you said you'd remove the > restrictions of 3 and 4, and add the comments of 6, I went ahead and did > them in this version. Thanks for the patch! Will review. I think the patch is master-only, because 1) there is no field report about the series of open-cursor issues while they exist since the introduction of postgres_fdw, and 2) the patch is large/invasive, so I will return to this somewhere in the v20 development cycle after working on some other stuff. Best regards, Etsuro Fujita
Re: postgres_fdw: transaction mode inheritance corner cases
От:
Matheus Alcantara <matheusssilv97@gmail.com>
Дата:
On 19/10/26 06:22, Etsuro Fujita wrote: >> I'm attaching the v4 patch. It is your v3-0001 plus the fixes from my >> previous email that you agree. Since you said you'd remove the >> restrictions of 3 and 4, and add the comments of 6, I went ahead and did >> them in this version. > > Thanks for the patch! Will review. > > I think the patch is master-only, because 1) there is no field report > about the series of open-cursor issues while they exist since the > introduction of postgres_fdw, and 2) the patch is large/invasive, so I > will return to this somewhere in the v20 development cycle after > working on some other stuff. > Agree. Thank you! -- Matheus Alcantara EDB: https://www.enterprisedb.com