[(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

Поиск
Список
Период
Сортировка
Искать

[(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Jehan-Guillaume de Rorthais <jgdr@dalibo.com>
Дата:
Вложения:
Hi all,

We have been bitten by this old bug recently:

https://www.postgresql.org/message-id/flat/CAFjFpRfcgwsHRmpvoOK-GUQi-n8MgAS%2BOxcQo%3DaBDn1COywmcg%40mail.gmail.com

I suspect this bug lost attention when the only fixed submitted to the
commitfest has been flagged as "returned with feedback":

https://commitfest.postgresql.org/patch/1819/

Please, find in attachment the old patch forbidding more than one row to be
deleted/updated from postgresExecForeignDelete and postgresExecForeignUpdate. I
just rebased them without modification. I suppose this is much safer than
leaving the FDW destroy arbitrary rows on the remote side based on their sole
ctid.

The original discussion talked about using "WHERE CURRENT OF" with cursors to
update/delete rows but discard it because of performance penalty. As adding
tableoid as a junk clause as been rejected, should we investigate the former?
At least for existing major release?

Or maybe we should just not support foreign table to reference a
remote partitioned table?

I'm afraid other fix suggestions from 2018-2019 couldn't be backported as they
seem to require additional feature in FDW altogether. This might be another
reason this bug has been forgotten.

Regards,

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
Вложения:
Hi,

On Sat, Jul 19, 2025 at 12:53 AM Jehan-Guillaume de Rorthais
 wrote:
> We have been bitten by this old bug recently:
>
> https://www.postgresql.org/message-id/flat/CAFjFpRfcgwsHRmpvoOK-GUQi-n8MgAS%2BOxcQo%3DaBDn1COywmcg%40mail.gmail.com
>
> I suspect this bug lost attention when the only fixed submitted to the
> commitfest has been flagged as "returned with feedback":
>
> https://commitfest.postgresql.org/patch/1819/

This is on my TODO list, but I didn't have time to work on it, unfortunately.

> Please, find in attachment the old patch forbidding more than one row to be
> deleted/updated from postgresExecForeignDelete and postgresExecForeignUpdate. I
> just rebased them without modification. I suppose this is much safer than
> leaving the FDW destroy arbitrary rows on the remote side based on their sole
> ctid.

Thanks for rebasing the patch set, but I don't think the idea
implemented in the second patch is safe; even with the patch we have:

create table plt (a int, b int) partition by list (a);
create table plt_p1 partition of plt for values in (1);
create table plt_p2 partition of plt for values in (2);
create function trig_null() returns trigger language plpgsql as
  $$ begin return null; end; $$;
create trigger trig_null before update or delete on plt_p1
  for each row execute function trig_null();
create foreign table fplt (a int, b int)
  server loopback options (table_name 'plt');

insert into fplt values (1, 1), (2, 2);
INSERT 0 0
select tableoid::regclass, ctid, * from plt;
 tableoid | ctid  | a | b
----------+-------+---+---
 plt_p1   | (0,1) | 1 | 1
 plt_p2   | (0,1) | 2 | 2
(2 rows)

explain verbose update fplt set b = (case when random() <= 1 then 10
else 20 end) where a = 1;
                                           QUERY PLAN
-------------------------------------------------------------------------------------------------
 Update on public.fplt  (cost=100.00..128.02 rows=0 width=0)
   Remote SQL: UPDATE public.plt SET b = $2 WHERE ctid = $1
   ->  Foreign Scan on public.fplt  (cost=100.00..128.02 rows=7 width=42)
         Output: CASE WHEN (random() <= '1'::double precision) THEN 10
ELSE 20 END, ctid, fplt.*
         Remote SQL: SELECT a, b, ctid FROM public.plt WHERE ((a = 1))
FOR UPDATE
(5 rows)

update fplt set b = (case when random() <= 1 then 10 else 20 end) where a = 1;
UPDATE 1
select tableoid::regclass, ctid, * from plt;
 tableoid | ctid  | a | b
----------+-------+---+----
 plt_p1   | (0,1) | 1 |  1
 plt_p2   | (0,2) | 2 | 10
(2 rows)

The row in the partition plt_p2 is updated, which is wrong as the row
doesn't satisfy the query's WHERE condition.

> Or maybe we should just not support foreign table to reference a
> remote partitioned table?

I don't think so because we can execute SELECT, INSERT, and direct
UPDATE/DELETE safely on such a foreign table.

I think a simple fix for this is to teach the system that the foreign
table is a partitioned table; in more detail, I would like to propose
to 1) add to postgres_fdw a table option, inherited, to indicate
whether the foreign table is a partitioned/inherited table or not, and
2) modify postgresPlanForeignModify() to throw an error if the given
operation is an update/delete on such a foreign table.  Attached is a
WIP patch for that.  I think it is the user's responsibility to set
the option properly, but we could modify postgresImportForeignSchema()
to support that.  Also, I think this would be back-patchable.

What do you think about that?

Best regards,
Etsuro Fujita

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Wed, Jul 23, 2025 at 7:38 PM Etsuro Fujita  wrote:
> I think a simple fix for this is to teach the system that the foreign
> table is a partitioned table; in more detail, I would like to propose
> to 1) add to postgres_fdw a table option, inherited, to indicate
> whether the foreign table is a partitioned/inherited table or not, and
> 2) modify postgresPlanForeignModify() to throw an error if the given
> operation is an update/delete on such a foreign table.  Attached is a
> WIP patch for that.  I think it is the user's responsibility to set
> the option properly, but we could modify postgresImportForeignSchema()
> to support that.  Also, I think this would be back-patchable.

I noticed that this issue occurs in other cases: eg, if a foreign
table is an updatable view on a partitioned/inherited table,
non-pushed-down updates/deletes on the foreign table have the same
issue.  So adding the support in postgresImportForeignSchema() is not
that simple.  I feel like leaving it to the user, at least for
back-branches.

Best regards,
Etsuro Fujita


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Jehan-Guillaume de Rorthais <jgdr@dalibo.com>
Дата:
Hi,

On Wed, 23 Jul 2025 19:38:19 +0900
Etsuro Fujita  wrote:

> Hi,
> 
> On Sat, Jul 19, 2025 at 12:53 AM Jehan-Guillaume de Rorthais
>  wrote:
> > […]
> > Please, find in attachment the old patch forbidding more than one row to be
> > deleted/updated from postgresExecForeignDelete and
> > postgresExecForeignUpdate. I just rebased them without modification. I
> > suppose this is much safer than leaving the FDW destroy arbitrary rows on
> > the remote side based on their sole ctid.
> 
> Thanks for rebasing the patch set, but I don't think the idea
> implemented in the second patch is safe; even with the patch we have:
> 
> […]
> 
> The row in the partition plt_p2 is updated, which is wrong as the row
> doesn't satisfy the query's WHERE condition.

That's a clever test to expose the weakness of this patch…

> > Or maybe we should just not support foreign table to reference a
> > remote partitioned table?
> 
> I don't think so because we can execute SELECT, INSERT, and direct
> UPDATE/DELETE safely on such a foreign table.

