Report
Changing a publication row filter can turn a later UPDATE into a conflicting INSERT
- Severity
- 42
- Blamed commit
- 52e4f0cd472d39d07732b99559989ea3b615be78
On 6 branches
REL_15_STABLE, REL_16_STABLE, REL_17_STABLE, REL_18_STABLE, REL_19_STABLE, master
Summary
pgoutput transforms an UPDATE into an INSERT when the
old row misses the publication row filter and the new
row matches it. That rule assumes the old row was never
sent to the subscriber. After ALTER PUBLICATION ... SET TABLE ... WHERE, the assumption can be false: the
row may already have been published under the previous
filter, including earlier in the same transaction.
Apply then stops with conflict=insert_exists.
Reproduction
On the publisher and subscriber, with
synchronous_commit=on:
-- publisher and subscriber
CREATE TABLE trf (
id int PRIMARY KEY, a int, note text);
ALTER TABLE trf REPLICA IDENTITY FULL;
-- publisher
CREATE PUBLICATION pubrf FOR TABLE trf;
-- subscriber
CREATE SUBSCRIPTION subrf
CONNECTION '...' PUBLICATION pubrf
WITH (copy_data = false);
Wait until the subscription is ready, then on the publisher:
BEGIN;
INSERT INTO trf VALUES (2, -1, 'pre-neg');
ALTER PUBLICATION pubrf SET TABLE trf WHERE (a > 0);
UPDATE trf SET a = 6 WHERE id = 2;
COMMIT;
Expected: the subscriber ends with (2, 6, 'pre-neg'),
as an UPDATE of the row already sent before the filter
change.
Actual: the apply worker logs
ERROR: conflict detected on relation "public.trf":
conflict=insert_exists
and does not catch up. The publisher has
(2, 6, 'pre-neg'); the subscriber still has no row.
The same conflict occurs if the row was copied or
replicated in an earlier transaction, the filter is
tightened afterwards, and an UPDATE then moves the row
into the new filter.
Analysis
pgoutput_row_filter() in
src/backend/replication/pgoutput/pgoutput.c
evaluates the filter that is in force for that change
(the historic publication definition). When the old row
misses and the new row matches, the UPDATE is emitted
as an INSERT. The comments there, and the "UPDATE
Transformations" section of the logical-replication
documentation, state that an old-row miss means the row
was not sent to the subscriber (or "probably" was not
copied by initial synchronization).
Those documents do not describe this outcome as
expected when the filter itself changes.
ALTER PUBLICATION cautions that toggling
publish_via_partition_root can lose or duplicate
rows, but it has no similar warning for
SET TABLE ... WHERE. Changing the WHERE clause of an
already-subscribed table also does not require
REFRESH PUBLICATION.
The transform was introduced in commit 52e4f0cd472d39d07732b99559989ea3b615be78 ("Allow specifying row filters for logical replication of tables").
Notes
Reproduced on master at 81b2179b492e3af891544813b7e22a42386b34d0.