Logical replication row filter loses unchanged toasted columns
Logical replication row filter loses unchanged toasted columns
От:
Shinya Kato <shinya11.kato@gmail.com>
Дата:
Hi hackers,
I found a bug in the row filter's UPDATE to INSERT transformation. An
unchanged column that is stored out-of-line silently becomes NULL on
the subscriber, unless it is part of the replica identity. This has
been there since row filters were added in commit 52e4f0cd472, so 15
and up are affected.
Reproduction:
```
-- publisher
CREATE TABLE t (id int PRIMARY KEY, body text);
ALTER TABLE t ALTER COLUMN body SET STORAGE EXTERNAL;
CREATE PUBLICATION p FOR TABLE t WHERE (id = 7);
INSERT INTO t VALUES (3, repeat('a', 5000));
-- subscriber
CREATE TABLE t (id int PRIMARY KEY, body text);
CREATE SUBSCRIPTION s CONNECTION 'dbname=postgres port=5432' PUBLICATION p;
-- publisher
UPDATE t SET id = 7; -- moves the row into the filter
-- subscriber
\pset null '(null)'
SELECT id, body FROM t;
id | body
----+--------
7 | (null)
(1 row)
```
pgoutput_row_filter() copies unchanged out-of-line values over from
the old tuple, but unless the replica identity is FULL the old tuple
carries only the replica identity columns. Any other column is still
an external on-disk pointer, so logicalrep_write_tuple() sends it as
LOGICALREP_COLUMN_UNCHANGED, which an INSERT cannot express, and
slot_store_data() stores a NULL. Where the column is NOT NULL, the
apply worker fails with a constraint violation and replication stops.
We cannot simply fill the value in. As Petr put it when
LOGICALREP_COLUMN_UNCHANGED was being discussed [1], such values "are
not written to WAL nor accessible via historic snapshot", so the
output plugin never sees them.
I see three ways to deal with this.
Option A: detect the missing value in pgoutput_row_filter() and raise
an error naming the table and the column, trading silent data loss for
a loud failure. The catch is that the error is not recoverable. Once
the change is in WAL, neither ALTER TABLE ... REPLICA IDENTITY FULL
nor dropping the row filter helps, because decoding uses the historic
catalog snapshot from the time of the change. The only way forward is
pg_replication_slot_advance() or recreating the subscription.
Option B: when a table belongs to a publication with a row filter,
make heap_update() log the whole old tuple, as it already does for
REPLICA IDENTITY FULL. The existing copy loop then finds the value,
the INSERT is complete, and no error is needed. This is the real fix,
but every UPDATE of such a table writes the unchanged out-of-line
value to WAL even when no transformation happens, which can be a large
regression. It also needs a new field in PublicationDesc, so I do not
think it can be back-patched.
Option C: document the restriction and leave the behavior alone. This
is the only option that changes nothing on the back branches, but the
value keeps disappearing without any warning.
I lean towards A because losing data silently seems worse than
stopping, but the unrecoverable error bothers me. Which approach do
you prefer, and should the fix be back-patched?
[1] https://www.postgresql.org/message-id/1f3a3b7d-3ea2-630c-1b99-368df3fdecdf%402ndquadrant.com
--
Shinya Kato
NTT OSS Center
Re: Logical replication row filter loses unchanged toasted columns
От:
Nikhil Sontakke <nikhil@planetscale.com>
Дата:
Option B: when a table belongs to a publication with a row filter,
make heap_update() log the whole old tuple, as it already does for
REPLICA IDENTITY FULL. The existing copy loop then finds the value,
the INSERT is complete, and no error is needed. This is the real fix,
but every UPDATE of such a table writes the unchanged out-of-line
value to WAL even when no transformation happens, which can be a large
regression. It also needs a new field in PublicationDesc, so I do not
think it can be back-patched.The concern with option B is that every UPDATE of a row-filtered table
would write the unchanged out-of-line value even when no transformation
happens. I think that can be narrowed considerably: the extra logging
can be done based on HeapTupleHasExternal(), which is a single infomask bit
test requiring no deforming. ExtractReplicaIdentity() already uses
exactly that gate for REPLICA IDENTITY FULL.
The cost then falls on every UPDATE of a row-filtered table whose row
currently holds out-of-line values, rather than on every UPDATE of such
a table. Where the wide column is usually NULL or stays inline this is
close to free, and where every row is toasted the cost is real -- but
that is precisely the case where the current behaviour loses data.
What makes B attractive is that it needs no change to the output plugin,
the protocol or the subscriber. Once the old tuple carries the
flattened values, the copy loop already in pgoutput_row_filter() finds
them and the INSERT goes out complete. It is the same mechanism that
makes REPLICA IDENTITY FULL work today.
I took a close look at option B and it might not be so attractive (what ever is? :-))
and might need invasive changes.
I agree it cannot be back-patched, for the reasons given: it needs to
know at heap_update() time that the table is published with a row
filter, and it would introduce a WAL volume regression in a minor
release.Option C: document the restriction and leave the behavior alone. This
is the only option that changes nothing on the back branches, but the
value keeps disappearing without any warning.I lean towards A because losing data silently seems worse than
stopping, but the unrecoverable error bothers me. Which approach do
you prefer, and should the fix be back-patched?
Rather than choosing among the three, would this combination work?
- back branches (15 and up): the subscriber-side error described
above, together with a documentation note in the UPDATE
transformation section stating that a column which is stored
out-of-line, unchanged, and outside the replica identity cannot be
carried through the transformation, and that REPLICA IDENTITY FULL
avoids it.
But this backpatching reason still holds good as far as I can see!
Regards,
Nikhil
- master: option B, so the INSERT is complete and no error is needed.
Option C then becomes the documentation half of the first item rather
than a standalone choice.
One thing worth being explicit about: back-patching an error changes
behaviour in a minor release. I still think it is the right trade, since thealternative is undetectable data loss, and where the column is NOT NULLreplication already fails today—just with a constraint violation that pointsat the symptom rather than the cause.Thanks,
---
Nikhil Sontakke
PlanetScale
Re: Logical replication row filter loses unchanged toasted columns
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Aug 13, 2026 at 11:12 AM Zhijie Hou (Fujitsu) wrote: > > I feel catching such an unchanged toasted column issue during INSERT in the > apply worker could be better. The apply worker provides native context about the > transaction and the action being replayed, making the error easier to diagnose. > Erroring in the apply worker also gives users more flexibility to resolve the > issue, for example, they could define a temporary trigger on the target table to > skip the conflict or fill in the toasted value manually (after querying it from > the publisher), or skip the whole transaction using ALTER SUB SKIP, or disable > the subscription for now and analyze the issue and resolve later. > Sounds like a reasonable approach to fix the problem. > I also thought of reporting ERROR during DML, like putting this in > CheckCmdReplicaIdentity, but we can't tell at that point whether the tuple > being updated has a toasted column. And we also could not simply error out in > CheckCmdReplicaIdentity for any column that could be toasted, because lots of > columns types (text, varchar ...) is default with EXTENDED storage that can > potentially be toasted, so that would be too broad. > > The only feasible place for DML error is at a lower level, like heap_update, > where we can error out if an unchanged toasted column (that is not part of the > replica identity) is being updated on a table published with a row filter. > However, this might overkill in cases where the row filter would not convert the > update to an INSERT, and I'm not sure we want to evaluate the row filter > expression during DML to do more detailed check. So I think it's not a great > idea to do it in DML. > > Beyond this specific row filter issue, I'm thinking about a more general > problem: when an unchanged toasted column is not logged in the new tuple, the > subscriber cannot perform proper conflict resolution. For example, if an update > hits an update_exists conflict and the user wants to keep the remote change > (converting the UPDATE to an INSERT), without the unchanged toasted value, the > resolution lacks the data needed for the INSERT. I think we may need to support > logging additional columns beyond the replica identity in the future to address > this. > > BTW, other CDC solutions also suffer from the lack of unchanged toasted > columns - I've seen several blogs mention this as a limitation [1][2]. > > So, I think after applying the fix to report an ERROR, it would be worth > implementing an additional WAL logging feature on top of it, allowing users to specify > which columns should be logged in WAL for logical decoding and replication. I > can see several use cases for this: 1) Allowing users to add non-RI columns to > publication row filter expressions. 2) Helping with conflict resolution. 3) > Giving subscriber replication workers more column data for analysis, such as > detecting whether two transactions modify the same subscriber-only unique index > and enabling parallel apply if not. 4) Making it easier for other CDC solutions > to handle missing values. > The only way to support these currently is to use REPLICA IDENTITY FULL which could be costly. One idea is to have INCLUDE-like syntax similar to what we have for CREATE INDEX to include columns for WAL logging unchanged toast columns. However, we can do that as a HEAD-only improvement in a separate thread. -- With Regards, Amit Kapila.
Re: Logical replication row filter loses unchanged toasted columns
On Wed, 12 Aug 2026 at 05:23, Shinya Kato wrote: > > I see three ways to deal with this. > > Option A: detect the missing value in pgoutput_row_filter() and raise > an error naming the table and the column, trading silent data loss for > a loud failure. [...] > > Option B: when a table belongs to a publication with a row filter, > make heap_update() log the whole old tuple, as it already does for > REPLICA IDENTITY FULL. [...] > > Option C: document the restriction and leave the behavior alone. [...] Or, an option D: Forbid the creation (and use) of filtered publication table definitions for tables which contain a non-identity varlena-typed column (i.e. the type's typlen is -1). Publishing varlena identity columns is safe, and users can just avoid including varlena columns when they add a filter; we should not allow users to create publications of which we know ahead of time that the data stream is likely to break on our side. I think this option D can be backported, but would require some pg_upgrade checks. Kind regards, Matthias van de Meent Databricks (https://www.databricks.com)
Re: Logical replication row filter loses unchanged toasted columns
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Aug 13, 2026 at 7:20 PM Matthias van de Meent wrote: > > On Wed, 12 Aug 2026 at 05:23, Shinya Kato wrote: > > > > I see three ways to deal with this. > > > > Option A: detect the missing value in pgoutput_row_filter() and raise > > an error naming the table and the column, trading silent data loss for > > a loud failure. [...] > > > > Option B: when a table belongs to a publication with a row filter, > > make heap_update() log the whole old tuple, as it already does for > > REPLICA IDENTITY FULL. [...] > > > > Option C: document the restriction and leave the behavior alone. [...] > > Or, an option D: Forbid the creation (and use) of filtered publication > table definitions for tables which contain a non-identity > varlena-typed column (i.e. the type's typlen is -1). > I think even if we want to block operations that can create such a situation, we should reject only the specific updates that lead to the problem, not every update on a table that merely has the potential for it. We already do something similar: UPDATE/DELETE is rejected when there's no replica identity and the table's publications publish those operations. I'd like to apply the same principle here. With that in mind, I could think of following two options: Option 1 Check at DML time, inside heap_update(): Detect the problem per-row, at the point where old/new tuple data is actually available when following conditions are met: the relation is published and has UPDATEs enabled, (b) some publication defines a row filter on it, (c) the replica identity key changed value in this UPDATE, (d) the old tuple has some externally-stored (TOASTed) attribute (HeapTupleHasExternal()), and (e) some specific non-replica-identity column's value is unchanged and still stored out-of-line. Only an UPDATE that actually satisfies all five conditions is rejected, with an error naming the offending column. All other UPDATEs on the same table proceed normally, including ones that don't touch the key, or ones where the TOASTed column did change. Conditions (a), (b), (c) reuse state heap_update() already computed for other purposes, so they add no real cost. Condition (d) gates condition (e), so the per-attribute scan only runs when the old tuple actually has a toasted value, which shouldn't be a hot code path as such an update has other toast related overhead as well. Option 2: Check at statement time, inside CheckCmdReplicaIdentity(): Reject upfront, before any row is touched, whenever: (a) the relation is published and has UPDATEs enabled, (b) some publication defines a row filter on it, (c) the relation has some toastable column outside the replica identity, and (d) the relation has a TOAST table (reltoastrelid is valid). This is cheaper to check (no per-row work, no tuple deform) and fails fast, but it's necessarily broader: toastability and the presence of a toast table are static, table-wide properties, not row properties. A table matching all four conditions would have every UPDATE rejected, including ones that never touch the key column and ones where the TOASTed column's current value happens to be short enough to be stored inline. I lean towards Option 1 (at least for master branch) for the reason above. Thoughts? -- With Regards, Amit Kapila.
Re: Logical replication row filter loses unchanged toasted columns
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
Вложения:
On Mon, Aug 17, 2026 at 5:45 PM Matthias van de Meent wrote: > > I don't understand the position of the LR developers here. > > AFAIK, Logical Replication is (and has been) positioned as a > transparent add-on feature, that adds a new feature (replicating the > logical changes in a database) without removing functionality (such as > DML). LR's lack of support for certain functionalities (such as DDL, > or until recently sequences) didn't remove those functionalities from > the table or database that was configured for DDL, but instead the > feature was built in a way that replication couldn't be set up for > some features (sequences), or the replication stream would move into > an error state (most breaking DDL changes). > > The solution that the developers seem to lean towards here is exactly > opposite to this: Enabling logical replication on a table breaks [^1] > (or would break [^2]) existing DML workloads. > The reason for existing behavior is that users can add/change RI after creating publications, so we can't simply reject creating publications when a proper RI is not defined on the table yet. Another related example is that CREATE PUBLICATION p FOR TABLE t WHERE (non_ri_col > 5) succeeds today even if t's RI doesn't cover non_ri_col but will give error at UPDATE/DELETE time. So, we are trying to follow the similar pattern here. > > [^1] tables without replication identity can recieve neither UPDATEs > nor DELETEs if those commands are included in the publication. > [^2] the general direction of this thread seems to lean towards > blocking DML on affected tables. -- With Regards, Amit Kapila.
RE: Logical replication row filter loses unchanged toasted columns
On Thursday, August 20, 2026 6:31 PM Amit Kapila wrote: > > On Wed, Aug 19, 2026 at 10:55 PM Amit Kapila > wrote: > > > > > > On Thu, Aug 20, 2026 at 4:54 AM Masahiko Sawada > wrote: > > > > > > > It can cost us high in some cases that can occur in the narrow > > > window of above conditions. I could think of two major points to consider: > > > (a) Changed toasted columns don't need their old value logged at all > > > — once a column is toasted in this transaction, its new value is > > > already fully resolvable from the new tuple, so flattening the old > > > tuple just pays a detoast fetch and extra WAL for a value nothing > > > downstream reads; (b) The trigger condition (rf_exists_for_update && > > > id_key_changed && HeapTupleHasExternal(oldtup)) can't tell whether > > > the filter's match result actually differs between old and new row > > > (we need additional WAL only when row_filter matches new row but not > > > old), since that needs evaluating the filter itself, already > > > rejected as too invasive inside heap_update(). > > > > I think we can somehow check (a) during heap_update(). But I agree > > that we should not check (b) during heap_update(). > > > > Fair enough. I think we can try to come up with a patch and see if it is good for > both HEAD and back-branches. BTW, one thing to note in at least the current > posted patch, there is an ABI break with new member rf_exists_for_update in > PublicationDesc. I feel as it can be added at the end of structure, the chances > of breaking any existing extension are very less. Also, the new parameter in > pub_rf_contains_invalid_column could be harmless as the function shouldn't > be used but we can overcome that by having a separate function like > pub_has_row_filter() as shown in Hou-San's patch for > PG18 version. Here is the patch (on HEAD) for the suggested approach. I extended extractReplicaIdentity to also extract unchanged toasted columns, as it fits best there, we only need to log unchanged toast columns when the replica identity changes. Since it now extracts more than just the replica identity, I renamed it to the more general BuildOldKeyTuple. The new logic to find unchanged toasted columns reuses the existing loop that marks non-replica-identity columns as NULL for old tuples, so the additional overhead (beyond the new WAL logging) should not be noticeable. Best Regards, Zhijie Hou