Sure, but it's still possible to create one local foreign partition pointing to
remote foreign equivalent. And it seems safer considering how hard it seems to
keep corruptions away from the current situation. 

> I think a simple fix for this is to teach the system that the foreign
> table is a partitioned table; in more detail, I would like to propose
> to 1) add to postgres_fdw a table option, inherited, to indicate
> whether the foreign table is a partitioned/inherited table or not, and
> 2) modify postgresPlanForeignModify() to throw an error if the given
> operation is an update/delete on such a foreign table.  Attached is a
> WIP patch for that.  I think it is the user's responsibility to set
> the option properly, but we could modify postgresImportForeignSchema()
> to support that.  Also, I think this would be back-patchable.

So it's just a flag the user must set to allow/disallow UPDATE/DELETE on a
foreign table. I'm not convinced by this solution as users can still
easily corrupt their data just because they overlooked the documentation.

What about the first solution Ashutosh Bapat was suggesting: «Use WHERE CURRENT
OF with cursors to update rows.» ?
https://www.postgresql.org/message-id/CAFjFpRfcgwsHRmpvoOK-GUQi-n8MgAS%2BOxcQo%3DaBDn1COywmcg%40mail.gmail.com

It seems to me it never has been explored, is it?

Regards,


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Wed, Jul 30, 2025 at 12:48 AM Jehan-Guillaume de Rorthais
 wrote:
> On Wed, 23 Jul 2025 19:38:19 +0900
> Etsuro Fujita  wrote:
> > On Sat, Jul 19, 2025 at 12:53 AM Jehan-Guillaume de Rorthais
> >  wrote:
> > > Or maybe we should just not support foreign table to reference a
> > > remote partitioned table?
> >
> > I don't think so because we can execute SELECT, INSERT, and direct
> > UPDATE/DELETE safely on such a foreign table.
>
> Sure, but it's still possible to create one local foreign partition pointing to
> remote foreign equivalent. And it seems safer considering how hard it seems to
> keep corruptions away from the current situation.

Yeah, that would be a simple workaround for this issue.

> > I think a simple fix for this is to teach the system that the foreign
> > table is a partitioned table; in more detail, I would like to propose
> > to 1) add to postgres_fdw a table option, inherited, to indicate
> > whether the foreign table is a partitioned/inherited table or not, and
> > 2) modify postgresPlanForeignModify() to throw an error if the given
> > operation is an update/delete on such a foreign table.  Attached is a
> > WIP patch for that.  I think it is the user's responsibility to set
> > the option properly, but we could modify postgresImportForeignSchema()
> > to support that.  Also, I think this would be back-patchable.
>
> So it's just a flag the user must set to allow/disallow UPDATE/DELETE on a
> foreign table. I'm not convinced by this solution as users can still
> easily corrupt their data just because they overlooked the documentation.
>
> What about the first solution Ashutosh Bapat was suggesting: «Use WHERE CURRENT
> OF with cursors to update rows.» ?
> https://www.postgresql.org/message-id/CAFjFpRfcgwsHRmpvoOK-GUQi-n8MgAS%2BOxcQo%3DaBDn1COywmcg%40mail.gmail.com
>
> It seems to me it never has been explored, is it?

My concern about that solution is: as mentioned by him, it requires
fetching only one row from the remote at a time, which would lead to
large performance degradation when updating many rows.

Best regards,
Etsuro Fujita


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Nikita Malakhov <hukutoc@gmail.com>
Дата:
Вложения:
Hi hackers!

We've been bitten by this bug recently too. So I've taken off from the previous approach,
have fixed some issues and developed it a but further, please check this POC patch.

While working on it I've stumbled upon a bunch of checks inside copy slot/tuple machinery
which considered only case when source and destination match, with an old commentary
that this is not very good and has to be improved, so I've slightly modified this functionality
for my purposes.

On Wed, Aug 6, 2025 at 2:25 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
On Wed, Jul 30, 2025 at 12:48 AM Jehan-Guillaume de Rorthais
<jgdr@dalibo.com> wrote:
> On Wed, 23 Jul 2025 19:38:19 +0900
> Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
> > On Sat, Jul 19, 2025 at 12:53 AM Jehan-Guillaume de Rorthais
> > <jgdr@dalibo.com> wrote:
> > > Or maybe we should just not support foreign table to reference a
> > > remote partitioned table?
> >
> > I don't think so because we can execute SELECT, INSERT, and direct
> > UPDATE/DELETE safely on such a foreign table.
>
> Sure, but it's still possible to create one local foreign partition pointing to
> remote foreign equivalent. And it seems safer considering how hard it seems to
> keep corruptions away from the current situation.

Yeah, that would be a simple workaround for this issue.

> > I think a simple fix for this is to teach the system that the foreign
> > table is a partitioned table; in more detail, I would like to propose
> > to 1) add to postgres_fdw a table option, inherited, to indicate
> > whether the foreign table is a partitioned/inherited table or not, and
> > 2) modify postgresPlanForeignModify() to throw an error if the given
> > operation is an update/delete on such a foreign table.  Attached is a
> > WIP patch for that.  I think it is the user's responsibility to set
> > the option properly, but we could modify postgresImportForeignSchema()
> > to support that.  Also, I think this would be back-patchable.
>
> So it's just a flag the user must set to allow/disallow UPDATE/DELETE on a
> foreign table. I'm not convinced by this solution as users can still
> easily corrupt their data just because they overlooked the documentation.
>
> What about the first solution Ashutosh Bapat was suggesting: «Use WHERE CURRENT
> OF with cursors to update rows.» ?
> https://www.postgresql.org/message-id/CAFjFpRfcgwsHRmpvoOK-GUQi-n8MgAS%2BOxcQo%3DaBDn1COywmcg%40mail.gmail.com
>
> It seems to me it never has been explored, is it?

My concern about that solution is: as mentioned by him, it requires
fetching only one row from the remote at a time, which would lead to
large performance degradation when updating many rows.

Best regards,
Etsuro Fujita




--
Regards,
Nikita Malakhov
Postgres Professional
The Russian Postgres Company

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
Вложения:
Hi Nikita,

On Fri, May 15, 2026 at 2:23 AM Nikita Malakhov  wrote:
> CFbot was unhappy with previous patch set, so here's updated one

Thanks for working on this issue!

I took a quick look at the patch set.  IIUC I think it's created based
on what I proposed in the original thread, which is invasive and thus
not back-patchable, so what you are proposing here isn't
back-patchable, either, I think.

I think we should first work on a back-patchable solution.  So I'd
like to re-propose the patch that I proposed in this thread before to
disallow UPDATE/DELETE in problematic cases [1].  Attached is a new
version of the patch.  Changes are:

* Renamed the new table option inherited to remotely_inherited, to
avoid confusion with local inheritance.
* Moved the logic to prevent problematic UPDATE/DELETE from a planner
function to an executor function, to avoid throwing an error
unnecessarily when there are no target rows to update/delete.
* Added docs to postgres-fdw.sgml.

I'm planning to add the postgresImportForeignSchema() support in the
next version.

