Report
Logical replication apply: cross-partition UPDATE inserts the new row even when a subscriber BEFORE DELETE trigger suppresses the delete, leaving the row in both partitions
- Severity
- 55
- Blamed commit
- f1ac27bfda6ce8a399d8001843e9aefff5814f9b
On 8 branches
REL_13_STABLE, REL_14_STABLE, REL_15_STABLE, REL_16_STABLE, REL_17_STABLE, REL_18_STABLE, REL_19_STABLE, master
Summary
When the logical replication apply worker applies an UPDATE to a partitioned table and the new row no longer belongs to the partition that holds the old row, it performs the update as a DELETE from the old partition followed by an INSERT into the new one (apply_handle_tuple_routing() in src/backend/replication/logical/worker.c). The INSERT is unconditional. If a BEFORE ROW DELETE trigger on the old partition returns NULL to suppress the delete (an ENABLE REPLICA or ENABLE ALWAYS trigger, so that it fires under the apply worker's session_replication_role = replica), the subscriber keeps the old row and also inserts the new one: one published UPDATE turns one row into two, and the subscriber silently and permanently has more rows than the publisher.
A local UPDATE in the same situation skips the INSERT when the DELETE did not happen (ExecCrossPartitionUpdate() in src/backend/executor/nodeModifyTable.c), precisely so that an UPDATE can never increase the number of rows. The apply path should behave the same way.
Present since PostgreSQL 13 (commit f1ac27bfda6). Affects REL_14_STABLE through REL_19_STABLE and master. Reproduced on master at 412848dac37f2e4455e1505f83f0af0f3d28a67d and on REL_17_STABLE.
Reproduction
Two instances; the publisher runs with wal_level = logical. The publisher table is not partitioned; the subscriber's table is partitioned on the key column so that changing a from 1 to 2 moves the row from tab_1 to tab_2. (A partitioned publisher table published with publish_via_partition_root = true behaves the same; what matters is that the subscriber receives an UPDATE for a table that is partitioned locally.)
Publisher:
CREATE TABLE tab (a int PRIMARY KEY, b text);
INSERT INTO tab VALUES (1, 'x');
CREATE PUBLICATION pub FOR TABLE tab;
Subscriber:
CREATE TABLE tab (a int PRIMARY KEY, b text) PARTITION BY LIST (a);
CREATE TABLE tab_1 PARTITION OF tab FOR VALUES IN (1, 3);
CREATE TABLE tab_2 PARTITION OF tab FOR VALUES IN (2, 4);
CREATE FUNCTION skip_delete() RETURNS trigger LANGUAGE plpgsql
AS $$ BEGIN RETURN NULL; END $$;
CREATE TRIGGER tab_1_skip_delete BEFORE DELETE ON tab_1
FOR EACH ROW EXECUTE FUNCTION skip_delete();
ALTER TABLE tab_1 ENABLE ALWAYS TRIGGER tab_1_skip_delete;
CREATE SUBSCRIPTION sub
CONNECTION 'host=... port=... user=... dbname=postgres'
PUBLICATION pub;
Wait for the initial synchronization to finish. For comparison, first run the same kind of UPDATE directly on the subscriber:
INSERT INTO tab VALUES (3, 'local');
INSERT 0 1
UPDATE tab SET a = 4 WHERE a = 3;
UPDATE 0
SELECT tableoid::regclass AS part, a, b FROM tab ORDER BY a;
part | a | b
-------+---+-------
tab_1 | 1 | x
tab_1 | 3 | local
(2 rows)
The trigger suppressed the DELETE and the executor therefore skipped the INSERT: row 3 stays in tab_1 and nothing appears in tab_2.
Now move the replicated row on the publisher and wait for the subscriber to catch up:
UPDATE tab SET a = 2 WHERE a = 1;
UPDATE 1
SELECT a, b FROM tab;
a | b
---+---
2 | x
(1 row)
Subscriber, actual result (master at 412848dac37):
SELECT tableoid::regclass AS part, a, b FROM tab ORDER BY a;
part | a | b
-------+---+-------
tab_1 | 1 | x
tab_2 | 2 | x
tab_1 | 3 | local
(3 rows)
Expected, by analogy with the local UPDATE above:
part | a | b
-------+---+-------
tab_1 | 1 | x
tab_1 | 3 | local
(2 rows)
The publisher has one row, (2, 'x'); the subscriber has that row and still has (1, 'x') as well. Nothing is logged on either side. Without the trigger the row is moved correctly, and a replicated UPDATE that stays within one partition is unaffected (it goes through ExecSimpleRelationUpdate(), which honours a suppressing BEFORE UPDATE trigger).
Analysis
apply_handle_update() hands UPDATEs on a locally partitioned table to apply_handle_tuple_routing() (worker.c). Its CMD_UPDATE branch locates the old tuple in its partition and checks whether the updated tuple still satisfies that partition's constraint. If not, it does:
/* DELETE old tuple found in the old partition. */
EvalPlanQualSetSlot(&epqstate, localslot);
TargetPrivilegesCheck(partrelinfo->ri_RelationDesc, ACL_DELETE);
ExecSimpleRelationDelete(partrelinfo, estate, &epqstate, localslot);
/* INSERT new tuple into the new partition. */
...
apply_handle_insert_internal(edata, partrelinfo_new, remoteslot_part);
ExecSimpleRelationDelete() (src/backend/executor/execReplication.c) runs the BEFORE ROW DELETE triggers and, when ExecBRDeleteTriggers() returns false because a trigger returned NULL, sets skip_tuple and does nothing further. It is declared void, so the caller cannot tell whether the tuple was deleted, and the INSERT into the new partition runs regardless.
The local executor handles the same split explicitly. ExecCrossPartitionUpdate() calls ExecDelete() with a tuple_deleted out parameter and then:
/*
* For some reason if DELETE didn't happen (e.g. trigger prevented it, or
* it was already deleted by self, or it was concurrently deleted by
* another transaction), then we should skip the insert as well;
* otherwise, an UPDATE could cause an increase in the total number of
* rows across all partitions, which is clearly wrong.
...
*/
if (!tuple_deleted)
That rule dates from commit 2f178441044 ("Allow UPDATE to move rows between partitions", PostgreSQL 11) and is covered by the trig_skip_delete test in src/test/regress/sql/update.sql. The apply-side implementation of the same operation, added by commit f1ac27bfda6ce8a399d8001843e9aefff5814f9b ("Add logical replication support to replicate into partitioned tables", PostgreSQL 13), did not carry the rule over: from the start it called the void delete routine and then inserted unconditionally. Commit a67da49e1d9 (PostgreSQL 18) changed the call from apply_handle_delete_internal() to a direct ExecSimpleRelationDelete(), but both are void and the behaviour is the same. So REL_14_STABLE through REL_17_STABLE (older shape) and REL_18_STABLE, REL_19_STABLE and master (newer shape) are all affected; REL_13_STABLE has the same code but is out of support.
This is distinct from the known limitation that a cross-partition UPDATE on the publisher is decoded as a separate DELETE and INSERT when the partitions are published individually; in that case the subscriber cannot tie the two together. Here the subscriber receives a single UPDATE and itself decides to split it, so it has everything it needs to honour the trigger's decision.
(Side note, not addressed here: in that split the apply worker fires BEFORE DELETE on the old partition and BEFORE INSERT on the new one, but not the BEFORE UPDATE triggers of the old partition that a local row-moving UPDATE fires first, as documented in the trigger chapter.)
Fix
Make ExecSimpleRelationDelete() return whether it deleted the tuple (true, or false when a BEFORE ROW DELETE trigger suppressed it), and have apply_handle_tuple_routing() skip the INSERT when it returns false, mirroring ExecCrossPartitionUpdate(). The other caller, apply_handle_delete_internal(), can ignore the result. The attached patch for master does this and adds a test to src/test/subscription/t/013_partition.pl that fails before the fix (got tab6_1|1|x and tab6_2|2|x, expected only tab6_1|1|x) and passes after it.
For the back branches the same change is needed, but ExecSimpleRelationDelete() is declared in src/include/executor/executor.h and is callable by extensions. Changing its return type from void to bool is binary-compatible for existing callers on the usual ABIs (an ignored return register), but it is still a declared-interface change in a minor release. Options: accept the signature change; or keep the void function as a wrapper and add a variant that returns the result (or takes an out parameter) for the apply worker to call. In REL_14_STABLE through REL_17_STABLE the cross-partition branch calls the static apply_handle_delete_internal() rather than ExecSimpleRelationDelete() directly, so that function has to propagate the result as well. The master patch applies cleanly to REL_18_STABLE and REL_19_STABLE but was not built or tested there.
Testing
Master at 412848dac37f2e4455e1505f83f0af0f3d28a67d, debug build with assertions enabled:
- The hand-run reproduction above, unpatched: 3 rows on the subscriber versus 1 on the publisher; the local UPDATE control leaves 2 rows and moves nothing.
- An ad-hoc TAP test with two variants (non-partitioned publisher table; partitioned publisher table published with publish_via_partition_root = true) shows the duplicate in both variants on master and on REL_17_STABLE (17.11 tip), and no duplicate on master with the patch. A cross-partition update whose delete is not suppressed still moves the row with the patch.
- With the patch, src/test/subscription/t/013_partition.pl passes (77 subtests, including the new one); with only the test change and an unpatched server the new subtest fails as described above.
- The whole src/test/subscription suite passes with the patch (39 tests).
- pgindent reports no changes on the modified files.
Prior discussion
No report of this behaviour was found in the pgsql-bugs or pgsql-hackers archives. The closest related discussion is on the thread of the original row-movement commit, in January 2018, before subscriber-side partitioned tables existed: CAA4eK1LTDpd8QwZVoyuL4VsU0x2zMur05-34G8bVSTJu3zGpdQ@mail.gmail.com asked how logical replication should treat triggers for row movement; the answer concerned the publisher-side decoding limitation described above, not the apply worker's own split.