Re: improvements / reworks for FDW insert batching

From: Rui Zhao <zhaorui126(at)gmail(dot)com>
To: Tomas Vondra <tomas(at)vondra(dot)me>
Cc: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: improvements / reworks for FDW insert batching
Date: 2026-11-30 16:24:35
Message-ID: CAHWVJhH+OZ895Qs7RmAh077TrATHscYw+nfXSix-3p21wswFZg@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi Tomas,

Thanks for working on FDW insert batching. I've run into quite a few
problems with batch_size in production. I agree that the executor should
decide whether a given INSERT can be batched. If it can, the FDW can
then say how many rows it can handle at once.

1. Volatile functions that read the target foreign table

> I wonder if maybe there are additional cases where we need to disable
> batching

One case I found is a volatile default that reads the target foreign
table. I used an empty postgres_fdw table ft(id int, seen int) backed
by an ordinary table, with no triggers on either table:

CREATE FUNCTION count_ft() RETURNS int LANGUAGE sql VOLATILE AS
'SELECT count(*)::int FROM ft';
ALTER FOREIGN TABLE ft ALTER COLUMN seen SET DEFAULT count_ft();
INSERT INTO ft(id) VALUES (1), (2), (3);
SELECT array_agg(seen ORDER BY id) FROM ft;

With batch_size 1, I got {0,1,2}: each call to count_ft() saw the rows
inserted so far. I emptied the backing table and repeated the INSERT
with batch_size 10. This time I got {0,0,0}: all three calls ran before
the first batch was sent. I got the same results on master and v1.

The same issue can change which rows get inserted. In a separate test,
I used INSERT ... SELECT with a volatile function in WHERE that accepted
a positive ID only if the target was still empty. Of three positive IDs,
only the first was inserted with batch_size 1, but all three were
inserted with batch_size 10.

COPY FROM does not have this problem because CopyFrom() already checks
for volatile defaults and WHERE conditions. In copyfrom.c:1005 in v1:

else if (cstate->volatile_defexprs)
{
insertMethod = CIM_SINGLE;
}
else if (contain_volatile_functions(cstate->whereClause))
{
insertMethod = CIM_SINGLE;
}

So even with batch_size 10, COPY FROM wrote one row at a time. I got
{0,1,2} in the default test, and only the first row passed the WHERE
condition in the second test.

I tried making INSERT behave the same way. Checking only the input
target list in the executor would miss volatile functions in scan
filters or subplans. I found it easier to check the expressions as the
planner processes each level of the query tree and pass a flag to the
executor. That worked, but the change was more involved than I
expected. I'm still not sure this FDW batching issue warrants changes
to both the planner and the executor.

Should INSERT disable batching in these cases too, as COPY FROM does?

2. Switching to an unbatched foreign partition

I also tried two foreign partitions on the same remote connection:
A with batch_size 10 and B with batch_size 1. The input was ordered:
two rows for A, then one for B. A BEFORE INSERT trigger on the remote
table for B counted the rows in A. It saw zero with INSERT but two
with COPY FROM. INSERT had buffered the rows for A and sent B's row
first. COPY flushed A before writing B.

I tried the following change in ExecInsert(). B's trigger then saw both
rows in A, but the flush was too broad:

--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -1036,10 +1036,13 @@ ExecInsert(ModifyTableContext *context,
return NULL;
}

+ if (estate->es_insert_pending_result_relations != NIL)
+ ExecPendingInserts(estate);
+
/*
* insert into foreign table: let the FDW do it
*/
slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
resultRelInfo,
slot,
planSlot);

The pending list belongs to the whole EState, not just the ModifyTable
writing to B. In a separate test, those two lines also flushed rows
buffered by another INSERT in the same query. To match COPY, we'd need
to track which partitions have pending rows from this INSERT and flush
only those batches. Should INSERT do that when it switches to an
unbatched partition?

3. An INSERT that reads its target in a subquery

For this case I'd suggest a note in the batch_size description in
postgres-fdw.sgml rather than another executor check. With an empty
one-column foreign table and no triggers or defaults, I ran:

INSERT INTO ft
SELECT v.id FROM (VALUES (1),(2),(3),(4),(5)) v(id)
WHERE (SELECT count(*) FROM ft WHERE ft.id < v.id) = 0;

When the subquery runs on the remote server for each candidate row,
it can see earlier batches from the same transaction, but not rows
still buffered locally. With batch_size set to 1, 2 and 10, this
inserted 1, 3 and 5 rows respectively. The same query on a local
table inserted all five, so disabling batching is not a fix here.

4. Statement-level triggers and foreign keys on the remote table

The batch_size description in postgres-fdw.sgml says that each batch is
a single query. Could we mention what that means for triggers and
constraints on the remote table? I tried two examples.

First, I had a remote AFTER INSERT FOR EACH STATEMENT trigger count the
rows in its NEW TABLE. I ran one INSERT locally:

INSERT INTO ft VALUES (1), (2), (3);

With batch_size 1, the remote trigger fired three times and counted
one row each time. With batch_size 10, all three rows went in one
remote INSERT, so the trigger fired once and counted three rows.

Second, ft_nodes mapped to an empty remote table nodes, where parent_id
references nodes(id) and the foreign key is not deferrable. I inserted
the child before its parent in the same local statement:

INSERT INTO ft_nodes (id, parent_id) VALUES (2, 1), (1, NULL);

With batch_size 1, the first remote INSERT tried to insert the child
before node 1 existed. It failed with a foreign key violation (23503),
leaving the table empty. With batch_size 10, both rows went in one
remote INSERT. Node 1 existed when the foreign key was checked at the
end of that statement, so both rows were inserted.

Separately, your 0003 checks that both rows moved to the foreign
partition are sent in one remote INSERT, but log_stmt() doesn't read
the OLD TABLE. The attached test patch applies after your 0003 and
also checks that the parent trigger sees {2,2} after both keys change
from 2 to 1.

Regards,
Rui

Attachment Content-Type Size
nocfbot-0001-Check-old-rows-after-a-batched-cross-partition-update.patch application/octet-stream 3.8 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Diego 2026-11-30 16:33:34 Re: [PATCH] libpq: Add PQpassfileLookup()
Previous Message Melanie Plageman 2026-11-30 16:14:54 Re: Why clearing the VM doesn't require registering vm buffer in wal record