Re: Bypassing cursors in postgres_fdw to enable parallel plans
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Andy Fan <zhihuifan1213@163.com>
Дата:
Rafia Sabih writes:
Hi,
>
> At present, in postgres_fdw, if a query which is using a parallel plan is fired from the remote end fails to use the
> parallel plan locally because of the presence of CURSORS. Consider the following example,
...
>
> Now, to overcome this limitation, I have worked on this idea (suggested by my colleague Bernd Helmle) of bypassing the
> cursors.
Do you know why we can't use parallel plan when cursor is used? Is It
related to this code in ExecutePlan?
/*
* Set up parallel mode if appropriate.
*
* Parallel mode only supports complete execution of a plan. If we've
* already partially executed it, or if the caller asks us to exit early,
* we must force the plan to run without parallelism.
*/
if (queryDesc->already_executed || numberTuples != 0)
use_parallel_mode = false;
Actually I can't understand the comment as well and I had this
confusion for a long time.
--
Best Regards
Andy Fan
Re: Bypassing cursors in postgres_fdw to enable parallel plans
Hello hackers,
I am back at this work with a rebased and revised patch. The new version is rebased and has a change in approach.
Whenever we are using non-cursor mode, for the first cursor we are always saving the tuples
in the tuplestore, this is because we do not have any means to know beforehand how many cursors are required for the query.
And when we switch to the next query then we do not have a way to fetch the tuples for the previous query.
So, the tuples retrieved earlier for the first query were lost if not saved.
I would highly appreciate your time and feedback for this.
On Wed, 12 Mar 2025 at 12:57, Andy Fan <zhihuifan1213@163.com> wrote:
Rafia Sabih <rafia.pghackers@gmail.com> writes:
Hi,
>
> At present, in postgres_fdw, if a query which is using a parallel plan is fired from the remote end fails to use the
> parallel plan locally because of the presence of CURSORS. Consider the following example,
...
>
> Now, to overcome this limitation, I have worked on this idea (suggested by my colleague Bernd Helmle) of bypassing the
> cursors.
Do you know why we can't use parallel plan when cursor is used? Is It
related to this code in ExecutePlan?
/*
* Set up parallel mode if appropriate.
*
* Parallel mode only supports complete execution of a plan. If we've
* already partially executed it, or if the caller asks us to exit early,
* we must force the plan to run without parallelism.
*/
if (queryDesc->already_executed || numberTuples != 0)
use_parallel_mode = false;
Actually I can't understand the comment as well and I had this
confusion for a long time.
--
Best Regards
Andy Fan
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Wed, Mar 12, 2025 at 7:57 AM Andy Fan wrote: > Do you know why we can't use parallel plan when cursor is used? Is It > related to this code in ExecutePlan? Yes. When a cursor is used, the whole query isn't executed all at once, but rather the executor will be started and stopped for each fetch from the cursor. We can't keep the parallel workers running for that whole time, not just because it would be inefficient, but because it would be incorrect. State changes would be possible in the leader that were not reflected in the workers, leading to chaos. -- Robert Haas EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Sep 29, 2025 at 10:51 AM Rafia Sabih wrote: > I am back at this work with a rebased and revised patch. The new version is rebased and has a change in approach. > Whenever we are using non-cursor mode, for the first cursor we are always saving the tuples > in the tuplestore, this is because we do not have any means to know beforehand how many cursors are required for the query. This might have the advantage of being simpler, but it's definitely worse. If we're only fetching one result set, which will be common, we'll buffer the whole thing in a tuplestore where that could otherwise be avoided. Maybe it's still best to go with this approach; not sure. > And when we switch to the next query then we do not have a way to fetch the tuples for the previous query. > So, the tuples retrieved earlier for the first query were lost if not saved. > I would highly appreciate your time and feedback for this. My suggestions are to work on the following areas: 1. Automated testing. The patch has no regression tests, and won't get committed without those. 2. Manual testing. How does the performance with this new option compare to the existing method? The answer might be different for small result sets that fit in memory and large ones that spill to disk, and will certainly also depend on how productive parallel query can be on the remote side; but I think you want to do and post on this list some measurements showing the best and worst case for the patch. 3. Patch clean-up. There are plenty of typos and whitespace-only changes in the patch. It's best to clean those up. Running pgindent is a good idea too. Some places could use comments. -- Robert Haas EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Fri, 10 Oct 2025 at 22:02, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Mon, Sep 29, 2025 at 10:51 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> > I am back at this work with a rebased and revised patch. The new version is rebased and has a change in approach.
> > Whenever we are using non-cursor mode, for the first cursor we are always saving the tuples
> > in the tuplestore, this is because we do not have any means to know beforehand how many cursors are required for the query.
>
> This might have the advantage of being simpler, but it's definitely
> worse. If we're only fetching one result set, which will be common,
> we'll buffer the whole thing in a tuplestore where that could
> otherwise be avoided. Maybe it's still best to go with this approach;
> not sure.
>
> > And when we switch to the next query then we do not have a way to fetch the tuples for the previous query.
> > So, the tuples retrieved earlier for the first query were lost if not saved.
> > I would highly appreciate your time and feedback for this.
>
> My suggestions are to work on the following areas:
>
> 1. Automated testing. The patch has no regression tests, and won't get
> committed without those.
>
> 2. Manual testing. How does the performance with this new option
> compare to the existing method? The answer might be different for
> small result sets that fit in memory and large ones that spill to
> disk, and will certainly also depend on how productive parallel query
> can be on the remote side; but I think you want to do and post on this
> list some measurements showing the best and worst case for the patch.
>
> 3. Patch clean-up. There are plenty of typos and whitespace-only
> changes in the patch. It's best to clean those up. Running pgindent is
> a good idea too. Some places could use comments.
>
> --
> Robert Haas
> EDB: http://www.enterprisedb.com
Thank you Robert, for reviewing this patch. On going through the patch more, I realised this was not equipped to handle the cases when there are more than two active cursors. So to accommodate such a case, I now modified the new struct for saving the previous query to a list of such structs. Also, it turns out we need not to save the tuples in case this is an active cursor, so we only populate the associated tuplestore only when we need to create a new cursor when the old cursor is not completely done.
In this version I have added the regression tests as well. I wanted to test this patch for all the cases of postgres_fdw, the only way I could figure out how to do this was to test the select statements with the new GUC.
I also did some tests for performance. I used the contrib_regression database and populated the table "S1"."T1" with more tuples to understand the impact of patch on higher scale. I also used auto_explain to get the foreign plans.
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:35.825 CET [44338] LOG: duration: 61.336 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
2025-11-14 14:40:35.825 CET [44862] LOG: duration: 60.575 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT count(*) FROM "S 1"."T 1"
Aggregate (cost=21888.22..21888.23 rows=1 width=8)
-> Seq Scan on "T 1" (cost=0.00..19956.98 rows=772498 width=0)
count
--------
990821
(1 row)
Time: 62.728 ms
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
Time: 1.515 ms
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:46.260 CET [44862] LOG: duration: 21.875 ms plan:
Query Text: SELECT count(*) FROM "S 1"."T 1"
Finalize Aggregate (cost=17255.64..17255.65 rows=1 width=8)
-> Gather (cost=17255.43..17255.64 rows=2 width=8)
Workers Planned: 2
-> Partial Aggregate (cost=16255.43..16255.44 rows=1 width=8)
-> Parallel Seq Scan on "T 1" (cost=0.00..15450.74 rows=321874 width=0)
2025-11-14 14:40:46.260 CET [44338] LOG: duration: 22.623 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
count
--------
990821
(1 row)
Time: 24.862 ms
So for this query, the advantage is coming from parallel query which was otherwise not possible in this scenario.
To study more performance with this patch, I found another interesting query and here are the results,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");2025-11-14 15:57:46.893 CET [1946]
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=112311.578..112804.516 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp read=12754 written=12754
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.039..48.808 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=112310.386..112310.387 rows=990821.00 loops=1)
Buckets: 262144 (originally 1024) Batches: 8 (originally 1) Memory Usage: 6408kB
Buffers: temp written=2537
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=0.728..112030.241 rows=990821.00 loops=1)
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.398..710.505 rows=990821.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=0.082..0.082 rows=1.00 loops=990821)
Planning:
Buffers: shared hit=5
Planning Time: 2.211 ms
Execution Time: 112825.428 ms
(15 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=261.416..354.520 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp written=2660
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.021..35.531 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=261.381..261.383 rows=100.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 12kB
Buffers: temp written=2660
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=255.563..261.356 rows=100.00 loops=1)
Buffers: temp written=2660
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.433..0.443 rows=100.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=2.609..2.609 rows=1.00 loops=100)
Buffers: temp written=2660
Planning:
Buffers: shared hit=5
Planning Time: 2.284 ms
Execution Time: 389.358 ms
(17 rows)
So even in the case without a parallel plan, it is performing significantly better. I investigated a bit more to find out why the query was so slow with the cursors,
Time: 1.515 ms
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:46.260 CET [44862] LOG: duration: 21.875 ms plan:
Query Text: SELECT count(*) FROM "S 1"."T 1"
Finalize Aggregate (cost=17255.64..17255.65 rows=1 width=8)
-> Gather (cost=17255.43..17255.64 rows=2 width=8)
Workers Planned: 2
-> Partial Aggregate (cost=16255.43..16255.44 rows=1 width=8)
-> Parallel Seq Scan on "T 1" (cost=0.00..15450.74 rows=321874 width=0)
2025-11-14 14:40:46.260 CET [44338] LOG: duration: 22.623 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
count
--------
990821
(1 row)
Time: 24.862 ms
So for this query, the advantage is coming from parallel query which was otherwise not possible in this scenario.
To study more performance with this patch, I found another interesting query and here are the results,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");2025-11-14 15:57:46.893 CET [1946]
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=112311.578..112804.516 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp read=12754 written=12754
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.039..48.808 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=112310.386..112310.387 rows=990821.00 loops=1)
Buckets: 262144 (originally 1024) Batches: 8 (originally 1) Memory Usage: 6408kB
Buffers: temp written=2537
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=0.728..112030.241 rows=990821.00 loops=1)
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.398..710.505 rows=990821.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=0.082..0.082 rows=1.00 loops=990821)
Planning:
Buffers: shared hit=5
Planning Time: 2.211 ms
Execution Time: 112825.428 ms
(15 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=261.416..354.520 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp written=2660
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.021..35.531 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=261.381..261.383 rows=100.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 12kB
Buffers: temp written=2660
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=255.563..261.356 rows=100.00 loops=1)
Buffers: temp written=2660
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.433..0.443 rows=100.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=2.609..2.609 rows=1.00 loops=100)
Buffers: temp written=2660
Planning:
Buffers: shared hit=5
Planning Time: 2.284 ms
Execution Time: 389.358 ms
(17 rows)
So even in the case without a parallel plan, it is performing significantly better. I investigated a bit more to find out why the query was so slow with the cursors,
and came to understand that it is repeatedly abandoning and recreating the cursor via the code path of postgresReScanForeignScan.
So, it looks like cursor management itself costs this much more time.
To understand the impact of the patch in case of tuples spilled to disk, I tried following example,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# set enable_hashjoin = off;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=4537.437..4598.483 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=3748.488..4090.547 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1818.521..1865.792 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.302..1568.640 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1929.955..1981.104 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.528..1553.249 rows=990821.00 loops=1)
Planning Time: 0.479 ms
Execution Time: 4661.872 ms
(19 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=3376.385..3435.406 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=2565.517..2916.814 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1249.517..1300.132 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.651..980.740 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1315.990..1369.576 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.426..970.728 rows=990821.00 loops=1)
Planning Time: 0.491 ms
Execution Time: 3527.457 ms
(19 rows)
So it doesn't hurt in this case either. But that is because not the tuplestore which is added in this patch is spilling to disk here.
To understand the impact of the patch in case of tuples spilled to disk, I tried following example,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# set enable_hashjoin = off;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=4537.437..4598.483 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=3748.488..4090.547 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1818.521..1865.792 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.302..1568.640 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1929.955..1981.104 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.528..1553.249 rows=990821.00 loops=1)
Planning Time: 0.479 ms
Execution Time: 4661.872 ms
(19 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=3376.385..3435.406 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=2565.517..2916.814 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1249.517..1300.132 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.651..980.740 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1315.990..1369.576 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.426..970.728 rows=990821.00 loops=1)
Planning Time: 0.491 ms
Execution Time: 3527.457 ms
(19 rows)
So it doesn't hurt in this case either. But that is because not the tuplestore which is added in this patch is spilling to disk here.
I am working on finding a case when there are two or more active cursors and then when storing the tuples of one cursor,
they are spilled onto the disk. That might give a picture of the worst case scenario of this patch.
Also, thanks to Kenan, a fellow hacker who finds this work interesting and offered to do some performance analysis for this patch,
Also, thanks to Kenan, a fellow hacker who finds this work interesting and offered to do some performance analysis for this patch,
maybe he can also post more results here.
--
Regards,
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
--
Regards,
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
KENAN YILMAZ <kenan.yilmaz@localus.com.tr>
Дата:
Hello Hackers,
I have executed use_cursor = true/false with quick tests.
The test table 't1' has 20,000,000 rows (~2.8 GB in size).
The test query is `EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;`
The result sums are;
** `postgres_fdw.use_cursor = true` --> 20090.782 ms
** `postgres_fdw.use_cursor = false` --> 24103.994 ms
If you wish to run more advanced and complex test queries, feel free to do so.
All execution test scenarios are listed below;
--
-- restart with flush caches;
$ pg_ctl -D $PGDATA stop && sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches && rm $PGDATA/log/*.log && pg_ctl -D $PGDATA start
-- Data prep stage
DROP DATABASE IF EXISTS testdb;
CREATE DATABASE testdb;
\c testdb;
DROP TABLE IF EXISTS t1 CASCADE;
CREATE UNLOGGED TABLE t1 (a int, b int, c text, d timestamp);
-- Insert test datas
INSERT INTO t1 SELECT 10 + mod(i, 30), i, md5(i::text) || md5((i+1000000)::text) || md5((i+2000000)::text), '2025-01-01 10:00:00'::timestamp + (random() * 31536000) * INTERVAL '1 second' FROM generate_series(1, 20000000) i;
-- Table maintenance
ALTER TABLE t1 SET LOGGED;
VACUUM (ANALYZE, FULL) t1;
-- FDW prep stage
DROP EXTENSION IF EXISTS postgres_fdw CASCADE;
CREATE EXTENSION postgres_fdw;
CREATE SERVER foreign_server FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host '127.0.0.1', port '5432', dbname 'testdb');
CREATE USER MAPPING FOR postgres SERVER foreign_server OPTIONS (user 'postgres');
CREATE FOREIGN TABLE t1fdw (a int, b int, c text, d timestamp) SERVER foreign_server OPTIONS (table_name 't1');
-- restart with flush caches are applied before all stage executions.
--
-- * Local t1 table EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1 WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=23260.306..23261.591 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared read=363637
I/O Timings: shared read=64590.910
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=23242.279..23242.280 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
Buffers: shared read=363637
I/O Timings: shared read=64590.910
Planning:
Buffers: shared hit=54 read=14 dirtied=1
I/O Timings: shared read=23.281
Planning Time: 38.734 ms
Execution Time: 23269.677 ms
(15 rows)
Time: 23347.716 ms (00:23.348)
--
-- * use_cursor = true (Default) EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=20074.746..20074.796 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17 dirtied=1
I/O Timings: shared read=10.696
Planning Time: 43.852 ms
Execution Time: 20090.782 ms
(6 rows)
Time: 20169.081 ms (00:20.169)
--> From Log Files
[153045]: line=11 sid=6923fba6.255d5 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[153045]: line=12 sid=6923fba6.255d5 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153045]: line=13 sid=6923fba6.255d5 tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[153045]: line=14 sid=6923fba6.255d5 tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[153045]: line=15 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: FETCH 100 FROM c1
[153045]: line=16 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153044]: line=5 sid=6923fba4.255d4 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 20074.799 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=20074.746..20074.796 rows=0.00 loops=1)
[153044]: line=6 sid=6923fba4.255d4 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153045]: line=17 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: CLOSE c1
[153045]: line=18 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153045]: line=19 sid=6923fba6.255d5 tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 20057.543 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Seq Scan on t1 (cost=0.00..613637.45 rows=1 width=105) (actual time=20057.541..20057.541 rows=0.00 loops=1)
Filter: (a > 1000)
Rows Removed by Filter: 20000000
[153045]: line=20 sid=6923fba6.255d5 tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153045]: line=21 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
--
-- * use_cursor = false EXPLAIN results
--
testdb=# SET postgres_fdw.use_cursor = false;
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24080.945..24080.956 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17
I/O Timings: shared read=30.074
Planning Time: 53.678 ms
Execution Time: 24103.994 ms
(6 rows)
Time: 24230.548 ms (00:24.231)
--> From Log Files
[153121]: line=11 sid=6923fc16.25621 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[153121]: line=12 sid=6923fc16.25621 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153121]: line=13 sid=6923fc16.25621 tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[153121]: line=14 sid=6923fc16.25621 tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[153113]: line=7 sid=6923fc0c.25619 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 24080.958 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24080.945..24080.956 rows=0.00 loops=1)
[153113]: line=8 sid=6923fc0c.25619 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153121]: line=15 sid=6923fc16.25621 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
[153121]: line=16 sid=6923fc16.25621 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153121]: line=17 sid=6923fc16.25621 tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 24059.372 ms plan:
Query Text: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=24058.076..24059.367 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=24051.406..24051.407 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
[153121]: line=18 sid=6923fc16.25621 tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
I have executed use_cursor = true/false with quick tests.
The test table 't1' has 20,000,000 rows (~2.8 GB in size).
The test query is `EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;`
The result sums are;
** `postgres_fdw.use_cursor = true` --> 20090.782 ms
** `postgres_fdw.use_cursor = false` --> 24103.994 ms
If you wish to run more advanced and complex test queries, feel free to do so.
All execution test scenarios are listed below;
--
-- restart with flush caches;
$ pg_ctl -D $PGDATA stop && sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches && rm $PGDATA/log/*.log && pg_ctl -D $PGDATA start
-- Data prep stage
DROP DATABASE IF EXISTS testdb;
CREATE DATABASE testdb;
\c testdb;
DROP TABLE IF EXISTS t1 CASCADE;
CREATE UNLOGGED TABLE t1 (a int, b int, c text, d timestamp);
-- Insert test datas
INSERT INTO t1 SELECT 10 + mod(i, 30), i, md5(i::text) || md5((i+1000000)::text) || md5((i+2000000)::text), '2025-01-01 10:00:00'::timestamp + (random() * 31536000) * INTERVAL '1 second' FROM generate_series(1, 20000000) i;
-- Table maintenance
ALTER TABLE t1 SET LOGGED;
VACUUM (ANALYZE, FULL) t1;
-- FDW prep stage
DROP EXTENSION IF EXISTS postgres_fdw CASCADE;
CREATE EXTENSION postgres_fdw;
CREATE SERVER foreign_server FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host '127.0.0.1', port '5432', dbname 'testdb');
CREATE USER MAPPING FOR postgres SERVER foreign_server OPTIONS (user 'postgres');
CREATE FOREIGN TABLE t1fdw (a int, b int, c text, d timestamp) SERVER foreign_server OPTIONS (table_name 't1');
-- restart with flush caches are applied before all stage executions.
--
-- * Local t1 table EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1 WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=23260.306..23261.591 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared read=363637
I/O Timings: shared read=64590.910
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=23242.279..23242.280 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
Buffers: shared read=363637
I/O Timings: shared read=64590.910
Planning:
Buffers: shared hit=54 read=14 dirtied=1
I/O Timings: shared read=23.281
Planning Time: 38.734 ms
Execution Time: 23269.677 ms
(15 rows)
Time: 23347.716 ms (00:23.348)
--
-- * use_cursor = true (Default) EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=20074.746..20074.796 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17 dirtied=1
I/O Timings: shared read=10.696
Planning Time: 43.852 ms
Execution Time: 20090.782 ms
(6 rows)
Time: 20169.081 ms (00:20.169)
--> From Log Files
[153045]: line=11 sid=6923fba6.255d5 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[153045]: line=12 sid=6923fba6.255d5 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153045]: line=13 sid=6923fba6.255d5 tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[153045]: line=14 sid=6923fba6.255d5 tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[153045]: line=15 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: FETCH 100 FROM c1
[153045]: line=16 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153044]: line=5 sid=6923fba4.255d4 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 20074.799 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=20074.746..20074.796 rows=0.00 loops=1)
[153044]: line=6 sid=6923fba4.255d4 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153045]: line=17 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: CLOSE c1
[153045]: line=18 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153045]: line=19 sid=6923fba6.255d5 tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 20057.543 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Seq Scan on t1 (cost=0.00..613637.45 rows=1 width=105) (actual time=20057.541..20057.541 rows=0.00 loops=1)
Filter: (a > 1000)
Rows Removed by Filter: 20000000
[153045]: line=20 sid=6923fba6.255d5 tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153045]: line=21 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
--
-- * use_cursor = false EXPLAIN results
--
testdb=# SET postgres_fdw.use_cursor = false;
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24080.945..24080.956 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17
I/O Timings: shared read=30.074
Planning Time: 53.678 ms
Execution Time: 24103.994 ms
(6 rows)
Time: 24230.548 ms (00:24.231)
--> From Log Files
[153121]: line=11 sid=6923fc16.25621 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[153121]: line=12 sid=6923fc16.25621 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153121]: line=13 sid=6923fc16.25621 tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[153121]: line=14 sid=6923fc16.25621 tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[153113]: line=7 sid=6923fc0c.25619 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 24080.958 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24080.945..24080.956 rows=0.00 loops=1)
[153113]: line=8 sid=6923fc0c.25619 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153121]: line=15 sid=6923fc16.25621 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
[153121]: line=16 sid=6923fc16.25621 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153121]: line=17 sid=6923fc16.25621 tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 24059.372 ms plan:
Query Text: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=24058.076..24059.367 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=24051.406..24051.407 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
[153121]: line=18 sid=6923fc16.25621 tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
---
Kenan YILMAZ
Rafia Sabih <rafia.pghackers@gmail.com>, 25 Kas 2025 Sal, 17:01 tarihinde şunu yazdı:
On Fri, 10 Oct 2025 at 22:02, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Mon, Sep 29, 2025 at 10:51 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> > I am back at this work with a rebased and revised patch. The new version is rebased and has a change in approach.
> > Whenever we are using non-cursor mode, for the first cursor we are always saving the tuples
> > in the tuplestore, this is because we do not have any means to know beforehand how many cursors are required for the query.
>
> This might have the advantage of being simpler, but it's definitely
> worse. If we're only fetching one result set, which will be common,
> we'll buffer the whole thing in a tuplestore where that could
> otherwise be avoided. Maybe it's still best to go with this approach;
> not sure.
>
> > And when we switch to the next query then we do not have a way to fetch the tuples for the previous query.
> > So, the tuples retrieved earlier for the first query were lost if not saved.
> > I would highly appreciate your time and feedback for this.
>
> My suggestions are to work on the following areas:
>
> 1. Automated testing. The patch has no regression tests, and won't get
> committed without those.
>
> 2. Manual testing. How does the performance with this new option
> compare to the existing method? The answer might be different for
> small result sets that fit in memory and large ones that spill to
> disk, and will certainly also depend on how productive parallel query
> can be on the remote side; but I think you want to do and post on this
> list some measurements showing the best and worst case for the patch.
>
> 3. Patch clean-up. There are plenty of typos and whitespace-only
> changes in the patch. It's best to clean those up. Running pgindent is
> a good idea too. Some places could use comments.
>
> --
> Robert Haas
> EDB: http://www.enterprisedb.com
Thank you Robert, for reviewing this patch. On going through the patch more, I realised this was not equipped to handle the cases when there are more than two active cursors. So to accommodate such a case, I now modified the new struct for saving the previous query to a list of such structs. Also, it turns out we need not to save the tuples in case this is an active cursor, so we only populate the associated tuplestore only when we need to create a new cursor when the old cursor is not completely done.
In this version I have added the regression tests as well. I wanted to test this patch for all the cases of postgres_fdw, the only way I could figure out how to do this was to test the select statements with the new GUC.
I also did some tests for performance. I used the contrib_regression database and populated the table "S1"."T1" with more tuples to understand the impact of patch on higher scale. I also used auto_explain to get the foreign plans.
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:35.825 CET [44338] LOG: duration: 61.336 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
2025-11-14 14:40:35.825 CET [44862] LOG: duration: 60.575 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT count(*) FROM "S 1"."T 1"
Aggregate (cost=21888.22..21888.23 rows=1 width=8)
-> Seq Scan on "T 1" (cost=0.00..19956.98 rows=772498 width=0)
count
--------
990821
(1 row)
Time: 62.728 ms
contrib_regression=# SET postgres_fdw.use_cursor = false;SET
Time: 1.515 ms
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:46.260 CET [44862] LOG: duration: 21.875 ms plan:
Query Text: SELECT count(*) FROM "S 1"."T 1"
Finalize Aggregate (cost=17255.64..17255.65 rows=1 width=8)
-> Gather (cost=17255.43..17255.64 rows=2 width=8)
Workers Planned: 2
-> Partial Aggregate (cost=16255.43..16255.44 rows=1 width=8)
-> Parallel Seq Scan on "T 1" (cost=0.00..15450.74 rows=321874 width=0)
2025-11-14 14:40:46.260 CET [44338] LOG: duration: 22.623 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
count
--------
990821
(1 row)
Time: 24.862 ms
So for this query, the advantage is coming from parallel query which was otherwise not possible in this scenario.
To study more performance with this patch, I found another interesting query and here are the results,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");2025-11-14 15:57:46.893 CET [1946]
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=112311.578..112804.516 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp read=12754 written=12754
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.039..48.808 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=112310.386..112310.387 rows=990821.00 loops=1)
Buckets: 262144 (originally 1024) Batches: 8 (originally 1) Memory Usage: 6408kB
Buffers: temp written=2537
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=0.728..112030.241 rows=990821.00 loops=1)
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.398..710.505 rows=990821.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=0.082..0.082 rows=1.00 loops=990821)
Planning:
Buffers: shared hit=5
Planning Time: 2.211 ms
Execution Time: 112825.428 ms
(15 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=261.416..354.520 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp written=2660
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.021..35.531 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=261.381..261.383 rows=100.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 12kB
Buffers: temp written=2660
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=255.563..261.356 rows=100.00 loops=1)
Buffers: temp written=2660
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.433..0.443 rows=100.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=2.609..2.609 rows=1.00 loops=100)
Buffers: temp written=2660
Planning:
Buffers: shared hit=5
Planning Time: 2.284 ms
Execution Time: 389.358 ms
(17 rows)
So even in the case without a parallel plan, it is performing significantly better. I investigated a bit more to find out why the query was so slow with the cursors,and came to understand that it is repeatedly abandoning and recreating the cursor via the code path of postgresReScanForeignScan.So, it looks like cursor management itself costs this much more time.
To understand the impact of the patch in case of tuples spilled to disk, I tried following example,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# set enable_hashjoin = off;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=4537.437..4598.483 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=3748.488..4090.547 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1818.521..1865.792 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.302..1568.640 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1929.955..1981.104 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.528..1553.249 rows=990821.00 loops=1)
Planning Time: 0.479 ms
Execution Time: 4661.872 ms
(19 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=3376.385..3435.406 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=2565.517..2916.814 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1249.517..1300.132 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.651..980.740 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1315.990..1369.576 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.426..970.728 rows=990821.00 loops=1)
Planning Time: 0.491 ms
Execution Time: 3527.457 ms
(19 rows)
So it doesn't hurt in this case either. But that is because not the tuplestore which is added in this patch is spilling to disk here.I am working on finding a case when there are two or more active cursors and then when storing the tuples of one cursor,they are spilled onto the disk. That might give a picture of the worst case scenario of this patch.
Also, thanks to Kenan, a fellow hacker who finds this work interesting and offered to do some performance analysis for this patch,maybe he can also post more results here.
--
Regards,
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Tue, 25 Nov 2025 at 15:24, KENAN YILMAZ <kenan.yilmaz@localus.com.tr> wrote:
Hello Hackers,
I have executed use_cursor = true/false with quick tests.
The test table 't1' has 20,000,000 rows (~2.8 GB in size).
The test query is `EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;`
The result sums are;
** `postgres_fdw.use_cursor = true` --> 20090.782 ms
** `postgres_fdw.use_cursor = false` --> 24103.994 ms
If you wish to run more advanced and complex test queries, feel free to do so.
All execution test scenarios are listed below;
--
-- restart with flush caches;
$ pg_ctl -D $PGDATA stop && sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches && rm $PGDATA/log/*.log && pg_ctl -D $PGDATA start
-- Data prep stage
DROP DATABASE IF EXISTS testdb;
CREATE DATABASE testdb;
\c testdb;
DROP TABLE IF EXISTS t1 CASCADE;
CREATE UNLOGGED TABLE t1 (a int, b int, c text, d timestamp);
-- Insert test datas
INSERT INTO t1 SELECT 10 + mod(i, 30), i, md5(i::text) || md5((i+1000000)::text) || md5((i+2000000)::text), '2025-01-01 10:00:00'::timestamp + (random() * 31536000) * INTERVAL '1 second' FROM generate_series(1, 20000000) i;
-- Table maintenance
ALTER TABLE t1 SET LOGGED;
VACUUM (ANALYZE, FULL) t1;
-- FDW prep stage
DROP EXTENSION IF EXISTS postgres_fdw CASCADE;
CREATE EXTENSION postgres_fdw;
CREATE SERVER foreign_server FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host '127.0.0.1', port '5432', dbname 'testdb');
CREATE USER MAPPING FOR postgres SERVER foreign_server OPTIONS (user 'postgres');
CREATE FOREIGN TABLE t1fdw (a int, b int, c text, d timestamp) SERVER foreign_server OPTIONS (table_name 't1');
-- restart with flush caches are applied before all stage executions.
--
-- * Local t1 table EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1 WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=23260.306..23261.591 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared read=363637
I/O Timings: shared read=64590.910
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=23242.279..23242.280 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
Buffers: shared read=363637
I/O Timings: shared read=64590.910
Planning:
Buffers: shared hit=54 read=14 dirtied=1
I/O Timings: shared read=23.281
Planning Time: 38.734 ms
Execution Time: 23269.677 ms
(15 rows)
Time: 23347.716 ms (00:23.348)
--
-- * use_cursor = true (Default) EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=20074.746..20074.796 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17 dirtied=1
I/O Timings: shared read=10.696
Planning Time: 43.852 ms
Execution Time: 20090.782 ms
(6 rows)
Time: 20169.081 ms (00:20.169)
--> From Log Files
[153045]: line=11 sid=6923fba6.255d5 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[153045]: line=12 sid=6923fba6.255d5 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153045]: line=13 sid=6923fba6.255d5 tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[153045]: line=14 sid=6923fba6.255d5 tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[153045]: line=15 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: FETCH 100 FROM c1
[153045]: line=16 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153044]: line=5 sid=6923fba4.255d4 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 20074.799 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=20074.746..20074.796 rows=0.00 loops=1)
[153044]: line=6 sid=6923fba4.255d4 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153045]: line=17 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: CLOSE c1
[153045]: line=18 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153045]: line=19 sid=6923fba6.255d5 tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 20057.543 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Seq Scan on t1 (cost=0.00..613637.45 rows=1 width=105) (actual time=20057.541..20057.541 rows=0.00 loops=1)
Filter: (a > 1000)
Rows Removed by Filter: 20000000
[153045]: line=20 sid=6923fba6.255d5 tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153045]: line=21 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
--
-- * use_cursor = false EXPLAIN results
--
testdb=# SET postgres_fdw.use_cursor = false;
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24080.945..24080.956 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17
I/O Timings: shared read=30.074
Planning Time: 53.678 ms
Execution Time: 24103.994 ms
(6 rows)
Time: 24230.548 ms (00:24.231)
--> From Log Files
[153121]: line=11 sid=6923fc16.25621 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[153121]: line=12 sid=6923fc16.25621 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153121]: line=13 sid=6923fc16.25621 tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[153121]: line=14 sid=6923fc16.25621 tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[153113]: line=7 sid=6923fc0c.25619 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 24080.958 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24080.945..24080.956 rows=0.00 loops=1)
[153113]: line=8 sid=6923fc0c.25619 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153121]: line=15 sid=6923fc16.25621 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
[153121]: line=16 sid=6923fc16.25621 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153121]: line=17 sid=6923fc16.25621 tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 24059.372 ms plan:
Query Text: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=24058.076..24059.367 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=24051.406..24051.407 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
[153121]: line=18 sid=6923fc16.25621 tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437---Kenan YILMAZ
Thanks Kenan for these. So, it looks like the patch performs the same as in the local scan case. I wonder if you found any case of performance degradation with the patch.
Per an off-list discussion with Robert, he suggested using the existing data structures for recording the state of last queries instead of inventing something new.
Makes sense, so I reworked the patch to include tuplestore in PgFdwScanState and then use PgFdwScanState as part of PgFdwConnState to keep track of previously
active cursors. Nothing else is changed in this version of the patch.
Rafia Sabih <rafia.pghackers@gmail.com>, 25 Kas 2025 Sal, 17:01 tarihinde şunu yazdı:
On Fri, 10 Oct 2025 at 22:02, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Mon, Sep 29, 2025 at 10:51 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> > I am back at this work with a rebased and revised patch. The new version is rebased and has a change in approach.
> > Whenever we are using non-cursor mode, for the first cursor we are always saving the tuples
> > in the tuplestore, this is because we do not have any means to know beforehand how many cursors are required for the query.
>
> This might have the advantage of being simpler, but it's definitely
> worse. If we're only fetching one result set, which will be common,
> we'll buffer the whole thing in a tuplestore where that could
> otherwise be avoided. Maybe it's still best to go with this approach;
> not sure.
>
> > And when we switch to the next query then we do not have a way to fetch the tuples for the previous query.
> > So, the tuples retrieved earlier for the first query were lost if not saved.
> > I would highly appreciate your time and feedback for this.
>
> My suggestions are to work on the following areas:
>
> 1. Automated testing. The patch has no regression tests, and won't get
> committed without those.
>
> 2. Manual testing. How does the performance with this new option
> compare to the existing method? The answer might be different for
> small result sets that fit in memory and large ones that spill to
> disk, and will certainly also depend on how productive parallel query
> can be on the remote side; but I think you want to do and post on this
> list some measurements showing the best and worst case for the patch.
>
> 3. Patch clean-up. There are plenty of typos and whitespace-only
> changes in the patch. It's best to clean those up. Running pgindent is
> a good idea too. Some places could use comments.
>
> --
> Robert Haas
> EDB: http://www.enterprisedb.com
Thank you Robert, for reviewing this patch. On going through the patch more, I realised this was not equipped to handle the cases when there are more than two active cursors. So to accommodate such a case, I now modified the new struct for saving the previous query to a list of such structs. Also, it turns out we need not to save the tuples in case this is an active cursor, so we only populate the associated tuplestore only when we need to create a new cursor when the old cursor is not completely done.
In this version I have added the regression tests as well. I wanted to test this patch for all the cases of postgres_fdw, the only way I could figure out how to do this was to test the select statements with the new GUC.
I also did some tests for performance. I used the contrib_regression database and populated the table "S1"."T1" with more tuples to understand the impact of patch on higher scale. I also used auto_explain to get the foreign plans.
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:35.825 CET [44338] LOG: duration: 61.336 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
2025-11-14 14:40:35.825 CET [44862] LOG: duration: 60.575 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT count(*) FROM "S 1"."T 1"
Aggregate (cost=21888.22..21888.23 rows=1 width=8)
-> Seq Scan on "T 1" (cost=0.00..19956.98 rows=772498 width=0)
count
--------
990821
(1 row)
Time: 62.728 ms
contrib_regression=# SET postgres_fdw.use_cursor = false;SET
Time: 1.515 ms
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:46.260 CET [44862] LOG: duration: 21.875 ms plan:
Query Text: SELECT count(*) FROM "S 1"."T 1"
Finalize Aggregate (cost=17255.64..17255.65 rows=1 width=8)
-> Gather (cost=17255.43..17255.64 rows=2 width=8)
Workers Planned: 2
-> Partial Aggregate (cost=16255.43..16255.44 rows=1 width=8)
-> Parallel Seq Scan on "T 1" (cost=0.00..15450.74 rows=321874 width=0)
2025-11-14 14:40:46.260 CET [44338] LOG: duration: 22.623 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
count
--------
990821
(1 row)
Time: 24.862 ms
So for this query, the advantage is coming from parallel query which was otherwise not possible in this scenario.
To study more performance with this patch, I found another interesting query and here are the results,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");2025-11-14 15:57:46.893 CET [1946]
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=112311.578..112804.516 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp read=12754 written=12754
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.039..48.808 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=112310.386..112310.387 rows=990821.00 loops=1)
Buckets: 262144 (originally 1024) Batches: 8 (originally 1) Memory Usage: 6408kB
Buffers: temp written=2537
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=0.728..112030.241 rows=990821.00 loops=1)
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.398..710.505 rows=990821.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=0.082..0.082 rows=1.00 loops=990821)
Planning:
Buffers: shared hit=5
Planning Time: 2.211 ms
Execution Time: 112825.428 ms
(15 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=261.416..354.520 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp written=2660
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.021..35.531 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=261.381..261.383 rows=100.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 12kB
Buffers: temp written=2660
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=255.563..261.356 rows=100.00 loops=1)
Buffers: temp written=2660
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.433..0.443 rows=100.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=2.609..2.609 rows=1.00 loops=100)
Buffers: temp written=2660
Planning:
Buffers: shared hit=5
Planning Time: 2.284 ms
Execution Time: 389.358 ms
(17 rows)
So even in the case without a parallel plan, it is performing significantly better. I investigated a bit more to find out why the query was so slow with the cursors,and came to understand that it is repeatedly abandoning and recreating the cursor via the code path of postgresReScanForeignScan.So, it looks like cursor management itself costs this much more time.
To understand the impact of the patch in case of tuples spilled to disk, I tried following example,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# set enable_hashjoin = off;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=4537.437..4598.483 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=3748.488..4090.547 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1818.521..1865.792 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.302..1568.640 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1929.955..1981.104 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.528..1553.249 rows=990821.00 loops=1)
Planning Time: 0.479 ms
Execution Time: 4661.872 ms
(19 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=3376.385..3435.406 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=2565.517..2916.814 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1249.517..1300.132 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.651..980.740 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1315.990..1369.576 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.426..970.728 rows=990821.00 loops=1)
Planning Time: 0.491 ms
Execution Time: 3527.457 ms
(19 rows)
So it doesn't hurt in this case either. But that is because not the tuplestore which is added in this patch is spilling to disk here.I am working on finding a case when there are two or more active cursors and then when storing the tuples of one cursor,they are spilled onto the disk. That might give a picture of the worst case scenario of this patch.
Also, thanks to Kenan, a fellow hacker who finds this work interesting and offered to do some performance analysis for this patch,maybe he can also post more results here.
--
Regards,
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
KENAN YILMAZ <kenan.yilmaz@localus.com.tr>
Дата:
Hello Hackers,
I have executed another quick tests based on v4-0001-Fetch-without-cursors patch.
I also recompiled PostgreSQL from the latest main branch.
Here are the execution time results;
** Local t1 table select (1st run) → 35049.790 ms — Parallel workers launched
** postgres_fdw.use_cursor = true → 18996.236 ms — No parallel workers launched
** postgres_fdw.use_cursor = false → 24962.529 ms — Parallel workers launched
** Local t1 table select (2nd run) → 21406.631 ms — Parallel workers launched
In my opinion, the primary goal is to enable FDW to fully support parallel execution.
From that perspective, these results seem acceptable.
If you would like to run more advanced or complex test queries, please feel free to proceed.
The following tests were executed in the same manner as in my previous test runs;
--
-- * Local t1 table EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1 WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=35042.394..35043.542 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=240 read=363397
I/O Timings: shared read=99749.585
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=35023.992..35023.993 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
Buffers: shared hit=240 read=363397
I/O Timings: shared read=99749.585
Planning:
Buffers: shared hit=64 read=9 dirtied=1
I/O Timings: shared read=4.656
Planning Time: 30.145 ms
Execution Time: 35049.790 ms
(15 rows)
Time: 35154.644 ms (00:35.155)
--
-- * use_cursor = true EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=18981.860..18981.896 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17 dirtied=1
I/O Timings: shared read=27.012
Planning Time: 65.290 ms
Execution Time: 18996.236 ms
(6 rows)
Time: 19121.351 ms (00:19.121)
--> From Log Files
--> From Log Files
[197885]: line=11 sid=6929af4a.304fd tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[197885]: line=12 sid=6929af4a.304fd tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197885]: line=13 sid=6929af4a.304fd tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[197885]: line=14 sid=6929af4a.304fd tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[197885]: line=15 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: FETCH 100 FROM c1
[197885]: line=16 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197882]: line=5 sid=6929af48.304fa tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 18981.899 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=18981.860..18981.896 rows=0.00 loops=1)
[197882]: line=6 sid=6929af48.304fa tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[197885]: line=17 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: CLOSE c1
[197885]: line=18 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197885]: line=19 sid=6929af4a.304fd tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 18950.616 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Seq Scan on t1 (cost=0.00..613637.45 rows=1 width=105) (actual time=18950.614..18950.614 rows=0.00 loops=1)
Filter: (a > 1000)
Rows Removed by Filter: 20000000
[197885]: line=20 sid=6929af4a.304fd tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[197885]: line=21 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
[197885]: line=22 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
--
-- * use_cursor = false EXPLAIN results
--
testdb=# SET postgres_fdw.use_cursor = false;
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24940.034..24940.054 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17
I/O Timings: shared read=34.719
Planning Time: 62.300 ms
Execution Time: 24962.529 ms
(6 rows)
Time: 25124.566 ms (00:25.125)
--> From Log Files
[197919]: line=11 sid=6929afcb.3051f tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[197919]: line=12 sid=6929afcb.3051f tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197919]: line=13 sid=6929afcb.3051f tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[197919]: line=14 sid=6929afcb.3051f tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[197917]: line=7 sid=6929afbd.3051d tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 24940.057 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24940.034..24940.054 rows=0.00 loops=1)
[197917]: line=8 sid=6929afbd.3051d tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[197919]: line=15 sid=6929afcb.3051f tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
[197919]: line=16 sid=6929afcb.3051f tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197919]: line=17 sid=6929afcb.3051f tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 24908.608 ms plan:
Query Text: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=24906.370..24908.603 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=24895.314..24895.314 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
[197919]: line=18 sid=6929afcb.3051f tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
---
--
-- * Local t1 table EXPLAIN results (again)
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1 WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Gather (cost=0.00..467803.67 rows=1 width=105) (actual time=21403.492..21405.381 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared read=363637
I/O Timings: shared read=59425.134
-> Parallel Seq Scan on t1 (cost=0.00..467803.67 rows=1 width=105) (actual time=21394.997..21394.997 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
Buffers: shared read=363637
I/O Timings: shared read=59425.134
Planning:
Buffers: shared hit=54 read=14
I/O Timings: shared read=30.482
Planning Time: 37.955 ms
Execution Time: 21406.631 ms
(15 rows)
Time: 21506.079 ms (00:21.506)
I have executed another quick tests based on v4-0001-Fetch-without-cursors patch.
I also recompiled PostgreSQL from the latest main branch.
Here are the execution time results;
** Local t1 table select (1st run) → 35049.790 ms — Parallel workers launched
** postgres_fdw.use_cursor = true → 18996.236 ms — No parallel workers launched
** postgres_fdw.use_cursor = false → 24962.529 ms — Parallel workers launched
** Local t1 table select (2nd run) → 21406.631 ms — Parallel workers launched
In my opinion, the primary goal is to enable FDW to fully support parallel execution.
From that perspective, these results seem acceptable.
If you would like to run more advanced or complex test queries, please feel free to proceed.
The following tests were executed in the same manner as in my previous test runs;
--
-- * Local t1 table EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1 WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=35042.394..35043.542 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=240 read=363397
I/O Timings: shared read=99749.585
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=35023.992..35023.993 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
Buffers: shared hit=240 read=363397
I/O Timings: shared read=99749.585
Planning:
Buffers: shared hit=64 read=9 dirtied=1
I/O Timings: shared read=4.656
Planning Time: 30.145 ms
Execution Time: 35049.790 ms
(15 rows)
Time: 35154.644 ms (00:35.155)
--
-- * use_cursor = true EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=18981.860..18981.896 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17 dirtied=1
I/O Timings: shared read=27.012
Planning Time: 65.290 ms
Execution Time: 18996.236 ms
(6 rows)
Time: 19121.351 ms (00:19.121)
--> From Log Files
--> From Log Files
[197885]: line=11 sid=6929af4a.304fd tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[197885]: line=12 sid=6929af4a.304fd tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197885]: line=13 sid=6929af4a.304fd tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[197885]: line=14 sid=6929af4a.304fd tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[197885]: line=15 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: FETCH 100 FROM c1
[197885]: line=16 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197882]: line=5 sid=6929af48.304fa tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 18981.899 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=18981.860..18981.896 rows=0.00 loops=1)
[197882]: line=6 sid=6929af48.304fa tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[197885]: line=17 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: CLOSE c1
[197885]: line=18 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197885]: line=19 sid=6929af4a.304fd tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 18950.616 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Seq Scan on t1 (cost=0.00..613637.45 rows=1 width=105) (actual time=18950.614..18950.614 rows=0.00 loops=1)
Filter: (a > 1000)
Rows Removed by Filter: 20000000
[197885]: line=20 sid=6929af4a.304fd tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[197885]: line=21 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
[197885]: line=22 sid=6929af4a.304fd tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
--
-- * use_cursor = false EXPLAIN results
--
testdb=# SET postgres_fdw.use_cursor = false;
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24940.034..24940.054 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17
I/O Timings: shared read=34.719
Planning Time: 62.300 ms
Execution Time: 24962.529 ms
(6 rows)
Time: 25124.566 ms (00:25.125)
--> From Log Files
[197919]: line=11 sid=6929afcb.3051f tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[197919]: line=12 sid=6929afcb.3051f tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197919]: line=13 sid=6929afcb.3051f tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[197919]: line=14 sid=6929afcb.3051f tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[197917]: line=7 sid=6929afbd.3051d tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 24940.057 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24940.034..24940.054 rows=0.00 loops=1)
[197917]: line=8 sid=6929afbd.3051d tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[197919]: line=15 sid=6929afcb.3051f tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
[197919]: line=16 sid=6929afcb.3051f tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[197919]: line=17 sid=6929afcb.3051f tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 24908.608 ms plan:
Query Text: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=24906.370..24908.603 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=24895.314..24895.314 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
[197919]: line=18 sid=6929afcb.3051f tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
---
--
-- * Local t1 table EXPLAIN results (again)
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1 WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Gather (cost=0.00..467803.67 rows=1 width=105) (actual time=21403.492..21405.381 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared read=363637
I/O Timings: shared read=59425.134
-> Parallel Seq Scan on t1 (cost=0.00..467803.67 rows=1 width=105) (actual time=21394.997..21394.997 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
Buffers: shared read=363637
I/O Timings: shared read=59425.134
Planning:
Buffers: shared hit=54 read=14
I/O Timings: shared read=30.482
Planning Time: 37.955 ms
Execution Time: 21406.631 ms
(15 rows)
Time: 21506.079 ms (00:21.506)
---
Kenan YILMAZ
Rafia Sabih <rafia.pghackers@gmail.com>, 27 Kas 2025 Per, 13:50 tarihinde şunu yazdı:
On Tue, 25 Nov 2025 at 15:24, KENAN YILMAZ <kenan.yilmaz@localus.com.tr> wrote:Hello Hackers,
I have executed use_cursor = true/false with quick tests.
The test table 't1' has 20,000,000 rows (~2.8 GB in size).
The test query is `EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;`
The result sums are;
** `postgres_fdw.use_cursor = true` --> 20090.782 ms
** `postgres_fdw.use_cursor = false` --> 24103.994 ms
If you wish to run more advanced and complex test queries, feel free to do so.
All execution test scenarios are listed below;
--
-- restart with flush caches;
$ pg_ctl -D $PGDATA stop && sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches && rm $PGDATA/log/*.log && pg_ctl -D $PGDATA start
-- Data prep stage
DROP DATABASE IF EXISTS testdb;
CREATE DATABASE testdb;
\c testdb;
DROP TABLE IF EXISTS t1 CASCADE;
CREATE UNLOGGED TABLE t1 (a int, b int, c text, d timestamp);
-- Insert test datas
INSERT INTO t1 SELECT 10 + mod(i, 30), i, md5(i::text) || md5((i+1000000)::text) || md5((i+2000000)::text), '2025-01-01 10:00:00'::timestamp + (random() * 31536000) * INTERVAL '1 second' FROM generate_series(1, 20000000) i;
-- Table maintenance
ALTER TABLE t1 SET LOGGED;
VACUUM (ANALYZE, FULL) t1;
-- FDW prep stage
DROP EXTENSION IF EXISTS postgres_fdw CASCADE;
CREATE EXTENSION postgres_fdw;
CREATE SERVER foreign_server FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host '127.0.0.1', port '5432', dbname 'testdb');
CREATE USER MAPPING FOR postgres SERVER foreign_server OPTIONS (user 'postgres');
CREATE FOREIGN TABLE t1fdw (a int, b int, c text, d timestamp) SERVER foreign_server OPTIONS (table_name 't1');
-- restart with flush caches are applied before all stage executions.
--
-- * Local t1 table EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1 WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=23260.306..23261.591 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared read=363637
I/O Timings: shared read=64590.910
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=23242.279..23242.280 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
Buffers: shared read=363637
I/O Timings: shared read=64590.910
Planning:
Buffers: shared hit=54 read=14 dirtied=1
I/O Timings: shared read=23.281
Planning Time: 38.734 ms
Execution Time: 23269.677 ms
(15 rows)
Time: 23347.716 ms (00:23.348)
--
-- * use_cursor = true (Default) EXPLAIN results
--
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=20074.746..20074.796 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17 dirtied=1
I/O Timings: shared read=10.696
Planning Time: 43.852 ms
Execution Time: 20090.782 ms
(6 rows)
Time: 20169.081 ms (00:20.169)
--> From Log Files
[153045]: line=11 sid=6923fba6.255d5 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[153045]: line=12 sid=6923fba6.255d5 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153045]: line=13 sid=6923fba6.255d5 tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[153045]: line=14 sid=6923fba6.255d5 tag=DECLARE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[153045]: line=15 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: FETCH 100 FROM c1
[153045]: line=16 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153044]: line=5 sid=6923fba4.255d4 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 20074.799 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=20074.746..20074.796 rows=0.00 loops=1)
[153044]: line=6 sid=6923fba4.255d4 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153045]: line=17 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: CLOSE c1
[153045]: line=18 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153045]: line=19 sid=6923fba6.255d5 tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 20057.543 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Seq Scan on t1 (cost=0.00..613637.45 rows=1 width=105) (actual time=20057.541..20057.541 rows=0.00 loops=1)
Filter: (a > 1000)
Rows Removed by Filter: 20000000
[153045]: line=20 sid=6923fba6.255d5 tag=CLOSE CURSOR usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153045]: line=21 sid=6923fba6.255d5 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
--
-- * use_cursor = false EXPLAIN results
--
testdb=# SET postgres_fdw.use_cursor = false;
testdb=# EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
QUERY PLAN
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24080.945..24080.956 rows=0.00 loops=1)
Planning:
Buffers: shared hit=33 read=17
I/O Timings: shared read=30.074
Planning Time: 53.678 ms
Execution Time: 24103.994 ms
(6 rows)
Time: 24230.548 ms (00:24.231)
--> From Log Files
[153121]: line=11 sid=6923fc16.25621 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: START TRANSACTION ISOLATION LEVEL REPEATABLE READ
[153121]: line=12 sid=6923fc16.25621 tag=idle usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153121]: line=13 sid=6923fc16.25621 tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: execute <unnamed>: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
[153121]: line=14 sid=6923fc16.25621 tag=SELECT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_execute_message, postgres.c:2245
[153113]: line=7 sid=6923fc0c.25619 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOG: 00000: duration: 24080.958 ms plan:
Query Text: EXPLAIN (ANALYZE, BUFFERS) SELECT a,b,c FROM t1fdw WHERE a > 1000;
Foreign Scan on t1fdw (cost=100.00..215.67 rows=427 width=40) (actual time=24080.945..24080.956 rows=0.00 loops=1)
[153113]: line=8 sid=6923fc0c.25619 tag=EXPLAIN usr=postgres db=testdb app=psql client=[local]: LOCATION: explain_ExecutorEnd, auto_explain.c:437
[153121]: line=15 sid=6923fc16.25621 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: statement: COMMIT TRANSACTION
[153121]: line=16 sid=6923fc16.25621 tag=idle in transaction usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: exec_simple_query, postgres.c:1078
[153121]: line=17 sid=6923fc16.25621 tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOG: 00000: duration: 24059.372 ms plan:
Query Text: SELECT a, b, c FROM public.t1 WHERE ((a > 1000))
Gather (cost=0.00..467803.85 rows=1 width=105) (actual time=24058.076..24059.367 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on t1 (cost=0.00..467803.85 rows=1 width=105) (actual time=24051.406..24051.407 rows=0.00 loops=3)
Filter: (a > 1000)
Rows Removed by Filter: 6666667
[153121]: line=18 sid=6923fc16.25621 tag=COMMIT usr=postgres db=testdb app=postgres_fdw client=127.0.0.1: LOCATION: explain_ExecutorEnd, auto_explain.c:437---Kenan YILMAZThanks Kenan for these. So, it looks like the patch performs the same as in the local scan case. I wonder if you found any case of performance degradation with the patch.Per an off-list discussion with Robert, he suggested using the existing data structures for recording the state of last queries instead of inventing something new.Makes sense, so I reworked the patch to include tuplestore in PgFdwScanState and then use PgFdwScanState as part of PgFdwConnState to keep track of previouslyactive cursors. Nothing else is changed in this version of the patch.Rafia Sabih <rafia.pghackers@gmail.com>, 25 Kas 2025 Sal, 17:01 tarihinde şunu yazdı:
On Fri, 10 Oct 2025 at 22:02, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Mon, Sep 29, 2025 at 10:51 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> > I am back at this work with a rebased and revised patch. The new version is rebased and has a change in approach.
> > Whenever we are using non-cursor mode, for the first cursor we are always saving the tuples
> > in the tuplestore, this is because we do not have any means to know beforehand how many cursors are required for the query.
>
> This might have the advantage of being simpler, but it's definitely
> worse. If we're only fetching one result set, which will be common,
> we'll buffer the whole thing in a tuplestore where that could
> otherwise be avoided. Maybe it's still best to go with this approach;
> not sure.
>
> > And when we switch to the next query then we do not have a way to fetch the tuples for the previous query.
> > So, the tuples retrieved earlier for the first query were lost if not saved.
> > I would highly appreciate your time and feedback for this.
>
> My suggestions are to work on the following areas:
>
> 1. Automated testing. The patch has no regression tests, and won't get
> committed without those.
>
> 2. Manual testing. How does the performance with this new option
> compare to the existing method? The answer might be different for
> small result sets that fit in memory and large ones that spill to
> disk, and will certainly also depend on how productive parallel query
> can be on the remote side; but I think you want to do and post on this
> list some measurements showing the best and worst case for the patch.
>
> 3. Patch clean-up. There are plenty of typos and whitespace-only
> changes in the patch. It's best to clean those up. Running pgindent is
> a good idea too. Some places could use comments.
>
> --
> Robert Haas
> EDB: http://www.enterprisedb.com
Thank you Robert, for reviewing this patch. On going through the patch more, I realised this was not equipped to handle the cases when there are more than two active cursors. So to accommodate such a case, I now modified the new struct for saving the previous query to a list of such structs. Also, it turns out we need not to save the tuples in case this is an active cursor, so we only populate the associated tuplestore only when we need to create a new cursor when the old cursor is not completely done.
In this version I have added the regression tests as well. I wanted to test this patch for all the cases of postgres_fdw, the only way I could figure out how to do this was to test the select statements with the new GUC.
I also did some tests for performance. I used the contrib_regression database and populated the table "S1"."T1" with more tuples to understand the impact of patch on higher scale. I also used auto_explain to get the foreign plans.
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:35.825 CET [44338] LOG: duration: 61.336 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
2025-11-14 14:40:35.825 CET [44862] LOG: duration: 60.575 ms plan:
Query Text: DECLARE c1 CURSOR FOR
SELECT count(*) FROM "S 1"."T 1"
Aggregate (cost=21888.22..21888.23 rows=1 width=8)
-> Seq Scan on "T 1" (cost=0.00..19956.98 rows=772498 width=0)
count
--------
990821
(1 row)
Time: 62.728 ms
contrib_regression=# SET postgres_fdw.use_cursor = false;SET
Time: 1.515 ms
contrib_regression=# select count(*) from ft1;
2025-11-14 14:40:46.260 CET [44862] LOG: duration: 21.875 ms plan:
Query Text: SELECT count(*) FROM "S 1"."T 1"
Finalize Aggregate (cost=17255.64..17255.65 rows=1 width=8)
-> Gather (cost=17255.43..17255.64 rows=2 width=8)
Workers Planned: 2
-> Partial Aggregate (cost=16255.43..16255.44 rows=1 width=8)
-> Parallel Seq Scan on "T 1" (cost=0.00..15450.74 rows=321874 width=0)
2025-11-14 14:40:46.260 CET [44338] LOG: duration: 22.623 ms plan:
Query Text: select count(*) from ft1;
Foreign Scan (cost=102.50..123.72 rows=1 width=8)
Relations: Aggregate on (ft1)
count
--------
990821
(1 row)
Time: 24.862 ms
So for this query, the advantage is coming from parallel query which was otherwise not possible in this scenario.
To study more performance with this patch, I found another interesting query and here are the results,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");2025-11-14 15:57:46.893 CET [1946]
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=112311.578..112804.516 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp read=12754 written=12754
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.039..48.808 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=112310.386..112310.387 rows=990821.00 loops=1)
Buckets: 262144 (originally 1024) Batches: 8 (originally 1) Memory Usage: 6408kB
Buffers: temp written=2537
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=0.728..112030.241 rows=990821.00 loops=1)
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.398..710.505 rows=990821.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=0.082..0.082 rows=1.00 loops=990821)
Planning:
Buffers: shared hit=5
Planning Time: 2.211 ms
Execution Time: 112825.428 ms
(15 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
explain (analyse, buffers) SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1");
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
Hash Left Join (cost=109013.50..131877.35 rows=772498 width=4) (actual time=261.416..354.520 rows=990821.00 loops=1)
Hash Cond: (t1."C 1" = t3.c1)
Buffers: shared hit=12232, temp written=2660
-> Seq Scan on "T 1" t1 (cost=0.00..19956.98 rows=772498 width=4) (actual time=0.021..35.531 rows=990821.00 loops=1)
Buffers: shared hit=12232
-> Hash (cost=109001.00..109001.00 rows=1000 width=4) (actual time=261.381..261.383 rows=100.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 12kB
Buffers: temp written=2660
-> Nested Loop (cost=200.43..109001.00 rows=1000 width=4) (actual time=255.563..261.356 rows=100.00 loops=1)
Buffers: temp written=2660
-> Foreign Scan on ft1 t2 (cost=100.00..331.00 rows=1000 width=4) (actual time=0.433..0.443 rows=100.00 loops=1)
-> Foreign Scan on ft2 t3 (cost=100.43..108.66 rows=1 width=4) (actual time=2.609..2.609 rows=1.00 loops=100)
Buffers: temp written=2660
Planning:
Buffers: shared hit=5
Planning Time: 2.284 ms
Execution Time: 389.358 ms
(17 rows)
So even in the case without a parallel plan, it is performing significantly better. I investigated a bit more to find out why the query was so slow with the cursors,and came to understand that it is repeatedly abandoning and recreating the cursor via the code path of postgresReScanForeignScan.So, it looks like cursor management itself costs this much more time.
To understand the impact of the patch in case of tuples spilled to disk, I tried following example,
contrib_regression=# SET postgres_fdw.use_cursor = true;
SET
contrib_regression=# set enable_hashjoin = off;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=4537.437..4598.483 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=3748.488..4090.547 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1818.521..1865.792 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.302..1568.640 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1929.955..1981.104 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.528..1553.249 rows=990821.00 loops=1)
Planning Time: 0.479 ms
Execution Time: 4661.872 ms
(19 rows)
contrib_regression=# SET postgres_fdw.use_cursor = false;
SET
contrib_regression=# explain (analyse, buffers)select * from ft1 a, ft1 b where a.c1 = b.c1 order by a.c2;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=831.49..833.99 rows=1000 width=94) (actual time=3376.385..3435.406 rows=990821.00 loops=1)
Sort Key: a.c2
Sort Method: external merge Disk: 137768kB
Buffers: temp read=83156 written=83253
-> Merge Join (cost=761.66..781.66 rows=1000 width=94) (actual time=2565.517..2916.814 rows=990821.00 loops=1)
Merge Cond: (a.c1 = b.c1)
Buffers: temp read=48725 written=48779
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1249.517..1300.132 rows=990821.00 loops=1)
Sort Key: a.c1
Sort Method: external merge Disk: 75664kB
Buffers: temp read=18910 written=18937
-> Foreign Scan on ft1 a (cost=100.00..331.00 rows=1000 width=47) (actual time=1.651..980.740 rows=990821.00 loops=1)
-> Sort (cost=380.83..383.33 rows=1000 width=47) (actual time=1315.990..1369.576 rows=990821.00 loops=1)
Sort Key: b.c1
Sort Method: external sort Disk: 79520kB
Buffers: temp read=29815 written=29842
-> Foreign Scan on ft1 b (cost=100.00..331.00 rows=1000 width=47) (actual time=0.426..970.728 rows=990821.00 loops=1)
Planning Time: 0.491 ms
Execution Time: 3527.457 ms
(19 rows)
So it doesn't hurt in this case either. But that is because not the tuplestore which is added in this patch is spilling to disk here.I am working on finding a case when there are two or more active cursors and then when storing the tuples of one cursor,they are spilled onto the disk. That might give a picture of the worst case scenario of this patch.
Also, thanks to Kenan, a fellow hacker who finds this work interesting and offered to do some performance analysis for this patch,maybe he can also post more results here.
--
Regards,
Rafia Sabih
CYBERTEC PostgreSQL International GmbH--Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Thu, Nov 27, 2025 at 5:50 AM Rafia Sabih wrote:
> Thanks Kenan for these. So, it looks like the patch performs the same as in the local scan case. I wonder if you found any case of performance degradation with the patch.
>
> Per an off-list discussion with Robert, he suggested using the existing data structures for recording the state of last queries instead of inventing something new.
> Makes sense, so I reworked the patch to include tuplestore in PgFdwScanState and then use PgFdwScanState as part of PgFdwConnState to keep track of previously
> active cursors. Nothing else is changed in this version of the patch.
Thanks for your continued work on this topic.
As we discussed off-list, the regression tests in this patch need
quite a bit more work. We shouldn't just repeat large numbers of tests
-- we should repeat enough to provide meaningful test coverage of the
new feature, and maybe add a few new ones that specifically target
scenarios that the patch is intended to cover. One somewhat bizarre
thing that I noticed scrolling through the regression test outputs is
this:
+-- Test with non-cursor mode
+SET postgres_fdw.use_cursor = false;
+SET postgres_fdw.use_cursor = true;
This happens in multiple places in the regression tests, and doesn't
really make any sense to me, because changing the GUC from to false,
doing nothing, and then changing it back to true doesn't seem like a
useful test scenario, and definitely doesn't seem like a test scenario
that we need to repeat multiple times. Honestly, I wonder how this
happened. Did you maybe run a script over the .sql files to generate
the new versions and then not check what the output actually looked
like? I really can't stress enough the need to be thoughtful about
constructing test cases for a patch of this type.
A related problem is that you've included 12,721 lines of useless
output in the patch file, because somehow postgres_fdw.out.orig got
checked into the repository. It's always a good idea, when posting a
patch to the list, to check the diffstat to make sure that there's
nothing in there that you don't expect to see. The presence of this
line just below your commit message could have alerted you to this
problem:
.../expected/postgres_fdw.out.orig | 12721 ++++++++++++++++
Ideally, I really recommend scrolling through the patch, not just the
diffstat, to make sure that everything is the way you want it to be,
before giving it to others to look at.
There are a number of other cosmetic problems with this patch that
make it hard to review the actual code changes. For instance:
+ /* To be used only in non-cursor mode */
+ Tuplestorestate *tuplestore;
+ TupleTableSlot *slot;
+ bool tuples_ready;
+ struct PgFdwScanState *next;
The comment is good, but it only explains a general fact about all
four of these fields. It doesn't explain specifically what each of
these fields is intended to do. Naming a field very generally, like
"next", when it must have some very specific purpose that is not
documented, makes it really hard for someone reading the code -- in
this case, me -- to understand what the point is. So, these fields
should probably have comments, but also, some of them probably need to
be renamed. Maybe "tuplestore" and "slot" are OK but "next" is not
going to be good enough.
+/* Fill the Tupleslot when another query needs to execute. */
+static void
+fillTupleSlot(PgFdwScanState *fsstate, ForeignScanState *node)
I think you're filling a tuple store, not a tuple slot.
+ initStringInfo(&buf);
What seems to happen here is that you create an empty buffer, add
fsstate->query to it and nothing else, and then use buf.data. So why
not just get rid of buf and use fsstate->query directly?
+ /* Always fetch the last prev_query */
+ for (; p1->next != NULL; p1 = p1->next);
There are multiple problems here. First, this code is not per
PostgreSQL style and would be reindented by pgindent, which you should
make a habit of running before posting. Second, p1 is not a
particularly informative or understandable variable name. Third, why
are we using a linked list if the value we're going to need is at the
end of the list? If we need to be able to access the last element of
the list efficiently, maybe we should be keeping the list in reverse
order, or maybe we should be using a List which permits efficient
random access.
But looking quickly through the patch, I have an even bigger question
here. It doesn't really seem like we ever care about any element of
the list other than the last. It looks like we go to a fair amount of
trouble to maintain the list at various points in the code, but it
seems like when we access the list, we just always go to the end. That
makes me wonder why we even need a list. Perhaps instead of
PgFdwConnState storing a pointer to "prev_queries", it should just
store a pointer to the PgFdwScanState for the query that is currently
"using" the connection, if there is one. That is, the query whose
result set is currently being received, and which must be buffered
into a tuplestore before using the connection for something else. When
we've done that, we reset the field to NULL, and we don't maintain any
list of the older "previous queries". Maybe there's some problem with
that idea, but that gets back to my earlier point about comments: the
comment for "next" (or however it got renamed) ought to be explaining
something about why it exists and what it's for. Without such a
comment, the only ways for me to be sure whether we really need "next"
is to either (a) ask you or (b) spend a long time staring at the code
to try to figure it out or (c) try removing it and see if it works.
Ah, wait! I just found some code that cares about the list but not
just about the last element:
+ for (; p1->next != NULL; p1 = p1->next)
+ /* find the correct prev_query */
+ {
+ if ((p1->tuples_ready && fsstate->cursor_number == p1->cursor_number))
+ cur_prev = p1;
+ }
But I'm still confused. Why do we need to iterate through the
prev_queries list to find the correct ForeignScanState? Isn't that
exactly what fsstate is here? I'm inclined to think that this is just
a complicated way of setting p1 = fsstate and then setting cur_prev =
p1, so we could skip all this and just test whether
fsstate->tuplestore != NULL and if so retrieve tuples from there. If
there's some reason why fsstate and cur_prev would end up being
different, then there should be some comment explaining it. I'm
inclined to think that would be a sign of a design flaw: I think the
idea here should be to make use of the ForeignScanState object that
already exists to hold the details that we need for this feature,
rather than creating a new one. But, if there were a comment telling
me why it's like this, I might change my mind.
+ /* Clear the last query details, once tuples are retrieved. */
+ if (fsstate->conn_state->prev_queries == cur_prev)
+ {
+ /*
+ * This is the first prev query in the list, check if there
+ * are more
+ */
+ if (fsstate->conn_state->num_prev_queries > 1)
+
+ /*
+ * fsstate->conn_state->prev_queries->next =
+ * cur_prev->next;
+ */
+ fsstate->next = cur_prev->next;
+ clear_prev_query_state(cur_prev);
+ }
This code can remove an item from the prev_queries list, but only if
it's the first item. Now, if my analysis above is correct and we don't
even need the prev_queries list, then it doesn't matter; all this
logic can basically go away. If we do need the prev_queries list, then
I don't think it can be right to only be able to remove the first
element of the list. There's no reason why the oldest prev_query has
to finish first. What if there are three queries in the list and the
middle one finishes first? Then this will just leave it in the list,
whereas if the first one had finished first, it would have been
deleted from the list. That kind of inconsistency doesn't seem like a
good idea.
+ /*
+ * This is to fetch all the tuples of this query and save
+ * them in Tuple Slot. Since it is using
+ * PQSetChunkedRowsMode, we only get the
+ * fsstate->fetch_size tuples in one run, so keep on
+ * executing till we get NULL in PGresult i.e. all the
+ * tuples are retrieved.
+ */
+ p1->tuplestore = tuplestore_begin_heap(false, true, work_mem);
+ p1->slot = MakeSingleTupleTableSlot(fsstate->tupdesc, &TTSOpsMinimalTuple);
The slot doesn't seem to be used anywhere in the code that follows. Is
there a reason to initialize it here, rather than wherever it's
needed? If so, maybe the comment could mention that.
+ i = 0;
I don't think this does anything, because you reinitialize i in the
inner loop where you use it. In general, try moving your variable
declarations to the innermost scope where they are needed. It makes
the code more clear and allows the compiler to tell you about stuff
like this.
+ else if (PQresultStatus(res) == PGRES_TUPLES_OK)
+ {
+ while (res != NULL)
+ res = pgfdw_get_result(conn);
+ break;
+ }
I doubt that that this is right. It seems like it's willing to throw
away an infinite number of result sets without doing anything with
them, or discard an infinite number of errors without processing them,
but that doesn't seem likely to be the right thing.
+ else if (PQresultStatus(res) == PGRES_FATAL_ERROR)
+ {
+ clear_conn_state(fsstate->conn_state);
+ pgfdw_report_error(res, conn, fsstate->query);
+ }
I also doubt that this is right. If it's necessary to call
clear_conn_state() before reporting this error, then the error
handling in this patch is probably wrong. We don't know where errors
will be thrown in general and cannot rely on being able to do manual
error cleanup before an error occurs. The goal should for it to be
safe for pgfdw_report_error -- or just ereport(ERROR, ...) -- to
happen anywhere without causing problems in the future.
clear_conn_state() doesn't look right either. It does some cleanup on
each element of the prev_queries list and decrements num_prev_queries,
but it doesn't actually remove the queries from the list. So after
calling this function the first time, I think that num_prev_queries
might end up being 0 while prev_queries is still a list of the same
length as before. After that, I imagine calling clear_conn_state() a
second time would result in num_prev_queries going negative. I don't
really understand why num_prev_queries exists -- it seems like it's
just a recipe for mistakes to have both the list itself, and a
separate field that gives you the list length. If you need that, the
existing List data type will do that bookkeeping for you, and then
there's less opportunity for mistakes.
Overall, I think the direction of the patch set has some promise, but
I think it needs a lot of cleanup: removal of unnecessary code, proper
formatting, moving variables to inner scopes, explanatory comments,
good names for variables and functions and structure members, removal
of unnecessary files from the patch, cleanup of the regression test
coverage so that it doesn't add more bloat than necessary, proper
choice of data structures, and so on. Right now, the good things that
you've done here are being hidden by these sorts of mechanical issues.
That's not just an issue for me as a reviewer: I suspect it's also
blocking you, as the patch author, from finding places where the code
could be made better. Being able to find such opportunities for
improvement and act on them is what will get this patch from
"interesting proof of concept" to "potentially committable patch".
--
Robert Haas
EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
Rafia Sabih писал(а) 2025-11-27 13:50: > On Tue, 25 Nov 2025 at 15:24, KENAN YILMAZ > wrote: > >> Hello Hackers, >> >> I have executed use_cursor = true/false with quick tests. >> Hi. I've looked at this patch, because also was playing with tuplestore in PgFdwScanState to have more predictable memory usage with large fetch_size. Unfortunately, I've found that you can't use TTSOpsMinimalTuple(?) tuplestore to store tuple's ctid. I hoped this patch provides some solution for this issue, but no, it seems have the same problem. Attaching test case with a reproducer. -- Best regards, Alexander Pyhalov, Postgres Professional
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Wed, 10 Dec 2025 at 18:44, Robert Haas <robertmhaas@gmail.com> wrote:
Overall, I think the direction of the patch set has some promise, but
I think it needs a lot of cleanup: removal of unnecessary code, proper
formatting, moving variables to inner scopes, explanatory comments,
good names for variables and functions and structure members, removal
of unnecessary files from the patch, cleanup of the regression test
coverage so that it doesn't add more bloat than necessary, proper
choice of data structures, and so on. Right now, the good things that
you've done here are being hidden by these sorts of mechanical issues.
That's not just an issue for me as a reviewer: I suspect it's also
blocking you, as the patch author, from finding places where the code
could be made better. Being able to find such opportunities for
improvement and act on them is what will get this patch from
"interesting proof of concept" to "potentially committable patch".
--
Robert Haas
EDB: http://www.enterprisedb.com
Thanks Robert for your time and attention to this patch.
Based on these review comments and an off list discussion about the design of the patch, I have reworked the patch significantly.
In this version, a tuplestore is added to the PgFdwScanState along with a flag. Now, in case of a cursor switch, this tuplestore is filled with the remaining tuples of the query. The corresponding flag is set to indicate that the tuplestore is ready to be fetched. To remember the last query that was executing, a pointer to its PgFdwScanState is maintained in the conn_state. Note that we only need to remember just the very last query and once tuples for it are fetched we can forget that pointer, because now its fsstate has the remaining tuples in the tuplestore.
So, this version of the patch looks simpler than before.
A few test cases are also added in the attached patch to cover the different scenarios in case of non-cursor mode.
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
Came to know that there were some CI failures. Posting the new version of the patch which fixes them.
On Mon, 26 Jan 2026 at 03:44, Rafia Sabih <rafia.pghackers@gmail.com> wrote:
On Wed, 10 Dec 2025 at 18:44, Robert Haas <robertmhaas@gmail.com> wrote:
Overall, I think the direction of the patch set has some promise, but
I think it needs a lot of cleanup: removal of unnecessary code, proper
formatting, moving variables to inner scopes, explanatory comments,
good names for variables and functions and structure members, removal
of unnecessary files from the patch, cleanup of the regression test
coverage so that it doesn't add more bloat than necessary, proper
choice of data structures, and so on. Right now, the good things that
you've done here are being hidden by these sorts of mechanical issues.
That's not just an issue for me as a reviewer: I suspect it's also
blocking you, as the patch author, from finding places where the code
could be made better. Being able to find such opportunities for
improvement and act on them is what will get this patch from
"interesting proof of concept" to "potentially committable patch".
--
Robert Haas
EDB: http://www.enterprisedb.com--
Thanks Robert for your time and attention to this patch.Based on these review comments and an off list discussion about the design of the patch, I have reworked the patch significantly.In this version, a tuplestore is added to the PgFdwScanState along with a flag. Now, in case of a cursor switch, this tuplestore is filled with the remaining tuples of the query. The corresponding flag is set to indicate that the tuplestore is ready to be fetched. To remember the last query that was executing, a pointer to its PgFdwScanState is maintained in the conn_state. Note that we only need to remember just the very last query and once tuples for it are fetched we can forget that pointer, because now its fsstate has the remaining tuples in the tuplestore.So, this version of the patch looks simpler than before.A few test cases are also added in the attached patch to cover the different scenarios in case of non-cursor mode.Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Jan 26, 2026 at 6:44 AM Rafia Sabih wrote:
> Thanks Robert for your time and attention to this patch.
> Based on these review comments and an off list discussion about the design of the patch, I have reworked the patch significantly.
> In this version, a tuplestore is added to the PgFdwScanState along with a flag. Now, in case of a cursor switch, this tuplestore is filled with the remaining tuples of the query. The corresponding flag is set to indicate that the tuplestore is ready to be fetched. To remember the last query that was executing, a pointer to its PgFdwScanState is maintained in the conn_state. Note that we only need to remember just the very last query and once tuples for it are fetched we can forget that pointer, because now its fsstate has the remaining tuples in the tuplestore.
> So, this version of the patch looks simpler than before.
> A few test cases are also added in the attached patch to cover the different scenarios in case of non-cursor mode.
+ DefineCustomBoolVariable("postgres_fdw.use_cursor",
Usually I would expect the GUC for a few feature to be defined in such
a way that a true values means to use the new feature and a false
value means not to do that. This is reversed. Maybe consider renaming
the GUC so that the sense is inverted.
+ /* To be used only in non-cursor mode */
+ Tuplestorestate *tuplestore; /* Tuplestore to save the tuples of the
+
* query for later fetc
h. */
+ TupleTableSlot *slot; /* Slot to be used when
reading the tuple from
+ * the
tuplestore */
+ bool tuples_ready; /* To indicate when tuplestore
is ready to be
+ * read. */
+ int total_tuples; /* total tuples in the
tuplestore. */
There's already a tuplestore_tuple_count() function, so it's not clear
why you need total_tuples. It's also not exactly clear what
tuples_ready means here: sure, it means that we're ready to read
tuples, but when does that happen? I think the /* To be used only in
non-cursor mode */ comment could use expansion, too. Maybe use this to
explain the idea that we're going to use a Tuplestore in non-cursor
mode when, and only when, there are overlapping scans.
+ fsstate->conn_state->last_query = NULL;
I think this should be called something like active_scan. last_query
makes it sound like the last query we ran, whether or not it is still
in progress. But the value that it points to is an PgFdwScanState, so
it's not a query, it's a scan, and we should only have this set to a
non-NULL value for as long as that scan is actually active (i.e. has
the exclusive use of the connection).
+ * This routine fetches all the tuples of a query and saves them in a
tuplestore.
+ * This is required when the result of a query is not completely
fetched but the control
+ * switches to a different query.
+ * A call to fetch_data is made from here, hence we need complete
ForeignScanState here.
This is a good explanation but the last sentence probably isn't
needed. Also, you don't mention that this only used in non-cursor mode
(or whatever we end up calling it).
+ if (conn->asyncStatus == PGASYNC_IDLE)
+ {
+ /* If the connection is not active then set up */
+ if (!PQsendQueryParams(conn, last_fsstate->query,
last_fsstate->numParams,
+ NULL,
values, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, last_fsstate->query);
+
+ if (!PQsetChunkedRowsMode(conn, last_fsstate->fetch_size))
+ pgfdw_report_error(NULL, conn, last_fsstate->query);
+ }
I think this is a problem for multiple reasons. One problem is that
the function header says that we use this "when the result of a query
is not completely fetched". But if the status where PGASYNC_IDLE, the
query has not even started yet. In that case, seems there is no reason
to call this function in the first place. We can just start the new
scan right away and wait to do anything about the other scan until
it's needed. Additionally, asyncStatus is not part of libpq's exposed
API. You're only able to access it here because you've included
libpq-int.h into postgres_fdw.h, but libpq-int.h is so-called because
it's "internal", so you should really be trying very hard not to use
it, and especially not to include it in another header file. I suggest
that there's probably just a bug here -- I don't think you should need
to check asyncStatus here in the first place.
+ if (pgfdw_use_cursor)
+ snprintf(sql, sizeof(sql), "CLOSE c%u",
+ fsstate->cursor_number);
+ else
+ close_cursor = true;
This is extremely confusing coding. If we're using a cursor, we write
some SQL into a buffer but don't actually do anything with the buffer
right away. But if we're not using a cursor, then we set a flag that
tells us to close a cursor ... which we're not using? I think the
logic updates in the function are not at all clear. You need to back
up and think more carefully about what the function is supposed to do
in each case. Look at how the function starts after your patch:
postgresReScanForeignScan(ForeignScanState *node)
{
PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
char sql[64];
PGresult *res;
bool close_cursor = false;
/* If we haven't created the cursor yet, nothing to do. */
if (!fsstate->cursor_exists)
return;
Well, if we're in non-cursor mode, that presumably means this function
always returns without doing anything, since there should not be a
cursor if we are not using with them. That can't be right.
Alternatively, maybe it means that the cursor_exists flag is now being
used to track something other than whether a cursor exists, which
wouldn't be right either. I don't know off the top of my head exactly
what this function should do in each case, but as the patch author,
it's your job to go through, figure that out, and make sure that it is
all correct and well-commented.
Similarly, you have a bunch of changes to a function called
create_cursor(), but why would a function that creates a cursor get
changed to handle a mode where we don't create cursors? Either the
function needs to be renamed, or there should be two separate
functions, or these changes don't do anything in the first place.
+ while (res != NULL)
+ res = pgfdw_get_result(fsstate->conn);
I don't see how this code can be right. We should know how many result
sets we expect and read exactly that number, not just read over and
over until there's nothing more. But even if we did want to read until
there's nothing more, we would need to free those result sets rather
than leaking them.
-
- /* Clean up */
- pfree(buf.data);
It's hard to understand why this would be a good idea.
/*
* We'll store the tuples in the batch_cxt. First, flush the previous
* batch.
*/
fsstate->tuples = NULL;
- MemoryContextReset(fsstate->batch_cxt);
oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
It's also hard to understand why this would be a good idea. It seems
like it makes the comment false: we wouldn't be flushing the previous
batch any more. We'd just be forgetting that it existed and leaking
the memory.
+ /*
+ * In non-cursor mode, there are three options for the further
+ * processing: 1. If the tuplestore is already filled, retrieve the
+ * tuples from there. 2. Fetch the tuples till the end of the query
+ * and store them in tuplestore. 3. Perform a normal fetch and process
+ * the tuples.
I find this comment pretty confusing. First of all, it's not really
clear what performing a "normal fetch" means here. But also, this says
that in non-cursor mode there are three options, and that's followed
by an if-else block i.e. two options. Three isn't the same as two, so
something isn't right here.
The code that follows is quite involved. It's rather deeply nested in
places, so possibly some of it needs to be broken out into separate
functions. It contains another instance, of this, which has the same
problems I pointed out earlier:
+ /* There are no more tuples to fetch */
+ while (res != NULL)
+ res = pgfdw_get_result(conn);
If there are no more tuples to fetch, then why do we need to loop
fetching result sets until we get a NULL? And if we ever get any, we
leak them, which is also bad.
+ /*
+ * Reset cursor mode when in asynchronous mode as it is not supported in
+ * non-cursor mode
+ */
+ if (!pgfdw_use_cursor)
+ pgfdw_use_cursor = true;
It's not allowed to change a GUC variable from outside of the GUC
code. If you need to disable the optimization in certain cases, you
need a separate flag for that, which is initially set based on
pgfdw_use_cursor and then can be changed here or wherever is needed.
You can't change the GUC value itself. This would cause a variety of
problems, including the fact that the optimization would then stay
disabled for later queries in the session, but probably also some more
GUC-related stuff.
-
SELECT current_database() AS current_database,
current_setting('port') AS current_port
\gset
-
Please avoid including unnecessary cosmetic changes in the patch file.
Overall, I think the test case changes are in much better shape than
they were in earlier patch versions. I suspect there might still be a
bit of room for improvement, but we can deal with that once some of
these other issues are sorted out.
--
Robert Haas
EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Fri, 6 Mar 2026 at 21:51, Robert Haas <robertmhaas@gmail.com> wrote:
On Mon, Jan 26, 2026 at 6:44 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Thanks Robert for your time and attention to this patch.
> Based on these review comments and an off list discussion about the design of the patch, I have reworked the patch significantly.
> In this version, a tuplestore is added to the PgFdwScanState along with a flag. Now, in case of a cursor switch, this tuplestore is filled with the remaining tuples of the query. The corresponding flag is set to indicate that the tuplestore is ready to be fetched. To remember the last query that was executing, a pointer to its PgFdwScanState is maintained in the conn_state. Note that we only need to remember just the very last query and once tuples for it are fetched we can forget that pointer, because now its fsstate has the remaining tuples in the tuplestore.
> So, this version of the patch looks simpler than before.
> A few test cases are also added in the attached patch to cover the different scenarios in case of non-cursor mode.
+ DefineCustomBoolVariable("postgres_fdw.use_cursor",
Usually I would expect the GUC for a few feature to be defined in such
a way that a true values means to use the new feature and a false
value means not to do that. This is reversed. Maybe consider renaming
the GUC so that the sense is inverted.
+ /* To be used only in non-cursor mode */
+ Tuplestorestate *tuplestore; /* Tuplestore to save the tuples of the
+
* query for later fetc
h. */
+ TupleTableSlot *slot; /* Slot to be used when
reading the tuple from
+ * the
tuplestore */
+ bool tuples_ready; /* To indicate when tuplestore
is ready to be
+ * read. */
+ int total_tuples; /* total tuples in the
tuplestore. */
There's already a tuplestore_tuple_count() function, so it's not clear
why you need total_tuples. It's also not exactly clear what
tuples_ready means here: sure, it means that we're ready to read
tuples, but when does that happen? I think the /* To be used only in
non-cursor mode */ comment could use expansion, too. Maybe use this to
explain the idea that we're going to use a Tuplestore in non-cursor
mode when, and only when, there are overlapping scans.
+ fsstate->conn_state->last_query = NULL;
I think this should be called something like active_scan. last_query
makes it sound like the last query we ran, whether or not it is still
in progress. But the value that it points to is an PgFdwScanState, so
it's not a query, it's a scan, and we should only have this set to a
non-NULL value for as long as that scan is actually active (i.e. has
the exclusive use of the connection).
+ * This routine fetches all the tuples of a query and saves them in a
tuplestore.
+ * This is required when the result of a query is not completely
fetched but the control
+ * switches to a different query.
+ * A call to fetch_data is made from here, hence we need complete
ForeignScanState here.
This is a good explanation but the last sentence probably isn't
needed. Also, you don't mention that this only used in non-cursor mode
(or whatever we end up calling it).
+ if (conn->asyncStatus == PGASYNC_IDLE)
+ {
+ /* If the connection is not active then set up */
+ if (!PQsendQueryParams(conn, last_fsstate->query,
last_fsstate->numParams,
+ NULL,
values, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, last_fsstate->query);
+
+ if (!PQsetChunkedRowsMode(conn, last_fsstate->fetch_size))
+ pgfdw_report_error(NULL, conn, last_fsstate->query);
+ }
I think this is a problem for multiple reasons. One problem is that
the function header says that we use this "when the result of a query
is not completely fetched". But if the status where PGASYNC_IDLE, the
query has not even started yet. In that case, seems there is no reason
to call this function in the first place. We can just start the new
scan right away and wait to do anything about the other scan until
it's needed. Additionally, asyncStatus is not part of libpq's exposed
API. You're only able to access it here because you've included
libpq-int.h into postgres_fdw.h, but libpq-int.h is so-called because
it's "internal", so you should really be trying very hard not to use
it, and especially not to include it in another header file. I suggest
that there's probably just a bug here -- I don't think you should need
to check asyncStatus here in the first place.
+ if (pgfdw_use_cursor)
+ snprintf(sql, sizeof(sql), "CLOSE c%u",
+ fsstate->cursor_number);
+ else
+ close_cursor = true;
This is extremely confusing coding. If we're using a cursor, we write
some SQL into a buffer but don't actually do anything with the buffer
right away. But if we're not using a cursor, then we set a flag that
tells us to close a cursor ... which we're not using? I think the
logic updates in the function are not at all clear. You need to back
up and think more carefully about what the function is supposed to do
in each case. Look at how the function starts after your patch:
postgresReScanForeignScan(ForeignScanState *node)
{
PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
char sql[64];
PGresult *res;
bool close_cursor = false;
/* If we haven't created the cursor yet, nothing to do. */
if (!fsstate->cursor_exists)
return;
Well, if we're in non-cursor mode, that presumably means this function
always returns without doing anything, since there should not be a
cursor if we are not using with them. That can't be right.
Alternatively, maybe it means that the cursor_exists flag is now being
used to track something other than whether a cursor exists, which
wouldn't be right either. I don't know off the top of my head exactly
what this function should do in each case, but as the patch author,
it's your job to go through, figure that out, and make sure that it is
all correct and well-commented.
Similarly, you have a bunch of changes to a function called
create_cursor(), but why would a function that creates a cursor get
changed to handle a mode where we don't create cursors? Either the
function needs to be renamed, or there should be two separate
functions, or these changes don't do anything in the first place.
+ while (res != NULL)
+ res = pgfdw_get_result(fsstate->conn);
I don't see how this code can be right. We should know how many result
sets we expect and read exactly that number, not just read over and
over until there's nothing more. But even if we did want to read until
there's nothing more, we would need to free those result sets rather
than leaking them.
-
- /* Clean up */
- pfree(buf.data);
It's hard to understand why this would be a good idea.
/*
* We'll store the tuples in the batch_cxt. First, flush the previous
* batch.
*/
fsstate->tuples = NULL;
- MemoryContextReset(fsstate->batch_cxt);
oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
It's also hard to understand why this would be a good idea. It seems
like it makes the comment false: we wouldn't be flushing the previous
batch any more. We'd just be forgetting that it existed and leaking
the memory.
+ /*
+ * In non-cursor mode, there are three options for the further
+ * processing: 1. If the tuplestore is already filled, retrieve the
+ * tuples from there. 2. Fetch the tuples till the end of the query
+ * and store them in tuplestore. 3. Perform a normal fetch and process
+ * the tuples.
I find this comment pretty confusing. First of all, it's not really
clear what performing a "normal fetch" means here. But also, this says
that in non-cursor mode there are three options, and that's followed
by an if-else block i.e. two options. Three isn't the same as two, so
something isn't right here.
The code that follows is quite involved. It's rather deeply nested in
places, so possibly some of it needs to be broken out into separate
functions. It contains another instance, of this, which has the same
problems I pointed out earlier:
+ /* There are no more tuples to fetch */
+ while (res != NULL)
+ res = pgfdw_get_result(conn);
If there are no more tuples to fetch, then why do we need to loop
fetching result sets until we get a NULL? And if we ever get any, we
leak them, which is also bad.
+ /*
+ * Reset cursor mode when in asynchronous mode as it is not supported in
+ * non-cursor mode
+ */
+ if (!pgfdw_use_cursor)
+ pgfdw_use_cursor = true;
It's not allowed to change a GUC variable from outside of the GUC
code. If you need to disable the optimization in certain cases, you
need a separate flag for that, which is initially set based on
pgfdw_use_cursor and then can be changed here or wherever is needed.
You can't change the GUC value itself. This would cause a variety of
problems, including the fact that the optimization would then stay
disabled for later queries in the session, but probably also some more
GUC-related stuff.
-
SELECT current_database() AS current_database,
current_setting('port') AS current_port
\gset
-
Please avoid including unnecessary cosmetic changes in the patch file.
Overall, I think the test case changes are in much better shape than
they were in earlier patch versions. I suspect there might still be a
bit of room for improvement, but we can deal with that once some of
these other issues are sorted out.
--
Robert Haas
EDB: http://www.enterprisedb.com
Thank you for the detailed review of the patch. Please find the attached file for the updated patch.
To summarise the changes done in this patch following these review comments,
- the new GUC is called disable_cursor, so when we want to use this feature we set it, otherwise it remains false by default. I hope this makes it easier to understand as you mentioned.
- Simplified the code in fetch_more_data for this new mode. Now we have a function called fetch_from_tuplestore, and it is called from fetch_more_data when tuples from tuplestore are requested. Another function called save_to_tuplestore is also introduced in this patch, it is called from create_cursor code when all the tuples are to be fetched for the active_scan. So things look better code readability wise.
- For handling the async mode, I went to one level up and modified async_capable to false when no_cursor mode is used. So, now we do not change any GUC as such.
- With regards to use of flag cursor_exists and functions create_cursor and close_cursor, these are used in this no_cursor mode as well. For the flag cursor_exists, I used it to check if we have already done the required steps for when disale_cursor is set, like setting the ChunkedRowsMode, saving the tuples to the tuplestore if required. Inherently there is no nothing in fsstate or conn_state through which we can identify that all the required steps are done or if this scan is coming for the first time, so maybe we can have a different flag for the case when disable_cursor is set and use it for such checks. But to me it feels like additional code when I can use existing vars, but I agree on making it more readable that way. So, I modified in this patch to add a separate flag called scan_init and functions init_scan and end_scan for the setting and resetting of the required values when cursors are not used. So, let me know what you think is better using the existing flag or creating a new one for this mode as done in this patch.
- For this change,
/*
* We'll store the tuples in the batch_cxt. First, flush the previous
* batch.
*/
fsstate->tuples = NULL;
- MemoryContextReset(fsstate->batch_cxt);
oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
* We'll store the tuples in the batch_cxt. First, flush the previous
* batch.
*/
fsstate->tuples = NULL;
- MemoryContextReset(fsstate->batch_cxt);
oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
since, the tuplestore is now created in batch_cxt, so we can't reset it here. But I now changed it to be done only when disable_cursor is set.
- Regarding the following change,
+ if (conn->asyncStatus == PGASYNC_IDLE)
+ {
+ /* If the connection is not active then set up */
+ {
+ /* If the connection is not active then set up */
When we are here after the call to the rescan, the connection is as per the current fsstate which has not yet started, hence the idle status, but we are here to fetch the tuples for the active scan which got reset after the rescan so it is required to set it up again. But you are right in that using asyncStatus is not appropriate here, so I added a new flag to check for rescan, which is set in rescan and used here to decide if we need to set the ChunkedRowsMode.
- Modified and added more comments
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
Rebased version of the patch is attached.
It is a minor change from the earlier version.
On Thu, 2 Apr 2026 at 20:00, Rafia Sabih <rafia.pghackers@gmail.com> wrote:
On Fri, 6 Mar 2026 at 21:51, Robert Haas <robertmhaas@gmail.com> wrote:On Mon, Jan 26, 2026 at 6:44 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Thanks Robert for your time and attention to this patch.
> Based on these review comments and an off list discussion about the design of the patch, I have reworked the patch significantly.
> In this version, a tuplestore is added to the PgFdwScanState along with a flag. Now, in case of a cursor switch, this tuplestore is filled with the remaining tuples of the query. The corresponding flag is set to indicate that the tuplestore is ready to be fetched. To remember the last query that was executing, a pointer to its PgFdwScanState is maintained in the conn_state. Note that we only need to remember just the very last query and once tuples for it are fetched we can forget that pointer, because now its fsstate has the remaining tuples in the tuplestore.
> So, this version of the patch looks simpler than before.
> A few test cases are also added in the attached patch to cover the different scenarios in case of non-cursor mode.
+ DefineCustomBoolVariable("postgres_fdw.use_cursor",
Usually I would expect the GUC for a few feature to be defined in such
a way that a true values means to use the new feature and a false
value means not to do that. This is reversed. Maybe consider renaming
the GUC so that the sense is inverted.
+ /* To be used only in non-cursor mode */
+ Tuplestorestate *tuplestore; /* Tuplestore to save the tuples of the
+
* query for later fetc
h. */
+ TupleTableSlot *slot; /* Slot to be used when
reading the tuple from
+ * the
tuplestore */
+ bool tuples_ready; /* To indicate when tuplestore
is ready to be
+ * read. */
+ int total_tuples; /* total tuples in the
tuplestore. */
There's already a tuplestore_tuple_count() function, so it's not clear
why you need total_tuples. It's also not exactly clear what
tuples_ready means here: sure, it means that we're ready to read
tuples, but when does that happen? I think the /* To be used only in
non-cursor mode */ comment could use expansion, too. Maybe use this to
explain the idea that we're going to use a Tuplestore in non-cursor
mode when, and only when, there are overlapping scans.
+ fsstate->conn_state->last_query = NULL;
I think this should be called something like active_scan. last_query
makes it sound like the last query we ran, whether or not it is still
in progress. But the value that it points to is an PgFdwScanState, so
it's not a query, it's a scan, and we should only have this set to a
non-NULL value for as long as that scan is actually active (i.e. has
the exclusive use of the connection).
+ * This routine fetches all the tuples of a query and saves them in a
tuplestore.
+ * This is required when the result of a query is not completely
fetched but the control
+ * switches to a different query.
+ * A call to fetch_data is made from here, hence we need complete
ForeignScanState here.
This is a good explanation but the last sentence probably isn't
needed. Also, you don't mention that this only used in non-cursor mode
(or whatever we end up calling it).
+ if (conn->asyncStatus == PGASYNC_IDLE)
+ {
+ /* If the connection is not active then set up */
+ if (!PQsendQueryParams(conn, last_fsstate->query,
last_fsstate->numParams,
+ NULL,
values, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, last_fsstate->query);
+
+ if (!PQsetChunkedRowsMode(conn, last_fsstate->fetch_size))
+ pgfdw_report_error(NULL, conn, last_fsstate->query);
+ }
I think this is a problem for multiple reasons. One problem is that
the function header says that we use this "when the result of a query
is not completely fetched". But if the status where PGASYNC_IDLE, the
query has not even started yet. In that case, seems there is no reason
to call this function in the first place. We can just start the new
scan right away and wait to do anything about the other scan until
it's needed. Additionally, asyncStatus is not part of libpq's exposed
API. You're only able to access it here because you've included
libpq-int.h into postgres_fdw.h, but libpq-int.h is so-called because
it's "internal", so you should really be trying very hard not to use
it, and especially not to include it in another header file. I suggest
that there's probably just a bug here -- I don't think you should need
to check asyncStatus here in the first place.
+ if (pgfdw_use_cursor)
+ snprintf(sql, sizeof(sql), "CLOSE c%u",
+ fsstate->cursor_number);
+ else
+ close_cursor = true;
This is extremely confusing coding. If we're using a cursor, we write
some SQL into a buffer but don't actually do anything with the buffer
right away. But if we're not using a cursor, then we set a flag that
tells us to close a cursor ... which we're not using? I think the
logic updates in the function are not at all clear. You need to back
up and think more carefully about what the function is supposed to do
in each case. Look at how the function starts after your patch:
postgresReScanForeignScan(ForeignScanState *node)
{
PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
char sql[64];
PGresult *res;
bool close_cursor = false;
/* If we haven't created the cursor yet, nothing to do. */
if (!fsstate->cursor_exists)
return;
Well, if we're in non-cursor mode, that presumably means this function
always returns without doing anything, since there should not be a
cursor if we are not using with them. That can't be right.
Alternatively, maybe it means that the cursor_exists flag is now being
used to track something other than whether a cursor exists, which
wouldn't be right either. I don't know off the top of my head exactly
what this function should do in each case, but as the patch author,
it's your job to go through, figure that out, and make sure that it is
all correct and well-commented.
Similarly, you have a bunch of changes to a function called
create_cursor(), but why would a function that creates a cursor get
changed to handle a mode where we don't create cursors? Either the
function needs to be renamed, or there should be two separate
functions, or these changes don't do anything in the first place.
+ while (res != NULL)
+ res = pgfdw_get_result(fsstate->conn);
I don't see how this code can be right. We should know how many result
sets we expect and read exactly that number, not just read over and
over until there's nothing more. But even if we did want to read until
there's nothing more, we would need to free those result sets rather
than leaking them.
-
- /* Clean up */
- pfree(buf.data);
It's hard to understand why this would be a good idea.
/*
* We'll store the tuples in the batch_cxt. First, flush the previous
* batch.
*/
fsstate->tuples = NULL;
- MemoryContextReset(fsstate->batch_cxt);
oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
It's also hard to understand why this would be a good idea. It seems
like it makes the comment false: we wouldn't be flushing the previous
batch any more. We'd just be forgetting that it existed and leaking
the memory.
+ /*
+ * In non-cursor mode, there are three options for the further
+ * processing: 1. If the tuplestore is already filled, retrieve the
+ * tuples from there. 2. Fetch the tuples till the end of the query
+ * and store them in tuplestore. 3. Perform a normal fetch and process
+ * the tuples.
I find this comment pretty confusing. First of all, it's not really
clear what performing a "normal fetch" means here. But also, this says
that in non-cursor mode there are three options, and that's followed
by an if-else block i.e. two options. Three isn't the same as two, so
something isn't right here.
The code that follows is quite involved. It's rather deeply nested in
places, so possibly some of it needs to be broken out into separate
functions. It contains another instance, of this, which has the same
problems I pointed out earlier:
+ /* There are no more tuples to fetch */
+ while (res != NULL)
+ res = pgfdw_get_result(conn);
If there are no more tuples to fetch, then why do we need to loop
fetching result sets until we get a NULL? And if we ever get any, we
leak them, which is also bad.
+ /*
+ * Reset cursor mode when in asynchronous mode as it is not supported in
+ * non-cursor mode
+ */
+ if (!pgfdw_use_cursor)
+ pgfdw_use_cursor = true;
It's not allowed to change a GUC variable from outside of the GUC
code. If you need to disable the optimization in certain cases, you
need a separate flag for that, which is initially set based on
pgfdw_use_cursor and then can be changed here or wherever is needed.
You can't change the GUC value itself. This would cause a variety of
problems, including the fact that the optimization would then stay
disabled for later queries in the session, but probably also some more
GUC-related stuff.
-
SELECT current_database() AS current_database,
current_setting('port') AS current_port
\gset
-
Please avoid including unnecessary cosmetic changes in the patch file.
Overall, I think the test case changes are in much better shape than
they were in earlier patch versions. I suspect there might still be a
bit of room for improvement, but we can deal with that once some of
these other issues are sorted out.
--
Robert Haas
EDB: http://www.enterprisedb.comThank you for the detailed review of the patch. Please find the attached file for the updated patch.--To summarise the changes done in this patch following these review comments,- the new GUC is called disable_cursor, so when we want to use this feature we set it, otherwise it remains false by default. I hope this makes it easier to understand as you mentioned.- Simplified the code in fetch_more_data for this new mode. Now we have a function called fetch_from_tuplestore, and it is called from fetch_more_data when tuples from tuplestore are requested. Another function called save_to_tuplestore is also introduced in this patch, it is called from create_cursor code when all the tuples are to be fetched for the active_scan. So things look better code readability wise.- For handling the async mode, I went to one level up and modified async_capable to false when no_cursor mode is used. So, now we do not change any GUC as such.- With regards to use of flag cursor_exists and functions create_cursor and close_cursor, these are used in this no_cursor mode as well. For the flag cursor_exists, I used it to check if we have already done the required steps for when disale_cursor is set, like setting the ChunkedRowsMode, saving the tuples to the tuplestore if required. Inherently there is no nothing in fsstate or conn_state through which we can identify that all the required steps are done or if this scan is coming for the first time, so maybe we can have a different flag for the case when disable_cursor is set and use it for such checks. But to me it feels like additional code when I can use existing vars, but I agree on making it more readable that way. So, I modified in this patch to add a separate flag called scan_init and functions init_scan and end_scan for the setting and resetting of the required values when cursors are not used. So, let me know what you think is better using the existing flag or creating a new one for this mode as done in this patch.- For this change,/*
* We'll store the tuples in the batch_cxt. First, flush the previous
* batch.
*/
fsstate->tuples = NULL;
- MemoryContextReset(fsstate->batch_cxt);
oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);since, the tuplestore is now created in batch_cxt, so we can't reset it here. But I now changed it to be done only when disable_cursor is set.- Regarding the following change,+ if (conn->asyncStatus == PGASYNC_IDLE)
+ {
+ /* If the connection is not active then set up */When we are here after the call to the rescan, the connection is as per the current fsstate which has not yet started, hence the idle status, but we are here to fetch the tuples for the active scan which got reset after the rescan so it is required to set it up again. But you are right in that using asyncStatus is not appropriate here, so I added a new flag to check for rescan, which is set in rescan and used here to decide if we need to set the ChunkedRowsMode.- Modified and added more commentsRegards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Apr 10, 2026 at 3:42 AM Rafia Sabih wrote:
> Rebased version of the patch is attached.
> It is a minor change from the earlier version.
Hi,
Some issues:
- fetch_more_data() still gains a use_tuplestore parameter, but now
it's always false and never used for anything. already_done is also
dead code; it's never set to anything but false. There are also other
places in the patch where you haven't cleaned up things that aren't
needed any more.
- I think that instead of add scan_init alongside cursor_exists, it
might be better to just rename the existing cursor_exists flag and use
it in both modes. Right now, you've got a bunch of places in the code
where when disable_cursor has one value you look at cursor_exists and
when it has the other value you look at scan_init; basically, the two
flags seem to be the same thing, and only the name of the flag doesn't
make sense after your patch. But I would suggest calling it
scan_in_progress rather than scan_init, because it gets set back to
false in postgresEndForeignScan() when the scan finishes. In fact, I
would suggest creating a preparatory patch that does the cursor_exists
-> scan_in_progress renaming and make that 0001, and then make your
main patch 0002 on top of that. That patch could possibly be committed
separately at some point.
- postgresBeginForeignScan incorrectly does this:
/* Initially, there is no active_scan */
fsstate->conn_state->active_scan = NULL;
I think this is compensating for the lack of anything to clear
active_scan in postgresEndForeignScan; if you didn't do this, then
probably the first query using non-cursor mode would work and the
second one would fail. But the right fix is to remove this and make
postgresEndForeignScan clean it up properly instead. Otherwise,
imagine that query A begins using a postgres_fdw connection and is in
the middle of streaming a result set over the wire when a call to a
user-defined function triggers query B which accesses the same
postgres_fdw connection. This logic now nulls out the active-scan
pointer from the outer connection while in reality that outer
connection is still active. I expect terrible things to happen after
that. You might want to try to create a test case that exercises this
scenario.
- The logic in postgresReScanForeignScan() has multiple flaws. One of
these is, as you probably know already, where it says /* TODO: Handle
it in non-cursor mode as well */. Let's think through how this needs
to work a little bit. When we're using a cursor, we have three
possible strategies: we can close the cursor and re-execute the query,
we can use MOVE BACKWARD ALL, or if we still have every tuple we've
ever fetched from the remote side, we can just rescan them (the "Easy"
case). When there's no cursor, only two strategies are possible --
there's no equivalent of MOVE BACKWARD ALL. We can either throw away
the tuplestore we've accumulated and any results that are still being
received from the remote side (which is similar to "CLOSE") or we just
rewind our internal scan position (the "Easy" case).
So what I would suggest here is: set a local variable
reinitialize_scan = false at the top. In the cases where we currently
print CLOSE c%u, just set reinitialize_scan = true. In the MOVE
BACKWARD ALL case (fetch_ct_2 > 1 and PQserverVersion(fsstate->conn) <
150000 and !disable_cursor), construct the query, execute it, and
return from the function right there. Otherwise, fall through to the
end of the function and deal with what reinitializing the scan means
in the cursor case (CLOSE %u) and in the non-cursor case. But here we
come to a second bug: right now, you try to reinitialize the scan in
the disable_cursor case by just calling pgfdw_get_result(), but you do
so without checking whether the scan that we're rescanning is the same
as the active scan. If it is, then you need to do this, but if it
isn't, then you must not. Either way, you might also need to discard
any tuplestore that has been collected.
There's also the case where you don't reinitialize the scan, which is
the easy case: whether cursors are in use or not, you just need to
reset your notion of what's been fetched. But here we come to another
problem: fetch_ct_2 is, I would argue, not maintained properly in
non-cursor mode. In cursor mode, 0 means we haven't yet read any
tuples, 1 means we've read some tuples but not yet thrown any away,
and 2 means that some have been discarded. If it had the same meaning
in non-cursor mode, then the rescan code could use that value to
decide whether to take the "Easy" path where it just resets
next_tuple. But it doesn't: fetch_ct_2 in non-cursor mode just counts
the number of calls to fetch_more_data(), which doesn't tell us
anything about what rescan should do.
- The logic in postgresEndForeignScan has one of the same problems
that I mentioned in the previous point: it will call
pgfdw_get_result() even when the scan being ended is not the active
scan, and it doesn't deal with the associated tuplestore.
- save_to_tuplestore() gets confused between the scan FROM which it's
being called and the scan FOR which it's being called, or said
differently, it confuses the currently-active scan with the new scan
that we want to initiate. For instance, it tests fsscan->rescan to
decide whether to resend active_fsstate->query. That doesn't really
make any sense. I think a general problem with this patch is that it's
not clear exactly what the rescan flag is actually intended to mean,
but it certainly can't be right to decide that the query for plan node
A needs to be re-sent because plan node B is being rescanned. A little
further down, you switch to fsstate->batch_cxt to store tuples in
active_fsstate->tuplestore, which is another example of the same
confusion. You should probably have a function here that only gets the
*active* scan as an argument, so that you can't get mixed up like this
and mistakenly refer to the wrong one. We don't even know that fsstate
and active_fsstate are from the same query: recall the case I
mentioned earlier, where query A begins using a postgres_fdw
connection and is in the middle of streaming a result set over the
wire when a call to a user-defined function triggers query B which
accesses the same postgres_fdw connection.
- There are multiple points in save_to_tuplestore() where you can
overwrite res without calling PQclear() on the previous value of res.
You need to make sure that every place in the patch where you create a
PGresult, you also free it.
- You need to think about the fact that the GUC can be changed at any
time. disable_cursor could be true when the scan starts and false by
the time it ends, or false by the time it's rescanned, or it could be
true for an outer query that starts running a query on the connection
and then false by the time an inner level wants to use the same
connection for something else. Right now, if anything like that
happens, this code is going to fail terribly. I think you need every
scan to remember whether it was started with or without a cursor, and
do rescans and end-scans based on that, not the GUC. And even if the
*current* scan is being started with a cursor, that doesn't mean there
can't be a *previous* scan in progress that was started without using
a cursor; you need to make sure, for example, that
save_to_tuplestore() is still called in that case.
- I know I suggested inverting the sense of the GUC (the feature
should say what it does, not what it doesn't do) but I don't really
like disable_cursor as the name of the feature, either, because
defining the feature in terms of shutting off cursors is kind of
confusing. I think we should come up with a name for this feature that
doesn't have a negation in the name. Maybe something like
postgres_fdw.streaming_fetch = { true | false }? Or
postgres_fdw.fetch_mode = { cursor | stream }? That would be similar
to the existing fetch_size option; one could even argue for allowing
fetch_size = 0 to mean "don't use a cursor, just fetch everything,"
although maybe overloading the setting that way is a little too clever
(or maybe it's fine).
- But also note that postgres_fdw.fetch_size -- which, again, is
closely related to this feature -- is a table or server level option,
not a GUC. That suggests that this feature should also be a table or
server level option.
--
Robert Haas
EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Tue, 12 May 2026 at 14:56, Robert Haas <robertmhaas@gmail.com> wrote:
On Mon, May 11, 2026 at 7:03 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Thanks Robert for the detailed review and some great suggestions for improving this patch. I went through the comments and the patch and here is the revised version. To summarize the changes done in this patch,
> - as suggested, split it into two patches now, the first patch changes the cursor_exists flag to scan_in_progress, the second patch is the one with the rest of the changes to implement this fetch mechanism
> - changed the GUC to server/tables level option called streaming_fetch. Still a boolean type. Open to better naming suggestions.
> - refactored postrgesReScanForeignScan for a more readable code
> Following the suggestions above, now, it handles the case for the backward cursor separately and exits the function straight from there. In case of close cursor, it checks if cursor or cursor-free mode is used, and executes different actions as per the mode. In cursor-free mode we end_scan and tuplestore. In the third case when we start scanning the tuples already fetched, things remain the same in both modes.
> - added the changes to show the option in explain verbose output
> - Added a lot more test cases to check the option with other options and also to cover more code-paths, particularly rescans and ending the query in between, error cases etc.
>
> There is one problem that remains here, the use of ExprContext. We need this when we are fetching the tuples for the active scan, but since this is only available in node, we can not have the one which was there at the time when active_scan was the fsstate, so at the moment it is using the econtext from the node. This doesn't seem correct to me, but to have the correct ExprContext we need the node, but it also doesn't seem totally right to have the pointer to node in ScanState for this scenario. Please let me know what could be a good way to handle this.
The problem here is that save_to_tuplestore() has gotten itself into
the business of resending the query when a node is rescanned and we
haven't yet buffered the results anywhere. But it doesn't need to do
that in the first place. If the query needs to be resent, it's not
currently active on the connection, and then there's no need to do
anything to free up the connection, so save_to_tuplestore() doesn't
need to be called in the first place. The reason why you're having
this problem is that postgresReScanForeignScan calls end_scan but
end_scan does not clear the active_scan pointer. So then
save_to_tuplestore() gets called if something else tries to use the
connection, and to make that work, you did this.
But the right solution is to make sure that the active_scan pointer is
only non-NULL when there are actually results already on the wire that
need to be drained. If you do that, then save_to_tuplestore() won't
get called if rescan has already read all of the pending results off
the wire, and then you can delete the code that resends the query, and
then you won't need an econtext here in the first place.
Thanks Robert for the quick follow up on this. I found this to be true and modified the patch accordingly.
Please find the updated patches attached. In the first patch jnothing is changed, just adding it here for the sake of completeness.
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
One of the patch required a rebase, hence attaching the rebased patches.
On Wed, 20 May 2026 at 12:40, Rafia Sabih <rafia.pghackers@gmail.com> wrote:
On Tue, 12 May 2026 at 14:56, Robert Haas <robertmhaas@gmail.com> wrote:On Mon, May 11, 2026 at 7:03 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Thanks Robert for the detailed review and some great suggestions for improving this patch. I went through the comments and the patch and here is the revised version. To summarize the changes done in this patch,
> - as suggested, split it into two patches now, the first patch changes the cursor_exists flag to scan_in_progress, the second patch is the one with the rest of the changes to implement this fetch mechanism
> - changed the GUC to server/tables level option called streaming_fetch. Still a boolean type. Open to better naming suggestions.
> - refactored postrgesReScanForeignScan for a more readable code
> Following the suggestions above, now, it handles the case for the backward cursor separately and exits the function straight from there. In case of close cursor, it checks if cursor or cursor-free mode is used, and executes different actions as per the mode. In cursor-free mode we end_scan and tuplestore. In the third case when we start scanning the tuples already fetched, things remain the same in both modes.
> - added the changes to show the option in explain verbose output
> - Added a lot more test cases to check the option with other options and also to cover more code-paths, particularly rescans and ending the query in between, error cases etc.
>
> There is one problem that remains here, the use of ExprContext. We need this when we are fetching the tuples for the active scan, but since this is only available in node, we can not have the one which was there at the time when active_scan was the fsstate, so at the moment it is using the econtext from the node. This doesn't seem correct to me, but to have the correct ExprContext we need the node, but it also doesn't seem totally right to have the pointer to node in ScanState for this scenario. Please let me know what could be a good way to handle this.
The problem here is that save_to_tuplestore() has gotten itself into
the business of resending the query when a node is rescanned and we
haven't yet buffered the results anywhere. But it doesn't need to do
that in the first place. If the query needs to be resent, it's not
currently active on the connection, and then there's no need to do
anything to free up the connection, so save_to_tuplestore() doesn't
need to be called in the first place. The reason why you're having
this problem is that postgresReScanForeignScan calls end_scan but
end_scan does not clear the active_scan pointer. So then
save_to_tuplestore() gets called if something else tries to use the
connection, and to make that work, you did this.
But the right solution is to make sure that the active_scan pointer is
only non-NULL when there are actually results already on the wire that
need to be drained. If you do that, then save_to_tuplestore() won't
get called if rescan has already read all of the pending results off
the wire, and then you can delete the code that resends the query, and
then you won't need an econtext here in the first place.Thanks Robert for the quick follow up on this. I found this to be true and modified the patch accordingly.Please find the updated patches attached. In the first patch jnothing is changed, just adding it here for the sake of completeness.--Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Jun 5, 2026 at 5:03 AM Rafia Sabih wrote:
> One of the patch required a rebase, hence attaching the rebased patches.
Did you generate these patches with "git format-patch"? They don't
apply for me, because 0002 contains some of the same changes that are
also present in 0001. I strongly recommend always generating the patch
sets you post from a private branch using "git rebase master" followed
by "git format-patch -v$VERSION master".
You added a new member to FdwScanPrivateIndex which is fine, but you
put it in the middle instead of at the end, which might be OK but is
slightly surprising, and you didn't add a comment on the new member,
which is definitely not OK.
It appears to me that save_to_tuplestore() still has the same problems
that I have mentioned in previous reviews -- maybe not quite as badly,
but to some degree. For example, it still knows about both fsstate and
active_fsstate. Mostly, the references seem to all point to
active_fsstate now, but there is still a comment that refers to just
fsstate, and this whole setup of having two variables like this is
just very error-prone. I think it's really important to get rid of
that. Also, I still think this is wrong:
+ if (active_fsstate->rescan)
+ {
+ if (!PQsendQueryParams(conn, active_fsstate->query,
active_fsstate->numParams,
+ NULL,
active_fsstate->param_values, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, active_fsstate->query);
This is exactly what I talked about in
http://postgr.es/m/CA+TgmoZfxpohj1ag8PQyshKpFu+krUgeH0Xd=34Wvn29F5DWhw@mail.gmail.com
but it seems that it's not fixed: we're still sending the query if it
hasn't been sent yet, and we just shouldn't be doing that. I don't
think it's the right idea to have a "bool rescan" flag at all.
postgresReScanForeignScan just sets so that save_to_tuplestore can use
it to send the query when that's not actually needed in the first
place.
+ if (fsstate->conn_state->active_scan &&
+ fsstate != fsstate->conn_state->active_scan)
+ save_to_tuplestore(node);
I don't think this logic is correct. We shouldn't be trying to
initialize the current scan if the current scan is already active. It
seems to me that the only condition here should be the first one -- if
(fsstate_conn_state->active_scan == NULL) save_to_tuplestore(node). If
that's not sufficient, then it implies that init_scan() can be called
in some situation where the scan is already initialized, which is a
bug that should be fixed at its source, rather than here.
I generally recommend avoiding mention of specific details of the C
code in the regression tests. If you do that, as you have done, then
the SQL comments can need to be updated when the C code is changed,
even if the behavior has not changed, which is annoying.
I think that the changes to make_tuple_from_result_row are unlikely to
be correct. Why would this special handling be needed? If we're
passing the correct fsstate and the correct rel, then I don't
understand why the previous logic would produce the wrong answer. I
wonder if this is a holdover from an earlier patch version where
save_to_tuplestore() was more buggy than it is now. Or maybe it still
has a bug that we should fix. But I don't think changing
make_tuple_from_result_row is likely to be the right answer.
--
Robert Haas
EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Tue, 16 Jun 2026 at 14:58, Robert Haas <robertmhaas@gmail.com> wrote:
On Fri, Jun 5, 2026 at 5:03 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> One of the patch required a rebase, hence attaching the rebased patches.
Did you generate these patches with "git format-patch"? They don't
apply for me, because 0002 contains some of the same changes that are
also present in 0001. I strongly recommend always generating the patch
sets you post from a private branch using "git rebase master" followed
by "git format-patch -v$VERSION master".
The attached version should work properly.
You added a new member to FdwScanPrivateIndex which is fine, but you
put it in the middle instead of at the end, which might be OK but is
slightly surprising, and you didn't add a comment on the new member,
which is definitely not OK.
I added the comment now. I am not sure about the position, please do suggest if it is better at the end, I just added it to being closest to fetch_size.
It appears to me that save_to_tuplestore() still has the same problems
that I have mentioned in previous reviews -- maybe not quite as badly,
but to some degree. For example, it still knows about both fsstate and
active_fsstate. Mostly, the references seem to all point to
active_fsstate now, but there is still a comment that refers to just
fsstate, and this whole setup of having two variables like this is
just very error-prone. I think it's really important to get rid of
I understand your concern and I tried to solve it by passing fsstate now, also saving a backpointer to the node in active_fsstate to solve the issue with make_tuple_from_result_row. Since we need to have conn from fsstate, I am not sure how we can do that if we have only active_fsstate passed to the function.
that. Also, I still think this is wrong:
+ if (active_fsstate->rescan)
+ {
+ if (!PQsendQueryParams(conn, active_fsstate->query,
active_fsstate->numParams,
+ NULL,
active_fsstate->param_values, NULL, NULL, 0))
+ pgfdw_report_error(NULL, conn, active_fsstate->query);
This is exactly what I talked about in
http://postgr.es/m/CA+TgmoZfxpohj1ag8PQyshKpFu+krUgeH0Xd=34Wvn29F5DWhw@mail.gmail.com
but it seems that it's not fixed: we're still sending the query if it
hasn't been sent yet, and we just shouldn't be doing that. I don't
think it's the right idea to have a "bool rescan" flag at all.
postgresReScanForeignScan just sets so that save_to_tuplestore can use
it to send the query when that's not actually needed in the first
place.
Yes, it is removed in this version of the patch.
+ if (fsstate->conn_state->active_scan &&
+ fsstate != fsstate->conn_state->active_scan)
+ save_to_tuplestore(node);
I don't think this logic is correct. We shouldn't be trying to
initialize the current scan if the current scan is already active. It
seems to me that the only condition here should be the first one -- if
(fsstate_conn_state->active_scan == NULL) save_to_tuplestore(node). If
that's not sufficient, then it implies that init_scan() can be called
in some situation where the scan is already initialized, which is a
bug that should be fixed at its source, rather than here.
I generally recommend avoiding mention of specific details of the C
code in the regression tests. If you do that, as you have done, then
the SQL comments can need to be updated when the C code is changed,
even if the behavior has not changed, which is annoying.
Changed the comments.
I think that the changes to make_tuple_from_result_row are unlikely to
be correct. Why would this special handling be needed? If we're
passing the correct fsstate and the correct rel, then I don't
understand why the previous logic would produce the wrong answer. I
wonder if this is a holdover from an earlier patch version where
save_to_tuplestore() was more buggy than it is now. Or maybe it still
has a bug that we should fix. But I don't think changing
make_tuple_from_result_row is likely to be the right answer.
--
Robert Haas
EDB: http://www.enterprisedb.com
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Tue, Jun 23, 2026 at 5:38 AM Rafia Sabih wrote: > I understand your concern and I tried to solve it by passing fsstate now, also saving a backpointer to the node in active_fsstate to solve the issue with make_tuple_from_result_row. Since we need to have conn from fsstate, I am not sure how we can do that if we have only active_fsstate passed to the function. If fsstate->conn and active_fsstate->conn can be different, I think we have a big problem. The idea of save_to_tuplestore() is that there's a query running on the connection already and we have to finish reading its results before we can use the connection for something else. But that only makes sense if it's the SAME connection in both cases. If we're running a connection on connection A, there's no reason we need to do anything before sending a new query on connection B. -- Robert Haas EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Rafia Sabih <rafia.pghackers@gmail.com>
Дата:
On Fri, 26 Jun 2026 at 21:42, Robert Haas <robertmhaas@gmail.com> wrote:
On Tue, Jun 23, 2026 at 5:38 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> I understand your concern and I tried to solve it by passing fsstate now, also saving a backpointer to the node in active_fsstate to solve the issue with make_tuple_from_result_row. Since we need to have conn from fsstate, I am not sure how we can do that if we have only active_fsstate passed to the function.
If fsstate->conn and active_fsstate->conn can be different, I think we
have a big problem. The idea of save_to_tuplestore() is that there's a
query running on the connection already and we have to finish reading
its results before we can use the connection for something else. But
that only makes sense if it's the SAME connection in both cases. If
we're running a connection on connection A, there's no reason we need
to do anything before sending a new query on connection B.
So, do you suggest we can have a backpointer of conn also in active_fsstate...?
--
Robert Haas
EDB: http://www.enterprisedb.com
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Rafia Sabih <rafia.pghackers@gmail.com>
Дата:
On Thu, 2 Jul 2026 at 19:57, Robert Haas <robertmhaas@gmail.com> wrote:
On Mon, Jun 29, 2026 at 5:27 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> So, do you suggest we can have a backpointer of conn also in active_fsstate...?
I think that fsstate and active_fsstate have to be pointing to the
same conn_state object. Do you think otherwise?
No, but I don't understand why you think they can be different in the current implementation.
Currently, as per init_scan fsstate->conn_state->active_scan = fsstate, and it is never reassigned or anything.
So they cannot have different conn_state.
Am I missing something?
--
Robert Haas
EDB: http://www.enterprisedb.com
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
"Yilin Zhang" <jiezhilove@126.com>
Дата:
At 2026-07-03 20:51:12,"Rafia Sabih" <rafia.pghackers@gmail.com> wrote :
>
> No, but I don't understand why you think they can be different in the
> current implementation.
> Currently, as per init_scan fsstate->conn_state->active_scan = fsstate, and
> it is never reassigned or anything.
> So they cannot have different conn_state.
> Am I missing something?
>
This is the reproduction procedure for the crash caused by clearing active_scan that I mentioned last week.
Data preparation:
CREATE TABLE local_big (id int, val text);
CREATE TABLE local_big2 (id int, val text);
INSERT INTO local_big SELECT i, 'val_' || i FROM generate_series(1, 300000) i;
INSERT INTO local_big2 SELECT i, 'val_' || i FROM generate_series(1, 300000) i;
CREATE SERVER test_srv FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'localhost', port '55436', dbname 'test_bug2');
CREATE USER MAPPING FOR CURRENT_USER SERVER test_srv;
CREATE FOREIGN TABLE ft_big (id int, val text)
SERVER test_srv
OPTIONS (schema_name 'public', table_name 'local_big',
streaming_fetch 'true', fetch_size '1');
CREATE FOREIGN TABLE ft_small (id int, val text)
SERVER test_srv
OPTIONS (schema_name 'public', table_name 'local_big2',
streaming_fetch 'true', fetch_size '1');
session-1
DROP TABLE IF EXISTS bug2_pid;
CREATE TEMP TABLE bug2_pid (pid int);
INSERT INTO bug2_pid VALUES (pg_backend_pid()); -- pid_1
DO $$
DECLARE cnt int;
BEGIN
SET LOCAL enable_hashjoin = off;
SET LOCAL enable_mergejoin = off;
SELECT count(*) INTO cnt
FROM ft_big b, ft_small s
WHERE b.id = s.id
AND pg_backend_pid() > 0;
RAISE NOTICE 'completed: cnt=%', cnt;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'caught: %', SQLERRM;
END;
$$;
SELECT 'post_check' AS phase, count(*) FROM ft_big; -- CRASH HERE
session-2
SELECT pid FROM bug2_pid;
SELECT pg_cancel_backend(pid); -- After Session 1 enters the drain loop, execute pg_cancel_backend(pid) in Session 2.
I believe the issue regarding fsstate->conn and active_fsstate->conn that you've been discussing with Robert is related to this crash.
If only one PgFdwScanState* (active_fsstate) is available inside save_to_tuplestore, the assignment active_scan = NULL will clearly not be executed prior to draining.
The draining logic operates on data from active_fsstate, and we can only clear it after draining completes successfully.
Best regards,--Yilin Zhang
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Jul 3, 2026 at 8:51 AM Rafia Sabih wrote: > On Thu, 2 Jul 2026 at 19:57, Robert Haas wrote: >> On Mon, Jun 29, 2026 at 5:27 AM Rafia Sabih wrote: >> > So, do you suggest we can have a backpointer of conn also in active_fsstate...? >> >> I think that fsstate and active_fsstate have to be pointing to the >> same conn_state object. Do you think otherwise? >> > No, but I don't understand why you think they can be different in the current implementation. > Currently, as per init_scan fsstate->conn_state->active_scan = fsstate, and it is never reassigned or anything. > So they cannot have different conn_state. > Am I missing something? I don't think they can be different. I think you shouldn't be passing both of them, because save_to_tuplestore() is buggy if it ever references fsstate. If you only pass active_fsstate, then that can't happen. -- Robert Haas EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Mon, 6 Jul 2026 at 11:45, Yilin Zhang <jiezhilove@126.com> wrote:
At 2026-07-03 20:51:12,"Rafia Sabih" <rafia.pghackers@gmail.com> wrote :>> No, but I don't understand why you think they can be different in the> current implementation.> Currently, as per init_scan fsstate->conn_state->active_scan = fsstate, and> it is never reassigned or anything.> So they cannot have different conn_state.> Am I missing something?>This is the reproduction procedure for the crash caused by clearing active_scan that I mentioned last week.Data preparation:CREATE TABLE local_big (id int, val text);CREATE TABLE local_big2 (id int, val text);INSERT INTO local_big SELECT i, 'val_' || i FROM generate_series(1, 300000) i;INSERT INTO local_big2 SELECT i, 'val_' || i FROM generate_series(1, 300000) i;CREATE SERVER test_srv FOREIGN DATA WRAPPER postgres_fdwOPTIONS (host 'localhost', port '55436', dbname 'test_bug2');CREATE USER MAPPING FOR CURRENT_USER SERVER test_srv;CREATE FOREIGN TABLE ft_big (id int, val text)SERVER test_srvOPTIONS (schema_name 'public', table_name 'local_big',streaming_fetch 'true', fetch_size '1');CREATE FOREIGN TABLE ft_small (id int, val text)SERVER test_srvOPTIONS (schema_name 'public', table_name 'local_big2',streaming_fetch 'true', fetch_size '1');session-1DROP TABLE IF EXISTS bug2_pid;CREATE TEMP TABLE bug2_pid (pid int);INSERT INTO bug2_pid VALUES (pg_backend_pid()); -- pid_1DO $$DECLARE cnt int;BEGINSET LOCAL enable_hashjoin = off;SET LOCAL enable_mergejoin = off;SELECT count(*) INTO cntFROM ft_big b, ft_small sAND pg_backend_pid() > 0;RAISE NOTICE 'completed: cnt=%', cnt;EXCEPTION WHEN OTHERS THENRAISE NOTICE 'caught: %', SQLERRM;END;$$;SELECT 'post_check' AS phase, count(*) FROM ft_big; -- CRASH HEREsession-2SELECT pid FROM bug2_pid;SELECT pg_cancel_backend(pid); -- After Session 1 enters the drain loop, execute pg_cancel_backend(pid) in Session 2.
Hello Yilin,
Thanks for your input. But unfortunately I am not able to reproduce the issue with this test case. Also, I am not able to understand it much, as to how we are going to access bug2_pid from session 2, because it is a temp table from a different session. Maybe you can simplify this a little more, or maybe share the backtrace in case of the crash.
I believe the issue regarding fsstate->conn and active_fsstate->conn that you've been discussing with Robert is related to this crash.If only one PgFdwScanState* (active_fsstate) is available inside save_to_tuplestore, the assignment active_scan = NULL will clearly not be executed prior to draining.The draining logic operates on data from active_fsstate, and we can only clear it after draining completes successfully.
Yes you are right, this was the gap, in case of crash while draining, active_fsstate couldn't be cleared and a dangling pointer was left, which causes the crash on the next execution.
To fix this, I have now added a condition in pgfdw_abort_cleanup, to reset the active_scan in case of unfinished drain. Since I was not able to use your test case so I couldn't verify if this fixes the issue.
Apart from that I have now changed the save_to_tuplestore function to only have active_fsstate and PGconn. Also, there is a wrapper function to call it and check the relevant condition so we don't duplicate it all those 5 places. I have also added the calls to function to drain tuples to tuplestore in execute_dml_stmt and exectute_foreign_modify, to ensure that whenever a new query is sent on the connection, we perform the draining of the tuples to tuplestore if any or mark the other scan completed appropriately.
Please find the rebased patches attached.
Best regards,--Yilin Zhang
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
"Yilin Zhang" <jiezhilove@126.com>
Дата:
> Hello Yilin,
> Thanks for your input. But unfortunately I am not able to reproduce the
> issue with this test case. Also, I am not able to understand it much, as to
> how we are going to access bug2_pid from session 2, because it is a temp
> table from a different session. Maybe you can simplify this a little more,
> or maybe share the backtrace in case of the crash.
> Yes you are right, this was the gap, in case of crash while draining,
> active_fsstate couldn't be cleared and a dangling pointer was left, which
> causes the crash on the next execution.
> To fix this, I have now added a condition in pgfdw_abort_cleanup, to reset
> the active_scan in case of unfinished drain. Since I was not able to use
> your test case so I couldn't verify if this fixes the issue.
> Apart from that I have now changed the save_to_tuplestore function to only
> have active_fsstate and PGconn. Also, there is a wrapper function to call
> it and check the relevant condition so we don't duplicate it all those 5
> places. I have also added the calls to function to drain tuples to
> tuplestore in execute_dml_stmt and exectute_foreign_modify, to ensure that
> whenever a new query is sent on the connection, we perform the draining of
> the tuples to tuplestore if any or mark the other scan completed
> appropriately.
Sorry, that was my mistake. The
temp keyword in the "CREATE TEMP TABLE" statement is unnecessary; just remove it directly.This crash has already been fixed in the v13 patch.
LGTM.
Best regards,--Yilin Zhang
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Rafia Sabih <rafia.pghackers@gmail.com>
Дата:
On Thu, 16 Jul 2026 at 12:24, Yilin Zhang <jiezhilove@126.com> wrote:
> Hello Yilin,> Thanks for your input. But unfortunately I am not able to reproduce the> issue with this test case. Also, I am not able to understand it much, as to> how we are going to access bug2_pid from session 2, because it is a temp> table from a different session. Maybe you can simplify this a little more,> or maybe share the backtrace in case of the crash.> Yes you are right, this was the gap, in case of crash while draining,> active_fsstate couldn't be cleared and a dangling pointer was left, which> causes the crash on the next execution.> To fix this, I have now added a condition in pgfdw_abort_cleanup, to reset> the active_scan in case of unfinished drain. Since I was not able to use> your test case so I couldn't verify if this fixes the issue.> Apart from that I have now changed the save_to_tuplestore function to only> have active_fsstate and PGconn. Also, there is a wrapper function to call> it and check the relevant condition so we don't duplicate it all those 5> places. I have also added the calls to function to drain tuples to> tuplestore in execute_dml_stmt and exectute_foreign_modify, to ensure that> whenever a new query is sent on the connection, we perform the draining of> the tuples to tuplestore if any or mark the other scan completed> appropriately.Sorry, that was my mistake. Thetempkeyword in the "CREATE TEMP TABLE" statement is unnecessary; just remove it directly.
Nevertheless, your input was valuable in finding the issue and fixing it.
This crash has already been fixed in the v13 patch.LGTM.
Hey, thanks a lot for confirming this.
Best regards,--Yilin Zhang
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Wed, Jul 15, 2026 at 7:50 AM Rafia Sabih wrote: > Please find the rebased patches attached. Hi, I think you're making progress here, but I still see some problems. - I don't really like the fact that pgfdw_abort_cleanup just zeroes the active_scan pointer. When a transaction or subtransation is aborted, pgfdw_cancel_query_end calls pgfdw_get_cleanup_result to consume all the remaining tuples. It's at that point that we can say no active scan is in progress any more, so that's where I think the pointer should be getting cleared. If we ever arrived at one of these memset calls with an active scan still in progress, just clearing the pointer wouldn't fix anything -- we'd need to actually drain the tuples. The reason it works is because the tuples should always be getting drained earlier, before this logic is reached, so I think we should clear the pointer there rather than here. Now, on the other hand, that same logic probably applies to the pendingAreq stuff, about whose correctness I am also suspicious, and you could maybe argue you just followed the existing precedent. But I think it's a bad precedent upon which I would rather not double down. - A side benefit of the above change is that postgresReScanForeignScan would not need to set fsstate->conn_state->active_scan = NULL when it calls pgfdw_cancel_query. Instead, calling pgfdw_cancel_query would clear active_scan as a side-effect, which is more correct. - The explain output for streaming fetch mode now shows "streaming_fetch: true". That's nice, but the capitalization and punctuation is different from every other EXPLAIN property, which is less nice. - I think it would be a good idea for pgfdw_exec_query() to Assert(state == NULL || state->active_scan == NULL). That way, if we ever miss a drain_other_active_scan() call, it has a chance of tripping an Assert, if that code path is tested. - drain_other_active_scan's test for conn_state->active_scan != self does not do anything. postgresReScanForeignScan and postgresEndForeignScan don't call it when fsstate->streaming_fetch is true. In create_cursor and init_scan we are setting up a new active scan so the newly-created scan cannot already be in process. In execute_foreign_modify and execute_dml, there is no support for streaming fetch, so a streaming fetch scan for one of those cases cannot already be in progress. If you remove that test, then the "self" parameter for that function isn't needed any more. You don't need the conn parameter either, because it has to be the same as conn_state->active_scan->conn. So this can be simplified down to a one-parameter function: drain_other_active_scan(PgFdwConnState *conn_state). (This last point is basically the same issue that we have exchanged many emails about already. You shouldn't need to pass anything from the current scan into the functions that clear the active scan. Everything should be done via the active scan.) - fetch_from_tuplestore fetches every single tuple out of the tuplestore and returns them all at once. This defeats the purpose of using a tuplestore. The purpose of the tuplestore is to keep you from needing to put all the tuples in memory at the same time. So, when the connection is needed by some other process, you correctly put all of the tuples into a tuplestore, which means it can spill to disk if there's too much data. But as soon as we read from the tuplestore, you read all of the tuples at once. This is different from what happens in the cursor mode, which is that we fetch tuples from the remote side in small batches. This probably needs to work similarly. - save_to_tuplestore doesn't handle unexpected result statuses cleanly. If PQresultStatus(res) is an unexpected value - i.e. not PGRES_FATAL_ERROR, PGRES_TUPLES_OK, or PGRES_TUPLES_CHUNK - like say if somehow managed to be PGRES_COMMAND_OK or PGRES_COPY_BOTH or PGRES_PIPELINE_SYNC, then something fairly random would happen. It's OK for the code to error out if it sees a result status it isn't expecting, but it shouldn't just fall through to code that isn't going to cope with that status nicely. -- Robert Haas EDB: http://www.enterprisedb.com
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Rafia Sabih <rafia.pghackers@gmail.com>
Дата:
On Tue, 21 Jul 2026 at 02:02, Robert Haas <robertmhaas@gmail.com> wrote:
On Wed, Jul 15, 2026 at 7:50 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Please find the rebased patches attached.
Hi,
I think you're making progress here, but I still see some problems.
- I don't really like the fact that pgfdw_abort_cleanup just zeroes
the active_scan pointer. When a transaction or subtransation is
aborted, pgfdw_cancel_query_end calls pgfdw_get_cleanup_result to
consume all the remaining tuples. It's at that point that we can say
no active scan is in progress any more, so that's where I think the
pointer should be getting cleared. If we ever arrived at one of these
memset calls with an active scan still in progress, just clearing the
pointer wouldn't fix anything -- we'd need to actually drain the
tuples. The reason it works is because the tuples should always be
getting drained earlier, before this logic is reached, so I think we
should clear the pointer there rather than here. Now, on the other
hand, that same logic probably applies to the pendingAreq stuff, about
whose correctness I am also suspicious, and you could maybe argue you
just followed the existing precedent. But I think it's a bad precedent
upon which I would rather not double down.
Yes you are right, this was based on the existing flow of pendingAreq, but also because we have access to conn_state in this function. In the functions pgfdw_cancel_query_end and pgfdw_get_cleanup_result we are only dealing with conn only, so clearing the conn_state there doesn't seem possible without significant changes.
- A side benefit of the above change is that postgresReScanForeignScan
would not need to set fsstate->conn_state->active_scan = NULL when it
calls pgfdw_cancel_query. Instead, calling pgfdw_cancel_query would
clear active_scan as a side-effect, which is more correct.
- The explain output for streaming fetch mode now shows
"streaming_fetch: true". That's nice, but the capitalization and
punctuation is different from every other EXPLAIN property, which is
less nice.
- I think it would be a good idea for pgfdw_exec_query() to
Assert(state == NULL || state->active_scan == NULL). That way, if we
ever miss a drain_other_active_scan() call, it has a chance of
tripping an Assert, if that code path is tested.
- drain_other_active_scan's test for conn_state->active_scan != self
does not do anything. postgresReScanForeignScan and
postgresEndForeignScan don't call it when fsstate->streaming_fetch is
true. In create_cursor and init_scan we are setting up a new active
scan so the newly-created scan cannot already be in process. In
execute_foreign_modify and execute_dml, there is no support for
streaming fetch, so a streaming fetch scan for one of those cases
cannot already be in progress. If you remove that test, then the
"self" parameter for that function isn't needed any more. You don't
need the conn parameter either, because it has to be the same as
conn_state->active_scan->conn. So this can be simplified down to a
one-parameter function: drain_other_active_scan(PgFdwConnState
*conn_state).
I realise, following these inputs we would not even need this function anymore and can just use save_to_tuplestore instead, that will simplify the code. Thanks.
(This last point is basically the same issue that we have exchanged
many emails about already. You shouldn't need to pass anything from
the current scan into the functions that clear the active scan.
Everything should be done via the active scan.)
Unfortunately, I keep on making this mistake because we can get active_state from current_state, so I just find this simple to start with current_fsstate and use active_fsstate when required. I would be more mindful of this.
- fetch_from_tuplestore fetches every single tuple out of the
tuplestore and returns them all at once. This defeats the purpose of
using a tuplestore. The purpose of the tuplestore is to keep you from
needing to put all the tuples in memory at the same time. So, when the
connection is needed by some other process, you correctly put all of
the tuples into a tuplestore, which means it can spill to disk if
there's too much data. But as soon as we read from the tuplestore, you
read all of the tuples at once. This is different from what happens in
the cursor mode, which is that we fetch tuples from the remote side in
small batches. This probably needs to work similarly.
- save_to_tuplestore doesn't handle unexpected result statuses
cleanly. If PQresultStatus(res) is an unexpected value - i.e. not
PGRES_FATAL_ERROR, PGRES_TUPLES_OK, or PGRES_TUPLES_CHUNK - like say
if somehow managed to be PGRES_COMMAND_OK or PGRES_COPY_BOTH or
PGRES_PIPELINE_SYNC, then something fairly random would happen. It's
OK for the code to error out if it sees a result status it isn't
expecting, but it shouldn't just fall through to code that isn't going
to cope with that status nicely.
--
Robert Haas
EDB: http://www.enterprisedb.com
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Rafia Sabih <rafia.pghackers@gmail.com>
Дата:
On Tue, 21 Jul 2026 at 19:35, Robert Haas <robertmhaas@gmail.com> wrote:
On Tue, Jul 21, 2026 at 2:41 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Yes you are right, this was based on the existing flow of pendingAreq, but also because we have access to conn_state in this function. In the functions pgfdw_cancel_query_end and pgfdw_get_cleanup_result we are only dealing with conn only, so clearing the conn_state there doesn't seem possible without significant changes.
I think you can add a parameter to pgfdw_cancel_query and
pgfdw_cancel_query_end, a PgFdwConnState. The callers in connection.c
have a ConnCacheEntry and can pass &entry->state, and the callers in
postgres_fdw.c have a PgFdwScanState and can pass fsstate->conn_state.
Yes, you are right we can do that. However, looking at it more closely, zeroing the conn_state which includes pendingAreq doesn't look right. Because in pgfdw_abort_cleanup, when the check is done for pendingAreq, it would always be false, since we have cleared it already. So, wouldn't doing active_scan = NULL in pgfdw_cancel_query_end make more sense here rather than zeroing...?
--
Robert Haas
EDB: http://www.enterprisedb.com
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Rafia Sabih <rafia.pghackers@gmail.com>
Дата:
On Tue, 28 Jul 2026 at 14:30, Robert Haas <robertmhaas@gmail.com> wrote:
On Thu, Jul 23, 2026 at 6:03 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
>> I think you can add a parameter to pgfdw_cancel_query and
>> pgfdw_cancel_query_end, a PgFdwConnState. The callers in connection.c
>> have a ConnCacheEntry and can pass &entry->state, and the callers in
>> postgres_fdw.c have a PgFdwScanState and can pass fsstate->conn_state.
>>
> Yes, you are right we can do that. However, looking at it more closely, zeroing the conn_state which includes pendingAreq doesn't look right. Because in pgfdw_abort_cleanup, when the check is done for pendingAreq, it would always be false, since we have cleared it already. So, wouldn't doing active_scan = NULL in pgfdw_cancel_query_end make more sense here rather than zeroing...?
I'm not entirely sure I understand the question. I'd generally
recommend clearing individual fields of a structure over using memset
to zeroing the entire thing. On that note, I wonder if the memset that
the current code uses in pgfdw_abort_cleanup() is buggy -- how can it
justify zeroing the *entire* state entry? I guess maybe that works
today because the only member of PgFdwConnState is pendingAreq, but it
doesn't seem like the right thing in general.
The question was that we should just clear active_scan and not the struct memset the way it is doing in pgfdw_abort_cleanup, which you clarified in your answer.
Regarding your other point, that's my understanding too that this memset is working because it is the only one in struct.
Should we also change that to clearing only pendingAreq instead of the complete struct memset that it is doing now? Should this be done as a separate patch?
--
Robert Haas
EDB: http://www.enterprisedb.com
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Fri, 21 Aug 2026 at 12:25, Rafia Sabih <rafia.pghackers@gmail.com> wrote:
On Tue, 11 Aug 2026 at 02:13, Robert Haas <robertmhaas@gmail.com> wrote:On Mon, Aug 3, 2026 at 7:28 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Please find the reworked patch set attached.
> This version handles the concerns discussed above.
Hi,I noticed while looking over this version of the patch set that there
are a lot of similarities between process_pending_request() and
save_to_tuplestore(). In one sense, actually, they're exactly the same
thing: they track some query that is actively using the connection and
whose results must be read before the connection can be used for
something else. Possibly they should share code, but for sure we
should be suspicious if one of them is called someplace that the other
is not. execute_foreign_modify() is one place where things diverge:
process_pending_request() is called at the top of the function, and
save_to_tuplestore() is called a bit further down. That's a problem,
because SQL queries can be executed in the middle, showing that you've
put the call to save_to_tuplestore() in the wrong place.
Another place where this comes up is pgfdw_exec_query(). There, async
requests are handled via process_pending_request(), but for an active
scan, we instead Assert that the caller took care of it. But in fact,
many callers of pgfdw_exec_query() don't do that (e.g.
postgresAnalyzeForeignTable, postgresGetAnalyzeInfoForForeignTable).
We either need to make them all do it, or perhaps we should think
about changing things so that pgfdw_exec_query() does
save_to_tuplestore() itself. That would require every caller to pass a
non-NULL PgFdwConnState, or else those that don't would need to be
safe for some other reason.
Yet another place where this comes up is in fetch_more_data_begin().
It sends a new query, but it doesn't call save_to_tuplestore() first.
And it comes up in GetConnection() too, which has pendingAreq handling
but no save_to_tuplestore(). It's not impossible to make all of this
logic correct if pendingAreq is handled in one way and streaming_fetch
is handled in a different way that is also correct but puts all the
code in different places. However, it might be easier if we make them
as similar as possible, instead of inventing a new way to do a very
similar thing.You are indeed right in this observation. I tried to keep them similar in this version.I chose to make pgfdw_exec_query() self-draining rather than trusting every caller to remember. It no longer Asserts that state->active_scan == NULL. Instead it actively drains any pending streaming scan itself before sending the new query. state is now a required, non-NULL parameter.The signature for save_to_tuplestore is still not correct. I don't
understand how this can still not be right after as much discussion as
we've had. As I said last time: "So this can be simplified down to a
one-parameter function: drain_other_active_scan(PgFdwConnState
*conn_state)." In the current patch, it has two parameters, which is
more than one. Once again, you don't need PGconn *conn. As I said last
time: "You don't need the conn parameter either, because it has to be
the same as conn_state->active_scan->conn." That's still true.
save_to_tuplestore() should be structured with a loop at the top
level, instead of entering a loop only after the first call to
pgfdw_get_next_result(). Right now, if the first call to
pgfdw_get_next_result() returns an unexpected PQresultStatus(), an
error will be reported (which is good), but if a later call returns an
unexpected PQresultStatus(), no error will be reported, which is bad.
Everything that gets done for the first call to
pgfdw_get_next_result() should be done for the subsequent ones too.
This function currently has three calls to pgfdw_get_next_result() and
you want to get that down to no more than two, or possibly just one.The function is now changed to have only PgFdwScanState i.e. active_scan as the parameter and PGConn is now retrieved from this itself. Next, now there is a loop and within it there is only via calls to fetch_stream_result to retrieve chunks of tuples and handle all the other result status cases. This looks much cleaner and also is what you are asking for here. Also, I felt the name drain_other_active_scan as more appropriate for this function than save_to_tuplestore. But of course I am open to renaming anything else which makes more sense.The use of #ifdef LIBPQ_HAS_CHUNK_MODE is not correct. If this patch
were to be accepted, it would be part of a version of PostgreSQL that
definitely has chunk mode. We do not need to cater to the scenario of
that not being true.Removed.
In fetch_more_data(), the call to fetch_stream_result() to clear the
remains of the query from the connection is quite scary -- if any
tuples were returned there, unexpectedly, they'd be silently dropped.
The caller is expecting no tuples, but that's not checked. The bigger
picture here is that fetch_stream_result() is highly duplicative of
save_to_tuplestore(). The error handling isn't currently identical
between those two functions, but it should be. Either we should get
rid of fetch_stream_result(), or save_to_tuplestore() should use it as
a subroutine.In the attached patch, fetch_stream_result handles all the result status and also it reports errors whenever required. save_to_tuplestore function now repeatedly calls fetch_stream_result to get the chunks as well as handling different result statuses, so more duplicate handling of TUPLES_OK, NULL, etc. In fetch_more_data, when eof is marked because of the partial chunk, then it calls save_to_tuplestore to save the tuples to tuplestore and handle the NULL state afterwards via call to fetch_stream_result. So things are more uniformly handled now.
fetch_ct_2 needs to count the number of times that tuples[] has been
filled, to a maximum of 2, so that postgresReScanForeignScan can use
that information to know how to rewind. But it doesn't currently work
that way, because the streaming-tuplestore cases in fetch_more_data()
ignore it. If we enter the if (fsstate->tuplestore) block, then we
reload tuples[] inside fetch_from_tuplestore() but don't touch
fetch_ct_2. If we have no tuplestore, then we call
fetch_stream_result() which is fine except when res == NULL. In that
case, we return right away without bumping fetch_ct_2.I have now placed the increment block for fetch_ct_2 to the beginning of the function, so that it can be handled similarly in case of either mode. My understanding with respect to fetch_ct_2 is that it should mean the same in any of these modes, so I am using it similarly.Once again thank you for your support and patient review for this work.--
Robert Haas
EDB: http://www.enterprisedb.com--Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
CFBot informed me that the patches need a rebase. Please find the attached files for the rebased patches.
-- Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
От:
Rafia Sabih <rafia.pghackers@gmail.com>
Дата:
On Wed, 2 Sept 2026 at 21:14, Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
On Wed, 2 Sept 2026 at 13:49, Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Please find the reworked patchset in the attachment.
> Looking forward to your feedback on this one.
I tried this patch out with the "postgres compatible" endpoint I built
for MotherDuck[1]. DuckDB (currently) doesn't support cursors, so that
is blocking us from supporting postgres_fdw. With this patchset (and a
few small bugfixes on my side) I was able to get it to work with
motherduck its postgres endpoint.
[1]: https://motherduck.com/blog/motherduck-now-speaks-postgres/
P.S. I did not review any of the code.
Interesting!
Thank you for sharing this information. I am happy to see that the work is already useful.
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
The patches required a minor rebase.
The latest patches attached.
On Thu, 3 Sept 2026 at 10:25, Rafia Sabih <rafia.pghackers@gmail.com> wrote:
On Wed, 2 Sept 2026 at 21:14, Jelte Fennema-Nio <postgres@jeltef.nl> wrote:On Wed, 2 Sept 2026 at 13:49, Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> Please find the reworked patchset in the attachment.
> Looking forward to your feedback on this one.
I tried this patch out with the "postgres compatible" endpoint I built
for MotherDuck[1]. DuckDB (currently) doesn't support cursors, so that
is blocking us from supporting postgres_fdw. With this patchset (and a
few small bugfixes on my side) I was able to get it to work with
motherduck its postgres endpoint.
[1]: https://motherduck.com/blog/motherduck-now-speaks-postgres/
P.S. I did not review any of the code.Interesting!Thank you for sharing this information. I am happy to see that the work is already useful.--Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Wed, Dec 17, 2025 at 9:09 AM Alexander Pyhalov wrote: > I've looked at this patch, because also was playing with tuplestore in > PgFdwScanState to have more predictable memory usage with large > fetch_size. Unfortunately, I've found that you can't use > TTSOpsMinimalTuple(?) tuplestore to store tuple's ctid. I hoped this > patch provides some solution for this issue, but no, it seems have the > same problem. Attaching test case with a reproducer. Rafia, the bug that Alexander reports here is still unfixed in the latest version of the patch. In short, tuplestore_puttuple() doesn't store the CTID. A standalone, Claude-written test case demonstrating the problem is attached. One possible way to fix this is to disable streaming_fetch when CTID is among the columns fetched. If the CTID is being fetched because we're doing an UPDATE or DELETE, the scan is going to have to be drained to allow the per-row UPDATE or DELETE commands to be executed, so streaming-fetch mode is actually a bad idea anyway. -- Robert Haas Databricks
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Tue, Sep 15, 2026 at 9:30 AM Rafia Sabih wrote: > The patches required a minor rebase. > The latest patches attached. If you enter drain_active_scan() with tuplestore_lost_rows = true, the function will set it to false, which is wrong. I think that drain_active_scan() should store the previous value of tuplestore_lost_rows into a local variable just before setting tuplestore_lost_rows = true, and restore that value in the places where it previously stores false. http://postgr.es/m/CA+Tgmoa-FXH9jZaxm039eWf8=nhnoBfDS=oeKfm50sbGEAZ58g@mail.gmail.com pointed out that pgfdw_subxact_callback() needs to drain active scans before calling RELEASE SAVEPOINT. It still doesn't. You should probably add some transaction-control tests to the regression test suite for postgres_fdw, so that these kinds of issues can't come back once fixed. drain_active_scan() switches to active_fsstate->batch_cxt while it's executing, which causes allocations to be performed in the correct memory context. But that only handles memory allocation, and tuplestores also use files, which are controlled by the resource owner mechanism, not the memory context mechanism. Any files created here should end up owned by whatever the correct resource owner is for the scan we're draining, but instead they end up using the resource owner that's in effect at the time we need to perform the drain. You'll need to save the resource owner and temporarily switch to it here as you do for the memory context. I attach Claude-written test cases for all three issues. -- Robert Haas Databricks
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Fri, 9 Oct 2026 at 22:57, Robert Haas <robertmhaas@gmail.com> wrote:
On Tue, Sep 15, 2026 at 9:30 AM Rafia Sabih <rafia.pghackers@gmail.com> wrote:
> The patches required a minor rebase.
> The latest patches attached.
If you enter drain_active_scan() with tuplestore_lost_rows = true, the
function will set it to false, which is wrong. I think that
drain_active_scan() should store the previous value of
tuplestore_lost_rows into a local variable just before setting
tuplestore_lost_rows = true, and restore that value in the places
where it previously stores false.
http://postgr.es/m/CA+Tgmoa-FXH9jZaxm039eWf8=nhnoBfDS=oeKfm50sbGEAZ58g@mail.gmail.com
pointed out that pgfdw_subxact_callback() needs to drain active scans
before calling RELEASE SAVEPOINT. It still doesn't. You should
probably add some transaction-control tests to the regression test
suite for postgres_fdw, so that these kinds of issues can't come back
once fixed.
drain_active_scan() switches to active_fsstate->batch_cxt while it's
executing, which causes allocations to be performed in the correct
memory context. But that only handles memory allocation, and
tuplestores also use files, which are controlled by the resource owner
mechanism, not the memory context mechanism. Any files created here
should end up owned by whatever the correct resource owner is for the
scan we're draining, but instead they end up using the resource owner
that's in effect at the time we need to perform the drain. You'll need
to save the resource owner and temporarily switch to it here as you do
for the memory context.
I attach Claude-written test cases for all three issues.
Thank you for providing the tests and your comments on this.
The latest version of the patches are attached.
I have added tests to cover these issues, and also compacted the tests.
-- Regards,
Rafia Sabih
Rafia Sabih
CYBERTEC PostgreSQL International GmbH
Re: Bypassing cursors in postgres_fdw to enable parallel plans
On Tue, Nov 3, 2026 at 8:25 AM Rafia Sabih wrote: > Thank you for providing the tests and your comments on this. > The latest version of the patches are attached. > > I have added tests to cover these issues, and also compacted the tests. Thanks. I spent a bunch of time today studying this with an LLM, and unfortunately the result is that I think it needs a redesign. Here's the problem: as currently designed, tuples are fed to their type input functions when we read results off the wire. However, when the underlying data type is a domain, that can run arbitrary SQL. It's not really OK to run arbitrary SQL in the places where we're calling drain_active_scan(). Say an ERROR occurs. Then that ERROR gets associated with the statement that caused the drain to occur, not the statement that actually caused the problem. Worse still, security-relevant things might be different at one point in time vs. the other. For example, suppose Alice runs a query that fetches from a foreign table, but then in the middle of that table it calls a SECURITY DEFINER function owned by Bob that accesses the same foreign server and drains the active scan. Now, the type input functions which should have gotten run as Alice actually get run by Bob, and if Bob is smart he will have set search_path, so that is likely to be different as well, and other things could be, too. I think there's no way this is OK from a security perspective, and it can also just deliver straight-up wrong answers. The attached streaming_fetch_reentrant.sql is a Claude-written example of reentrancy where we just get an annoying error, but I'm sure there are ways to create worse consequences. So I think what we need to do here is get rid of the tuplestore, and let me be clear that it was my suggestion in the first place. :-( Instead, what we should do is keep the data in PGresult form unless we need to spill it to disk. If we spill to disk, save all the rows and columns that we got from the remote server just as we received them, without doing any type conversion. Since we'll be saving C strings rather than a tuple, we probably want to use a BufFile or something rather than a tuplestore. Postpone all type conversion until we're actually ready to return a row from the relevant scan. This might also help with a second problem that Claude found. Right now, when a subtransaction aborts, pgfdw_subxact_callback() calls pgfdw_abort_cleanup(_begin) for all scans corresponding to the current transaction level. That's good, and correct. However, AtSubAbort_Portals() can also mark as failed and subsequently clean up portals from *outer* transaction levels that were being used in the current transaction level at the time of the failure, and when it does, it also reparents their resource owners under the subtransaction being cleaned up. After CleanupSubTransaction() runs, active_scan->resowner points at freed memory, which is very bad, because it's still possible for drain_active_scan() to be called, and it will try to use that pointer. If the failed cursor is subsequently closed, then the ConnCacheEntry's active_scan pointer is pointing to freed memory, which is even worse. See streaming_fetch_failed_portal.sql for a relevant test case. Again, worse consequences are probably possible than the error shown here, like crashing the server. The design change proposed above doesn't directly solve this problem, but it might help, because it means that draining an active scan no longer really needs to know anything about the scan being drained. It needs a place to save PGresult objects, and it needs a place to spool too-large PGresult objects to disk, but it doesn't need to know things like what tuple descriptor applies to the data being read, because that kind of evaluation all happens later. So it might be possible to get rid of the active_scan pointer in PgFdwConnState. Instead, we could store a 64-bit integer "active spool ID". Separately, we could store a hash table that maps spool IDs onto stored or serialized PGresult objects in transaction-lifespan memory. Whenever we begin a scan, we also store the current value of ActivePortal, and the scan's active_portal is propagated to any spool we create for it. During subtransaction abort, we delete any spools for scans that began in the subtransaction we're cleaning up, and any whose portals are in a failed state. Doing so doesn't leave dangling pointers, just dangling spool IDs. But that's OK: when we next go to drain an active scan on that connection, we'll see that the spool ID points to a nonexistent spool and know that we just need to throw results away without saving them. In other words, this decouples the mechanism that keeps track of whether there is leftover stuff to read from the connection from the mechanism that keeps track of the memory and disk files that we use to store the stuff we read. I didn't think that was going to be necessary, but now I think it is, because now I see that the resource owner that owns the spool file (whether it's a tuplestore or not) can get destroyed either before or after we finish reading all the rows from the remote side. Unfortunately, fixing all of this seems like it will be quite a bit of work, but I'm not sure we really have much choice. We certainly can't keep running type input functions in the middle of queries other than the ones that caused them to be executed. How to solve the second problem is up for debate. -- Robert Haas Databricks