I think the remotely_inherited option would be useful when adding the
support for the UPDATE/DELETE, as it could be used to address one of
Tom Lane's comments about what I proposed in the original thread that
it adds the tabloid condition to a remote UPDATE/DELETE query whether
the target table is inherited or not: that could be avoid if the
option is set to false.

What do you think about that?

Best regards,
Etsuro Fujita

[1] https://www.postgresql.org/message-id/CAPmGK15CQK-oYFMAyq%2BrR0rQapUHtvAGuGgY5ahERHzZ4tmC8g%40mail.gmail.com

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
Hi Nikita,

On Sun, Jun 7, 2026 at 5:33 AM Nikita Malakhov  wrote:
> Thanks for working on the subject! I'll try to take a look inside in a couple of days.

Great!

Best regards,
Etsuro Fujita


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Wed, Jun 10, 2026 at 08:22:31PM +0900, Etsuro Fujita wrote:
> On Wed, Jun 10, 2026 at 2:38 PM Michael Paquier  wrote:
>> I would not object with a switch of the default behavior across major
>> versions, and perhaps my argument is not sound enough, but I've learnt
>> my share when it comes to be careful with changes like the one you may
>> introduce here across a minor release, particularly knowing that
>> remotely_inherited *can* be set on an option basis when creating a
>> table *or* when importing a schema.  The designs we have for these
>> queries allows this kind of flexibility.
> 
> I agree that we should take a more conservative approach especially on
> the stable branches, and I think it's a good idea to add the option to
> IMPORT FOREIGN SCHEMA for that, so I will update the patch as such in
> the next version.

Cool, thanks.
--
Michael

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Wed, Jun 10, 2026 at 08:30:46PM +0900, Etsuro Fujita wrote:
> To address this, I think it would be good if we could 1) extend the
> concept of inheritance to cover remote inheritances, like pt, and 2)
> extend inherited UPDATE/DELETE so that we update/delete leaf tables,
> like pt_p2, somehow directly, as done for local inheritances.  I'm not
> sure about how to do that, though.

FWIW, I think that there is a good argument for keeping it down to
simpler, and just not care about the option chain in such cases,
leaving it up to users to address that with two imports anyway?  Just 
having the option at one level would solve most historical problems I
could see on this thread.  Good is sometimes a better option than
theoretically perfect.  And good here means a simpler implementation
overall, at least it seems to me so..
--
Michael

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Nikita Malakhov <hukutoc@gmail.com>
Дата:
Hi!

While testing the proposed solution we've stumbled upon another vanilla bug related to FDW -
a query with DELETE ... USING selects invalid records from partitioned FDW tables:

CREATE EXTENSION postgres_fdw;

CREATE SERVER testserver1 FOREIGN DATA WRAPPER postgres_fdw;
DO $d$
    BEGIN
        EXECUTE $$CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw
            OPTIONS (dbname '$$||current_database()||$$',
                     port '$$||current_setting('port')||$$'
            )$$;
    END;
$d$;

CREATE USER MAPPING FOR public SERVER testserver1
OPTIONS (user 'value', password 'value');
CREATE USER MAPPING FOR CURRENT_USER SERVER loopback;
CREATE USER MAPPING FOR CURRENT_USER SERVER loopback2;
CREATE USER MAPPING FOR public SERVER loopback3;

CREATE TABLE acc_entry
(
    id bigint,
    doc_date date,
    impact int,
    amount numeric
) PARTITION BY RANGE (doc_date);

CREATE TABLE acc_entry_p1
PARTITION OF acc_entry
FOR VALUES FROM ('2025-01-01') TO ('2025-07-01');

CREATE TABLE acc_entry_p2
PARTITION OF acc_entry
FOR VALUES FROM ('2025-07-01') TO ('2026-01-01');

CREATE FOREIGN TABLE measurement_fdw
(
    id bigint,
    doc_date date,
    impact int,
    amount numeric
)
SERVER loopback
OPTIONS (table_name 'acc_entry');

INSERT INTO acc_entry
SELECT
    CASE
        WHEN g IN (4,15,26,35,46,55,66,75,86,95)
            THEN 2501020100000124
        ELSE g
    END AS id,
    CASE WHEN g % 2 = 0 THEN timestamp '2025-02-02' ELSE timestamp '2025-08-08' END,
    1,
    g
FROM generate_series(1,100) g;

DELETE FROM measurement_fdw
USING (
    SELECT id
    FROM measurement_fdw
    WHERE id = 2501020100000124
    LIMIT 1
) s
WHERE measurement_fdw.id = s.id;

The latter query selects and deletes records with invalid ID which should not be selected at all.
Although rewritten query like
with sub as (
           select t1.id sub_id
           from measurement_fdw t1
           where t1.id=2501020100000124
           limit 1
        )
select m.id, m.doc_date, m.impact, m.amount from measurement_fdw m, sub
        where m.id = sub.sub_id;
works correctly.
Currently I try to figure out what's the cause of this strange behavior and I'm suspicious about
/*
 * WCO_RLS_MERGE_DELETE_CHECK is used to check DELETE USING quals on
 * the existing target row.
*/
add_with_check_options(rel, rt_index,
                    WCO_RLS_MERGE_DELETE_CHECK,
merge_delete_permissive_policies,
merge_delete_restrictive_policies,
withCheckOptions,
hasSubLinks,
hasSubLinks,
true);

--
Regards,
Nikita Malakhov
Postgres Professional
The Russian Postgres Company

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Etsuro Fujita <etsuro.fujita@gmail.com>
Дата:
On Sun, Jun 14, 2026 at 4:43 AM Nikita Malakhov  wrote:
> While testing the proposed solution we've stumbled upon another vanilla bug related to FDW -
> a query with DELETE ... USING selects invalid records from partitioned FDW tables:

> CREATE TABLE acc_entry
> (
>     id bigint,
>     doc_date date,
>     impact int,
>     amount numeric
> ) PARTITION BY RANGE (doc_date);
>
> CREATE TABLE acc_entry_p1
> PARTITION OF acc_entry
> FOR VALUES FROM ('2025-01-01') TO ('2025-07-01');
>
> CREATE TABLE acc_entry_p2
> PARTITION OF acc_entry
> FOR VALUES FROM ('2025-07-01') TO ('2026-01-01');
>
> CREATE FOREIGN TABLE measurement_fdw
> (
>     id bigint,
>     doc_date date,
>     impact int,
>     amount numeric
> )
> SERVER loopback
> OPTIONS (table_name 'acc_entry');
>
> INSERT INTO acc_entry
> SELECT
>     CASE
>         WHEN g IN (4,15,26,35,46,55,66,75,86,95)
>             THEN 2501020100000124
>         ELSE g
>     END AS id,
>     CASE WHEN g % 2 = 0 THEN timestamp '2025-02-02' ELSE timestamp '2025-08-08' END,
>     1,
>     g
> FROM generate_series(1,100) g;
>
> DELETE FROM measurement_fdw
> USING (
>     SELECT id
>     FROM measurement_fdw
>     WHERE id = 2501020100000124
>     LIMIT 1
> ) s
> WHERE measurement_fdw.id = s.id;
>
> The latter query selects and deletes records with invalid ID which should not be selected at all.

I think that that would be another example that the bug discussed here
causes unexpected results, as I have this after inserting the data
into the partitioned table:

select tableoid::regclass, ctid, * from acc_entry where ctid in
(select ctid from acc_entry where id = 2501020100000124);
   tableoid   |  ctid  |        id        |  doc_date  | impact | amount
--------------+--------+------------------+------------+--------+--------
 acc_entry_p1 | (0,2)  | 2501020100000124 | 2025-02-02 |      1 |      4
 acc_entry_p1 | (0,8)  |               16 | 2025-02-02 |      1 |     16
 acc_entry_p1 | (0,13) | 2501020100000124 | 2025-02-02 |      1 |     26
 acc_entry_p1 | (0,18) |               36 | 2025-02-02 |      1 |     36
 acc_entry_p1 | (0,23) | 2501020100000124 | 2025-02-02 |      1 |     46
 acc_entry_p1 | (0,28) |               56 | 2025-02-02 |      1 |     56
 acc_entry_p1 | (0,33) | 2501020100000124 | 2025-02-02 |      1 |     66
 acc_entry_p1 | (0,38) |               76 | 2025-02-02 |      1 |     76
 acc_entry_p1 | (0,43) | 2501020100000124 | 2025-02-02 |      1 |     86
 acc_entry_p1 | (0,48) |               96 | 2025-02-02 |      1 |     96
 acc_entry_p2 | (0,2)  |                3 | 2025-08-08 |      1 |      3
 acc_entry_p2 | (0,8)  | 2501020100000124 | 2025-08-08 |      1 |     15
 acc_entry_p2 | (0,13) |               25 | 2025-08-08 |      1 |     25
 acc_entry_p2 | (0,18) | 2501020100000124 | 2025-08-08 |      1 |     35
 acc_entry_p2 | (0,23) |               45 | 2025-08-08 |      1 |     45
 acc_entry_p2 | (0,28) | 2501020100000124 | 2025-08-08 |      1 |     55
 acc_entry_p2 | (0,33) |               65 | 2025-08-08 |      1 |     65
 acc_entry_p2 | (0,38) | 2501020100000124 | 2025-08-08 |      1 |     75
 acc_entry_p2 | (0,43) |               85 | 2025-08-08 |      1 |     85
 acc_entry_p2 | (0,48) | 2501020100000124 | 2025-08-08 |      1 |     95
(20 rows)

Note that the rows with normal ids have the same ctid as the rows with
id=2501020100000124 (for example, ctid of the row with id=3 is (0,2),
which is the same as that of the first row, which has
id=2501020100000124), so the bug would delete such normal-id rows as
well when performing the delete query.

Best regards,
Etsuro Fujita


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Nikita Malakhov <hukutoc@gmail.com>
Дата:
Вложения:
Hi hackers!

I've fixed the issue mentioned in two previous messages, so for anyone already have taken
my patch set above I'd compiled a fixed patch set. It does not object an approach
proposed by Etsuro-san.

The first patch file
v4-0001-copy-and-remote-tableoid-param.patch
is a core patch introducing extended copy slot and tuple facilities
and core machinery for remote table OIDs;

The second file
v4-0002-teach-fdw-use-remote-tableoid.patch
is a fdw facilities changes (fixed) to use remote table OID.

On Mon, Jun 15, 2026 at 5:55 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:
On Sun, Jun 14, 2026 at 4:43 AM Nikita Malakhov <hukutoc@gmail.com> wrote:
> While testing the proposed solution we've stumbled upon another vanilla bug related to FDW -
> a query with DELETE ... USING selects invalid records from partitioned FDW tables:

> CREATE TABLE acc_entry
> (
>     id bigint,
>     doc_date date,
>     impact int,
>     amount numeric
> ) PARTITION BY RANGE (doc_date);
>
> CREATE TABLE acc_entry_p1
> PARTITION OF acc_entry
> FOR VALUES FROM ('2025-01-01') TO ('2025-07-01');
>
> CREATE TABLE acc_entry_p2
> PARTITION OF acc_entry
> FOR VALUES FROM ('2025-07-01') TO ('2026-01-01');
>
> CREATE FOREIGN TABLE measurement_fdw
> (
>     id bigint,
>     doc_date date,
>     impact int,
>     amount numeric
> )
> SERVER loopback
> OPTIONS (table_name 'acc_entry');
>
> INSERT INTO acc_entry
> SELECT
>     CASE
>         WHEN g IN (4,15,26,35,46,55,66,75,86,95)
>             THEN 2501020100000124
>         ELSE g
>     END AS id,
>     CASE WHEN g % 2 = 0 THEN timestamp '2025-02-02' ELSE timestamp '2025-08-08' END,
>     1,
>     g
> FROM generate_series(1,100) g;
>
> DELETE FROM measurement_fdw
> USING (
>     SELECT id
>     FROM measurement_fdw
>     WHERE id = 2501020100000124
>     LIMIT 1
> ) s
> WHERE measurement_fdw.id = s.id;
>
> The latter query selects and deletes records with invalid ID which should not be selected at all.

I think that that would be another example that the bug discussed here
causes unexpected results, as I have this after inserting the data
into the partitioned table:

select tableoid::regclass, ctid, * from acc_entry where ctid in
(select ctid from acc_entry where id = 2501020100000124);
   tableoid   |  ctid  |        id        |  doc_date  | impact | amount
--------------+--------+------------------+------------+--------+--------
 acc_entry_p1 | (0,2)  | 2501020100000124 | 2025-02-02 |      1 |      4
 acc_entry_p1 | (0,8)  |               16 | 2025-02-02 |      1 |     16
 acc_entry_p1 | (0,13) | 2501020100000124 | 2025-02-02 |      1 |     26
 acc_entry_p1 | (0,18) |               36 | 2025-02-02 |      1 |     36
 acc_entry_p1 | (0,23) | 2501020100000124 | 2025-02-02 |      1 |     46
 acc_entry_p1 | (0,28) |               56 | 2025-02-02 |      1 |     56
 acc_entry_p1 | (0,33) | 2501020100000124 | 2025-02-02 |      1 |     66
 acc_entry_p1 | (0,38) |               76 | 2025-02-02 |      1 |     76
 acc_entry_p1 | (0,43) | 2501020100000124 | 2025-02-02 |      1 |     86
 acc_entry_p1 | (0,48) |               96 | 2025-02-02 |      1 |     96
 acc_entry_p2 | (0,2)  |                3 | 2025-08-08 |      1 |      3
 acc_entry_p2 | (0,8)  | 2501020100000124 | 2025-08-08 |      1 |     15
 acc_entry_p2 | (0,13) |               25 | 2025-08-08 |      1 |     25
 acc_entry_p2 | (0,18) | 2501020100000124 | 2025-08-08 |      1 |     35
 acc_entry_p2 | (0,23) |               45 | 2025-08-08 |      1 |     45
 acc_entry_p2 | (0,28) | 2501020100000124 | 2025-08-08 |      1 |     55
 acc_entry_p2 | (0,33) |               65 | 2025-08-08 |      1 |     65
 acc_entry_p2 | (0,38) | 2501020100000124 | 2025-08-08 |      1 |     75
 acc_entry_p2 | (0,43) |               85 | 2025-08-08 |      1 |     85
 acc_entry_p2 | (0,48) | 2501020100000124 | 2025-08-08 |      1 |     95
(20 rows)

Note that the rows with normal ids have the same ctid as the rows with
id=2501020100000124 (for example, ctid of the row with id=3 is (0,2),
which is the same as that of the first row, which has
id=2501020100000124), so the bug would delete such normal-id rows as
well when performing the delete query.

Best regards,
Etsuro Fujita


--
Regards,
Nikita Malakhov
Postgres Professional
The Russian Postgres Company

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Ajit Awekar <ajitpostgres@gmail.com>
Дата:
Вложения:
Hi Jakub,

Thanks for the detailed repros. Attached patch fixes #1, #3, and #4;
#2 as doc modification.

#1/#3: The whole-row Var and per-column Vars overlapped, duplicating
columns on the wire and misattributing conversion errors to the whole
row instead of the failing column. Fixed by skipping the whole-row Var
during deparse, fetching each column individually, and reconstructing
the row locally -- restores per-column error context and drops the
duplicate transfer.

#4: Fixed by filtering to Vars of the scanned relation. Also fixed a
zero-column-table assertion hit while testing this.

#2:  Added a note on this as a known limitation to the
postgres_fdw "Remote Query Optimization" docs, recommending
whole-query shipping where possible and limiting affected row counts
otherwise.

Verified against your repros plus the full regression.

Thanks & Best Regards,
Ajit



On Mon, 7 Sept 2026 at 08:37, shihao zhong <zhong950419@gmail.com> wrote:
Hi Ajit, Nikita,

A quick note as commitfest manager: this thread currently has two
commitfest entries pointing at it, #6770 and #7211.  Since Ajit's patch
continues Nikita's work rather than competing with it, I have merged them
into a single entry:

  https://commitfest.postgresql.org/patch/6770/

Ajit, you are now listed as an author there alongside Nikita, and #7211 has
been withdrawn as a duplicate.  Nothing about your patch changed -- it is
still the version under review, and cfbot tracks it as before.  Please use
#6770 from now on, and feel free to add reviewers or update the status
there.

Thanks,
Shihao

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
On Thu, Sep 10, 2026 at 2:21 PM Ajit Awekar  wrote:
>
> Hi Jakub,
>
> Thanks for the detailed repros. Attached patch fixes #1, #3, and #4;
> #2 as doc modification.
>
> #1/#3: The whole-row Var and per-column Vars overlapped, duplicating
> columns on the wire and misattributing conversion errors to the whole
> row instead of the failing column. Fixed by skipping the whole-row Var
> during deparse, fetching each column individually, and reconstructing
> the row locally -- restores per-column error context and drops the
> duplicate transfer.
>
> #4: Fixed by filtering to Vars of the scanned relation. Also fixed a
> zero-column-table assertion hit while testing this.
>
> #2:  Added a note on this as a known limitation to the
> postgres_fdw "Remote Query Optimization" docs, recommending
> whole-query shipping where possible and limiting affected row counts
> otherwise.
>
> Verified against your repros plus the full regression.
>

Hi Ajit,

I've took a quick look:

0. This thing crashes with edge case of no having no columns (sic!) and using
   trigger:

   DROP TABLE t1;
   DROP FOREIGN TABLE ft1;
   CREATE TABLE t1 (a int);
   INSERT INTO t1 VALUES (1),(2);
   CREATE FOREIGN TABLE ft1 (a int) SERVER loopback OPTIONS (table_name 't1');
   ALTER FOREIGN TABLE ft1 DROP COLUMN a; -- yay!
   CREATE OR REPLACE FUNCTION trg() RETURNS trigger LANGUAGE plpgsql
AS $$ BEGIN RAISE NOTICE 'trg % old=% new=%', TG_OP, OLD, NEW; IF
TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END $$;
   CREATE TRIGGER trg BEFORE DELETE ON ft1 FOR EACH ROW EXECUTE FUNCTION trg();
   EXPLAIN (VERBOSE, COSTS OFF) DELETE FROM ft1 WHERE random() <= 1;
   DELETE FROM ft1 WHERE random() <= 1;

   causes
   TRAP: failed Assert("relvalues != NULL"), File:
"../contrib/postgres_fdw/postgres_fdw.c", Line: 9268, PID: 382254
   postgres: test postgres [local]
DELETE(ExceptionalCondition+0x74)[0x5ebb9182d4e4]
   postgres_fdw.so(+0x1c0e6)[0x7ddec0d860e6]
   postgres_fdw.so(+0x1c25f)[0x7ddec0d8625f]
   postgres_fdw.so(+0x1f118)[0x7ddec0d89118]
   postgres: test postgres [local] DELETE(+0x37e092)[0x5ebb91513092]
   postgres: test postgres [local] DELETE(ExecScan+0x242)[0x5ebb914ffeb2]
   [..]

   I haven't investigated it further other than the EXPLAIN showing the
   difference with trigger and without it like this:
   -    Output: ctid, remotetableoid
   +    Output: ctid, remotetableoid, ft1.*
   which seems to be caused by the trigger itself (w/o trigger it wont
fetch "ft1.*
   but there are no columns there and so it will crash). Dunno if anybody would
   use something like that (what's the point), but someone by accident could
   remove all columns from fdw during maintenance and crashing whole server is
   not good.

1. In doc/src/sgml/postgres-fdw.sgml
   [..]
   ++  by first selecting the affected rows from the remote server and then
   ++  issuing a separate remote UPDATE or
   ++  DELETE for each row, identified by its
   ++  ctid and remote tableoid.  If the
   ++  remote table is the root of a partitioning hierarchy, each such per-row
   ++  command targets that root and so cannot benefit from partition pruning,
   ++  which can make this considerably slower than the whole-query case when

   perhaps it would read provide more details if the that last statement would
   go refering tableoid explictly, I mean:

   "If the remote table is the root of a partitioning hierarchy, each such per
   -row command targets that root and so cannot benefit from partition pruning
   >> (based on tableoid) <<, which can make this considerably slower than the
   whole-query case (..)" (see those new statement between >> and <<)

2. The commitmsg is a bit way too verbose to my taste and covers everything.
   As long as the source code provides explanations, I don't think we need to
   duplicate information that much about implementation in the commitmsg. It
   should also at least have Discussion: link, Authors , etc.

3. Wider question to the community: an open question persists that was earlier
   raised by Etsuro and Michael, should this be backpatched or not (altough
   they were discussing earlier iterations of the solution). With this patch
   the varnullingrels used by this patch seems to be PG16+, and this thing
   might alter the optimizer in some other ways. If that is not backpatchable
   then what we should do in earlier versions? Etsuro had patch in [1] to
   block dangerous thing (because it's bug/and we should block logical
   corruption of the remote side, shouldn't we?).

BTW: this still needs to be reviewed by "the elders of the internet"^H^H^H^H^H
people that understand the optimizer :)

-J.

[1] - https://www.postgresql.org/message-id/CAPmGK14KEFMTuQ1vYwWCo8SLks5rXv-56K-V%2BXMy4q8uQJvq1w%40mail.gmail.com


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Manuel Reyes Bravo <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Ajit Awekar  wrote:
> Verified against your repros plus the full regression.

I tested v2 (cfbot branch for CF 6770, on master at 862092932c9) against
the same master without it, both with --enable-cassert, using a loopback
server.  The attached run_cases.sh runs each case file on a fresh
cluster.

What v2 fixes
-------------

- Etsuro's DELETE ... USING case: master deletes 20 rows instead of 10;
  with v2, exactly the 10 matching rows.

- The same corruption through triggers (case_d): remote partitioned
  table, foreign table with a dropped column in the middle, a column
  mapped with column_name, a different column order, a BEFORE UPDATE
  trigger changing NEW and an AFTER UPDATE trigger reading OLD.  On
  master, updating ids 1 and 2 leaves two rows with id 2 and none with
  id 1.  With v2 both rows are right, and OLD and NEW seen by the
  triggers are right, so the local whole-row reconstruction handles the
  dropped and renamed columns.

- A local partitioned table with one local and one foreign partition,
  UPDATE and DELETE with RETURNING tableoid and the whole row (case_g),
  and a self-join UPDATE (case_h): wrong rows on master, right with v2.

Jakub's zero-column case with a BEFORE DELETE trigger still fails the
assertion (postgres_fdw.c:9281 on this tree), while master runs it
fine.  Without the trigger, DELETE ... RETURNING ft1 on the same table
works on both.

What v2 does not fix: chained foreign tables
--------------------------------------------

When a foreign table points to another foreign table, which points to
the partitioned table, the wrong rows are still updated and deleted,
exactly as on master (case_f):

    CREATE TABLE r (id int, grp int, v text) PARTITION BY LIST (grp);
    CREATE TABLE r1 PARTITION OF r FOR VALUES IN (1);
    CREATE TABLE r2 PARTITION OF r FOR VALUES IN (2);
    INSERT INTO r VALUES (1, 1, 'one'), (2, 2, 'two');
    CREATE FOREIGN TABLE ft_mid (id int, grp int, v text)
      SERVER loopback OPTIONS (table_name 'r');
    CREATE FOREIGN TABLE ft_outer (id int, grp int, v text)
      SERVER loopback OPTIONS (table_name 'ft_mid');

    UPDATE ft_outer SET v = v || '!' WHERE id = 1 AND random() <= 1;

    SELECT tableoid::regclass, ctid, * FROM r ORDER BY id;
     tableoid | ctid  | id | grp |  v
    ----------+-------+----+-----+------
     r1       | (0,2) |  1 |   1 | one!
     r2       | (0,2) |  2 |   2 | one!

With log_statement = all the cause is visible.  The outer hop sends

    UPDATE public.ft_mid SET v = $3 WHERE ctid = $1 AND tableoid = $2
    Parameters: $1 = '(0,1)', $2 = '16408', $3 = 'one!'

where 16408 is ft_mid itself, so the tableoid condition matches every
row of ft_mid.  The middle hop then finds (0,1) in both partitions and
sends two updates, one per remote tableoid:

    UPDATE public.r SET v = $3 WHERE ctid = $1 AND tableoid = $2
    Parameters: $1 = '(0,1)', $2 = '16398', $3 = 'one!'
    UPDATE public.r SET v = $3 WHERE ctid = $1 AND tableoid = $2
    Parameters: $1 = '(0,1)', $2 = '16403', $3 = 'one!'

In the same case, DELETE ... WHERE id = 3 also deletes id 4.

So once the remote table is itself a foreign table, (ctid, tableoid)
is no longer a row identity.  I don't see how the outer hop could fix
that without knowing the remote relkind.  Maybe that is worth a
sentence next to the new partitioning note in postgres-fdw.sgml, or a
check of the remote relkind that refuses the non-direct path for it,
but I would rather ask what you think than propose one.  The EXPLAIN
output in this case now shows "WHERE ctid = $1 AND tableoid = $2",
which makes it look protected when it is not.

Regards,
Manu

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Ajit Awekar <ajitpostgres@gmail.com>
Дата:
Вложения:
 Thanks Jakub and Manu for your reviews.

Thanks to Robert Haas for suggesting the approach of carrying 
the remote tableoid through fdw_scan_tlist offline.

  @Jakub: the zero-column+trigger crash is fixed (guarded in
  make_tuple_from_result_row(), falls back to shipping ROW() when
  there's nothing local to reconstruct from) — verified against your
  exact repro plus a partitioned variant. Commit message is updated.

  @Manu: went with your option (1) rather than (2) for case_f — a
  remote-relkind check to refuse the non-direct path adds a round trip
  for every foreign table, on every query, to guard a case most
  installations won't hit, so postgres-fdw.sgml now has an explicit
  paragraph: chaining foreign tables (ft -> ft -> partitioned) is not
  detected, the remote tableoid is just the middle table's own OID, and
  correctness there is still on the user.


Please find attached V3. Request a review.


Thanks & Best Regards,
Ajit

On Wed, 16 Sept 2026 at 18:45, Manuel Reyes Bravo <manuelreyesbravo@gmail.com> wrote:
Ajit Awekar <ajitpostgres@gmail.com> wrote:
> Verified against your repros plus the full regression.

I tested v2 (cfbot branch for CF 6770, on master at 862092932c9) against
the same master without it, both with --enable-cassert, using a loopback
server.  The attached run_cases.sh runs each case file on a fresh
cluster.

What v2 fixes
-------------

- Etsuro's DELETE ... USING case: master deletes 20 rows instead of 10;
  with v2, exactly the 10 matching rows.

- The same corruption through triggers (case_d): remote partitioned
  table, foreign table with a dropped column in the middle, a column
  mapped with column_name, a different column order, a BEFORE UPDATE
  trigger changing NEW and an AFTER UPDATE trigger reading OLD.  On
  master, updating ids 1 and 2 leaves two rows with id 2 and none with
  id 1.  With v2 both rows are right, and OLD and NEW seen by the
  triggers are right, so the local whole-row reconstruction handles the
  dropped and renamed columns.

- A local partitioned table with one local and one foreign partition,
  UPDATE and DELETE with RETURNING tableoid and the whole row (case_g),
  and a self-join UPDATE (case_h): wrong rows on master, right with v2.

Jakub's zero-column case with a BEFORE DELETE trigger still fails the
assertion (postgres_fdw.c:9281 on this tree), while master runs it
fine.  Without the trigger, DELETE ... RETURNING ft1 on the same table
works on both.

What v2 does not fix: chained foreign tables
--------------------------------------------

When a foreign table points to another foreign table, which points to
the partitioned table, the wrong rows are still updated and deleted,
exactly as on master (case_f):

    CREATE TABLE r (id int, grp int, v text) PARTITION BY LIST (grp);
    CREATE TABLE r1 PARTITION OF r FOR VALUES IN (1);
    CREATE TABLE r2 PARTITION OF r FOR VALUES IN (2);
    INSERT INTO r VALUES (1, 1, 'one'), (2, 2, 'two');
    CREATE FOREIGN TABLE ft_mid (id int, grp int, v text)
      SERVER loopback OPTIONS (table_name 'r');
    CREATE FOREIGN TABLE ft_outer (id int, grp int, v text)
      SERVER loopback OPTIONS (table_name 'ft_mid');

    UPDATE ft_outer SET v = v || '!' WHERE id = 1 AND random() <= 1;

    SELECT tableoid::regclass, ctid, * FROM r ORDER BY id;
     tableoid | ctid  | id | grp |  v
    ----------+-------+----+-----+------
     r1       | (0,2) |  1 |   1 | one!
     r2       | (0,2) |  2 |   2 | one!

With log_statement = all the cause is visible.  The outer hop sends

    UPDATE public.ft_mid SET v = $3 WHERE ctid = $1 AND tableoid = $2
    Parameters: $1 = '(0,1)', $2 = '16408', $3 = 'one!'

where 16408 is ft_mid itself, so the tableoid condition matches every
row of ft_mid.  The middle hop then finds (0,1) in both partitions and
sends two updates, one per remote tableoid:

    UPDATE public.r SET v = $3 WHERE ctid = $1 AND tableoid = $2
    Parameters: $1 = '(0,1)', $2 = '16398', $3 = 'one!'
    UPDATE public.r SET v = $3 WHERE ctid = $1 AND tableoid = $2
    Parameters: $1 = '(0,1)', $2 = '16403', $3 = 'one!'

In the same case, DELETE ... WHERE id = 3 also deletes id 4.

So once the remote table is itself a foreign table, (ctid, tableoid)
is no longer a row identity.  I don't see how the outer hop could fix
that without knowing the remote relkind.  Maybe that is worth a
sentence next to the new partitioning note in postgres-fdw.sgml, or a
check of the remote relkind that refuses the non-direct path for it,
but I would rather ask what you think than propose one.  The EXPLAIN
output in this case now shows "WHERE ctid = $1 AND tableoid = $2",
which makes it look protected when it is not.

Regards,
Manu

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Ajit,

Ajit Awekar  wrote:
> @Manu: went with your option (1) rather than (2) for case_f
>
> Please find attached V3. Request a review.

Thanks, the new paragraph describes case_f as I saw it, including that
the remote tableoid is the middle foreign table's own OID.

I ran the same eight cases on V3, applied on master e8a3ee5b197, against
that master, both with --enable-cassert.  V3 builds without warnings,
and make check (239) and postgres_fdw's check pass.

- Jakub's zero-column case with a BEFORE DELETE trigger no longer fails
  the assertion; the output is the same as master's.
- Etsuro's DELETE ... USING case, the dropped and renamed columns with
  triggers, the mixed local and foreign partitions and the self-join
  give the right rows, as with v2.
- The zero-column RETURNING and the cross-partition cases are the same
  as master.
- The chained case still updates the wrong rows, as documented.

Since the commit message mentions the extra column and WHERE clause for
every non-direct UPDATE/DELETE, I measured it, on a loopback server
with 100000 rows, UPDATE ... WHERE id <= N AND random() <= 1, median of 5
runs:

                                  master      V3
    plain table, 1000 rows         26 ms     29 ms
    plain table, 10000 rows       234 ms    224 ms
    100 partitions, 1000 rows      42 ms    309 ms
    100 partitions, 10000 rows    102 ms   3606 ms

On a plain table I can't see a difference.  With partitions V3 looks
much slower, but it is not what it adds.  With log_min_duration_statement
= 0, for 1000 rows master sends 100 per-row UPDATEs and V3 sends 1000,
at the same cost each (0.20 ms in one run, 0.25 ms in another, the same
for both).  Master sends fewer because each
"WHERE ctid = $1" hits that ctid in every partition, so the rows already
changed are not fetched again.  Master is faster only because it is
doing the wrong thing.

What remains is the cost your paragraph describes: each per-row UPDATE
goes through the root and scans every partition, so with 100 partitions
a row costs about ten times what it costs on a plain table (309 ms vs
29 ms for 1000 rows).  Prepared on the remote side the way postgres_fdw
does it, "WHERE ctid = $1 AND tableoid = $2" costs about 10% more than
"WHERE ctid = $1" (190 vs 172 ms for 1000 executions), so the tableoid
condition itself is cheap.

The attached fdw_update_cost.sh does both measurements: the medians, and
the statements the remote side receives with their count and time.  It
takes an install prefix and a port, like run_cases.sh.  The numbers move
a bit between runs, but the counts don't.

I have nothing else to raise on V3.

Regards,
Manu

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
On Tue, Sep 22, 2026 at 10:44 AM Ajit Awekar  wrote:
>
>  Thanks Jakub and Manu for your reviews.
>
> Thanks to Robert Haas for suggesting the approach of carrying
> the remote tableoid through fdw_scan_tlist offline.
>[..]
>
> Please find attached V3. Request a review.

Hi Ajit, v3 needs rebase due to 90893c7b7cf "Fix EXPLAIN of dummy set
operations some more" (in setrefs.c, from ~1 week ago)

-J.


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Ajit Awekar <ajitpostgres@gmail.com>
Дата:
Вложения:
On Tue, 13 Oct 2026 at 16:44, Jakub Wartak
 wrote:
  > On Tue, Sep 22, 2026 at 10:44 AM Ajit Awekar  wrote:
  > > Please find attached V3. Request a review.
  >
  > Hi Ajit, v3 needs rebase due to 90893c7b7cf "Fix EXPLAIN of dummy set
  > operations some more" (in setrefs.c, from ~1 week ago)

 Hi Jakub, Done, V4 is attached, rebased on the current master
(e355089a57d).  Only
 setrefs.c needed manual changes; there is no functional change from V3.

  Thanks & Best Regards,
  Ajit

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi Ajit,

On Mon, Oct 19, 2026 at 11:17 AM Ajit Awekar 
wrote:
> Only setrefs.c needed manual changes; there is no functional change
> from V3.

I applied V4 to today's master (126976a8ffc).  It still applies
cleanly, builds with --enable-cassert without warnings, and make check
and postgres_fdw's check pass.  The eight cases from my V3 review give
output byte-identical to V3: the original case, the dropped and renamed
columns with triggers, the mixed partitions and the self-join return
the right rows; the chained case still updates the wrong rows, as
documented.

Regards,
Manu


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
On Sat, Oct 24, 2026 at 2:29 AM Manu  wrote:
>
> Hi Ajit,
>
> On Mon, Oct 19, 2026 at 11:17 AM Ajit Awekar 
> wrote:
> > Only setrefs.c needed manual changes; there is no functional change
> > from V3.
>
> I applied V4 to today's master (126976a8ffc).  It still applies
> cleanly, builds with --enable-cassert without warnings, and make check
> and postgres_fdw's check pass.  The eight cases from my V3 review give
> output byte-identical to V3: the original case, the dropped and renamed
> columns with triggers, the mixed partitions and the self-join return
> the right rows; the chained case still updates the wrong rows, as
> documented.

Judging from behaviour from postgres_fdw on master+v4 it's almost LGTM, please
set as Ready for Commiter with v5, hopefully Commiters notice this bugfix. I'm
already past of understanding of all what is happening in this patchset and
edge cases with executor:

Some open question for debate questions I have are:

a. Confirmed one another edge-case regression in the executor with v4, given:

   DROP TABLE big;
   DROP FOREIGN TABLE fbig;
   CREATE TABLE big (id int primary key, a int, b text);
   INSERT INTO big SELECT s, s, 'x'||s FROM generate_series(1,10) s;
   ANALYZE big;
   CREATE FOREIGN TABLE fbig (id int, a int, b text)
      SERVER loopback OPTIONS (table_name 'big');

   and now accessing whole row blows up:

   postgres=# DELETE FROM fbig WHERE fbig.* IS NULL AND random() <= 1;
   ERROR:  attribute 3 of type record has wrong type
   DETAIL:  Table has type fbig, but query expects record.
   postgres=# \errverbose
   ERROR:  42804: attribute 3 of type record has wrong type
   DETAIL:  Table has type fbig, but query expects record.
   LOCATION:  CheckVarSlotCompatibility, execExprInterp.c:2429

   and without v4 it is still working:

   postgres=# DELETE FROM fbig WHERE fbig.* IS NULL AND random() <= 1;
   DELETE 0

   quite funny thing is that ROW(id, a, b) instead of fbig.* works there.

b. in plenty of places, e.g. in set_rel_width() and add_vars_to_targetlist(),
   there is this thing:
       Assert(blabla.fdwroutine != NULL)
   for checking this trick of using >max_attr can be done only by FDWs. But
   some people developing custom FDWs probably might not run without asserts,
   so that wouldn't hit? Maybe we need runtime elog() to catch it? It's open
   question.

b. I think also you should split the patch into two files for their's easier
   review (something easy: one with optimizer changes and the second one with
   just postgres_fdw changes alone)

d. Perhaps, the remaining elephant in the room would be what to do with
   backpatching (today this might be corrupting data logically), but to me
   those optimizer/executor changes look like invasive (and/or risky).

-J.


Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Jakub,

On Wed, Oct 28, 2026 at 10:12 AM Jakub Wartak
 wrote:
>    postgres=# DELETE FROM fbig WHERE fbig.* IS NULL AND random() <= 1;
>    ERROR:  attribute 3 of type record has wrong type

Confirmed with V4 on master 126976a8ffc and fcfd2456078, and V3
already had it; master gives no error.  A DELETE whose local qual uses
the whole row fails the same way without random() and on a foreign
partition.  UPDATE works on a plain foreign table, but on a
foreign partition it fails with "record type has not been registered".

The ForeignScan's fdw_scan_tlist gets two whole-row entries, one typed
fbig and one RECORD: normalize_wholerow_vartype() retypes the qual's
Var (postgres_fdw.c:1515 with V4), so it no longer equal()s the one
from the reltarget and is appended (:1538).  setrefs.c matches on
varno/varattno only and takes the first, the fbig one.  The comment at
:1507 assumes core's RECORD Var is already there, which is true only
for UPDATE or with row DELETE triggers; with an AFTER DELETE row
trigger the RECORD entry comes first and the DELETE on the plain
foreign table works (on the partition it then fails like UPDATE).

Ajit, I'll set the entry to Ready for Committer once v5 covers this
and passes the eight cases plus the attached case_i_whole_row.sql.txt.

Regards,
Manu

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Ajit Awekar <ajitpostgres@gmail.com>
Дата:
Вложения:
 Hi Jakub, Manu,

  Thanks for the reviews. Attached is v5, split into two patches as suggested:

  - v5-0001: planner support for an FDW-injected row-identity
    pseudo-column (costsize.c, initsplan.c, setrefs.c, relnode.c, ruleutils.c).
    It has  no effect unless an FDW uses it.
  - v5-0002: the postgres_fdw part (deparse, executor, tests, docs). It depends
     on 0001.


Changes since v4:

  1. Whole-row regression.  The statement

       DELETE FROM fbig WHERE fbig.* IS NULL AND random() <= 1;

     now returns without error, as on master.  Manu's diagnosis was right:
     the retyped qual Var no longer equal()ed the row-typed entry in
     fdw_scan_tlist, so a second whole-row entry was appended and
     setrefs.c took the first one.  All whole-row entries are now typed
     RECORD and folded into one.

  2. Foreign table as a partition.  A whole-row qual in DELETE or
     UPDATE, through a local parent or directly on the partition,
     failed with "record type has not been registered".  Retyped Vars
     in quals are now wrapped in a RelabelType back to their original
     row type.  EXPLAIN shows (t.*)::t IS NULL in such filters;
     results are unchanged.

  3. The Assert(fdwroutine != NULL) checks are now runtime errors.

  I added regression tests for 1 and 2.  Manu's case_i_whole_row.sql
  (i1-i8) runs without errors on v5, with the same results as  master.

Request a review.

Thanks & Best Regards,
Ajit

On Thu, 29 Oct 2026 at 00:02, Manu  wrote:
>
> Hi Jakub,
>
> On Wed, Oct 28, 2026 at 10:12 AM Jakub Wartak
>  wrote:
> >    postgres=# DELETE FROM fbig WHERE fbig.* IS NULL AND random() <= 1;
> >    ERROR:  attribute 3 of type record has wrong type
>
> Confirmed with V4 on master 126976a8ffc and fcfd2456078, and V3
> already had it; master gives no error.  A DELETE whose local qual uses
> the whole row fails the same way without random() and on a foreign
> partition.  UPDATE works on a plain foreign table, but on a
> foreign partition it fails with "record type has not been registered".
>
> The ForeignScan's fdw_scan_tlist gets two whole-row entries, one typed
> fbig and one RECORD: normalize_wholerow_vartype() retypes the qual's
> Var (postgres_fdw.c:1515 with V4), so it no longer equal()s the one
> from the reltarget and is appended (:1538).  setrefs.c matches on
> varno/varattno only and takes the first, the fbig one.  The comment at
> :1507 assumes core's RECORD Var is already there, which is true only
> for UPDATE or with row DELETE triggers; with an AFTER DELETE row
> trigger the RECORD entry comes first and the DELETE on the plain
> foreign table works (on the partition it then fails like UPDATE).
>
> Ajit, I'll set the entry to Ready for Committer once v5 covers this
> and passes the eight cases plus the attached case_i_whole_row.sql.txt.
>
> Regards,
> Manu

Re: [(known) BUG] DELETE/UPDATE more than one row in partitioned foreign table

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi Ajit,

On Tue, Nov 3, 2026 at 6:59 AM Ajit Awekar 
wrote:
>   I added regression tests for 1 and 2.  Manu's case_i_whole_row.sql
>   (i1-i8) runs without errors on v5, with the same results as  master.

Confirmed on master 3ba886b35a2 with cassert: v5 builds without
warnings, make check and postgres_fdw's check pass, and
case_i_whole_row returns the same rows as master; only the plans
differ.  Through a single foreign table the duplicate-ctid UPDATEs and
DELETEs now hit the right rows (7 of 7, master 0 of 7), and the
chained case is unchanged, as the docs now say.

I've set the entry to Ready for Committer.

Regards,
Manu


FAQ