Add a hook for handling logical decoding messages on subscribers.

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

Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
Hi all,

Commit ac4645c015 allows pgoutput to send logical decoding messages,
but it's limited to applications that use the pgoutput plugin -- the
built-in logical replication doesn't use it. I'd like to propose
introducing a hook to the logical replication message handling so that
extensions can plug in their own handling routine. This feature can be
used for extensions to implement DDL replication, function
replication, or trigger user-specific routines on the subscriber side.

I've attached the PoC patch; it adds a hook function, and adds a new
'message' subscription option that allows the user to request the
publisher to send logical decoding messages. Therefore, users need to
enable the 'message' option and set up the hook function at server
startup in order to receive the messages and trigger the hook
function.

I I went with a hook function in the patch. While it lets you chain
the multiple hook functions, providing the registration API might be
better, or other types of registry can also be considered.

Feedback is very welcome.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi,

On Fri, Jun 19, 2026 at 3:34 PM Masahiko Sawada  wrote:
>
> Hi all,
>
> Commit ac4645c015 allows pgoutput to send logical decoding messages,
> but it's limited to applications that use the pgoutput plugin -- the
> built-in logical replication doesn't use it. I'd like to propose
> introducing a hook to the logical replication message handling so that
> extensions can plug in their own handling routine. This feature can be
> used for extensions to implement DDL replication, function
> replication, or trigger user-specific routines on the subscriber side.

Thanks for working on this!

> I've attached the PoC patch; it adds a hook function, and adds a new
> 'message' subscription option that allows the user to request the
> publisher to send logical decoding messages. Therefore, users need to
> enable the 'message' option and set up the hook function at server
> startup in order to receive the messages and trigger the hook
> function.

I understand the intent of the proposal, but I'd like to get the
bigger picture first.

Do we have any external modules that actually implement DDL
replication (or any of the listed use-cases) with a similar hook? Or
any existing discussion? I could be missing something because I
haven't looked at all the DDL replication related threads.

Another thing I'm curious about - why a hook? Is the plan to implement
DDL replication as an external module rather than in core? If DDL
replication eventually gets into core, I'd expect it to be apply-side
logic executing the decoded DDL messages directly, not something going
through a hook.

Why not a hook at apply_dispatch to give external modules more freedom
with the pgoutput plugin?

> I I went with a hook function in the patch. While it lets you chain
> the multiple hook functions, providing the registration API might be
> better, or other types of registry can also be considered.

It's hard to tell how many external modules would make use of this
hook (rather, how many external modules implementing this hook one
would allow to be installed in a production database requiring
chaining), but my first thought is that a registration-based API along
the lines of RegisterXactCallback would be cleaner and work better.

> Feedback is very welcome.

A few comments on the patch:

1/
+ bool message; /* True if the subscription wants to receive
+ * logical messages */
 } Subscription;

Nit: I'd call these logical decoding messages or generic logical
messages - something to match the docs and pg_logical_emit_message.

2/
+void
+test_logical_message_handler(LogicalRepMessageData *msg)
+{
+ ereport(LOG,
+ (errmsg("received message: LSN %X/%08X, prefix: %s, message: %s",
+ LSN_FORMAT_ARGS(msg->lsn),
+ msg->prefix,
+ msg->message)));
+}

Why not have the test extension do a simple DDL/function/event-trigger
based replication? It doesn't need to be a full-blown implementation,
but to show the usefulness of this hook, it's better to have one
demonstrating the listed use-cases.

3/
+ if (subinfo->submessage)
+ appendPQExpBufferStr(query, ", message = true");

Why a subscription-level option? Why not leave the decision of whether
or not to act on the message to the external module implementers?

4/
+ /*
+ * Logical messages are handled only the (parallel) apply workers
+ */
+ if (am_tablesync_worker() || am_sequencesync_worker())
+ return;

Why these restrictions? Why not leave the decision to external module
implementers? Isn't this limiting - what if someone wants to use this
hook for the schema sync during the initial table sync phase?

5/ With this change, pg_logical_emit_message does affect the logical
replication apply if the subscriber has defined this hook. I think
it's worth mentioning in the docs for pg_logical_emit_message.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Jun 23, 2026 at 4:09 AM Bharath Rupireddy
 wrote:
>
> On Fri, Jun 19, 2026 at 3:34 PM Masahiko Sawada  wrote:
> >
> > Hi all,
> >
> > Commit ac4645c015 allows pgoutput to send logical decoding messages,
> > but it's limited to applications that use the pgoutput plugin -- the
> > built-in logical replication doesn't use it. I'd like to propose
> > introducing a hook to the logical replication message handling so that
> > extensions can plug in their own handling routine. This feature can be
> > used for extensions to implement DDL replication, function
> > replication, or trigger user-specific routines on the subscriber side.
>
> Thanks for working on this!
>
> > I've attached the PoC patch; it adds a hook function, and adds a new
> > 'message' subscription option that allows the user to request the
> > publisher to send logical decoding messages. Therefore, users need to
> > enable the 'message' option and set up the hook function at server
> > startup in order to receive the messages and trigger the hook
> > function.
>
> I understand the intent of the proposal, but I'd like to get the
> bigger picture first.
>
> Do we have any external modules that actually implement DDL
> replication (or any of the listed use-cases) with a similar hook? Or
> any existing discussion? I could be missing something because I
> haven't looked at all the DDL replication related threads.
>
> Another thing I'm curious about - why a hook? Is the plan to implement
> DDL replication as an external module rather than in core? If DDL
> replication eventually gets into core, I'd expect it to be apply-side
> logic executing the decoded DDL messages directly, not something going
> through a hook.
>

I think it is important to have some example extension implementation
to see how the hook could be utilized. One more use of such a hook
could be to use for audit of DDLs replayed on subscribers. BTW, can we
also consider it as a solution implementing basic DDL replication for
tables? The key question is what if someday we have in-core DDL
replication. I think extensions can still be used to implement
filtering or transformation of DDL. We can implement capture of DDL
using JSON format [1] so that it is forward compatible with in-core
DDL replication. So considering that, the extension handlers will look
like:

 _PG_init(void)
  {
      /* Publisher side */
      prev_ProcessUtility = ProcessUtility_hook;
      ProcessUtility_hook = ddlrep_ProcessUtility;

.....
      /* Subscriber side */
      prev_message_handler  = logical_message_handler;
      logical_message_handler = ddlrep_message_handler;

static void
  ddlrep_ProcessUtility(PlannedStmt *pstmt,
                         const char *queryString,
                         bool readOnlyTree,
                         ProcessUtilityContext context,
                         ParamListInfo params,
                         QueryEnvironment *queryEnv,
                         DestReceiver *dest,
                         QueryCompletion *qc)
  {
      bool replicate = should_replicate(pstmt);

      /*
       * Execute the DDL first.
       */
      if (prev_ProcessUtility)
          prev_ProcessUtility(pstmt, queryString, readOnlyTree, context,
                              params, queryEnv, dest, qc);
      else
          standard_ProcessUtility(pstmt, queryString, readOnlyTree, context,
                                  params, queryEnv, dest, qc);

      if (replicate)
      {
          const char *tag =
GetCommandTagName(CreateCommandTag(pstmt->utilityStmt));
          char       *msg = build_ddl_message(tag, queryString);

          /*
           * transactional = true  → message held in ReorderBuffer, emitted
           * to subscribers at COMMIT in WAL order relative to any DML in
           * the same transaction.
           *
           * omit_lsn = false → include the LSN so the subscriber can log
           * exactly which WAL position a given DDL came from.
           */
          LogLogicalMessage("pg_ddl", msg, strlen(msg),
                            true  /* transactional */,
                            false /* omit_lsn */);

...

 static void
  ddlrep_message_handler(const char *prefix,
                          Size sz,
                          const char *message,
                          bool transactional,
                          XLogRecPtr lsn)
  {
      char           *payload;
      char           *ddl;
      char           *search_path;
      StringInfoData  cmd;
      int             spi_rc;

      /*
       * Always pass through to the previous handler first.  This ensures
       * correct behaviour when chained with other extensions.
       */
      if (prev_message_handler)
          prev_message_handler(prefix, sz, message, transactional, lsn);

      if (strcmp(prefix, "pg_ddl") != 0)
          return;

    /* Write code to execute/perform DDL. */

When we have a built-in handler then the apply worker carefully
registers the same and gives an ERROR if the extension one is already
registered.

void
  ApplyWorkerMain(Datum main_arg)
  {
      /* ... existing initialisation ... */

      /*
       * If the subscription requests built-in DDL replication and an
       * extension has also registered a logical message hook, both would
       * process the same "pg_ddl" messages and execute DDL twice.
       * Refuse to start rather than silently corrupt.
       */
      if (MySubscription->ddloption != DDL_OPTION_NONE &&
          logical_message_hook != NULL)
          ereport(ERROR,
                  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                   ....

      /*
       * No conflict — register the built-in DDL handler when the
       * subscription requests DDL replication and no extension owns
       * the hook.
       */
      if (MySubscription->ddloption != DDL_OPTION_NONE)
          logical_message_hook = builtin_ddl_message_handler;

[1]
The JSON format for WAL could be of form to keep it extendable:

{
    "version": 1,
    "command_tag": "CREATE TABLE",
    "object_type": "table",
    "schema": "public",
    "identity": "public.foo",
    "ddl_text": "CREATE TABLE public.foo (id int PRIMARY KEY)",
    "search_path": "public"
 }


>
> Why not a hook at apply_dispatch to give external modules more freedom
> with the pgoutput plugin?
>

What advantage do you see with the same?

-- 
With Regards,
Amit Kapila.


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Tue, Jun 23, 2026 at 1:52 AM Amit Kapila  wrote:
>
> On Tue, Jun 23, 2026 at 4:09 AM Bharath Rupireddy
>  wrote:
> >
> > On Fri, Jun 19, 2026 at 3:34 PM Masahiko Sawada  wrote:
> > >
> > > Hi all,
> > >
> > > Commit ac4645c015 allows pgoutput to send logical decoding messages,
> > > but it's limited to applications that use the pgoutput plugin -- the
> > > built-in logical replication doesn't use it. I'd like to propose
> > > introducing a hook to the logical replication message handling so that
> > > extensions can plug in their own handling routine. This feature can be
> > > used for extensions to implement DDL replication, function
> > > replication, or trigger user-specific routines on the subscriber side.
> >
> > Thanks for working on this!
> >
> > > I've attached the PoC patch; it adds a hook function, and adds a new
> > > 'message' subscription option that allows the user to request the
> > > publisher to send logical decoding messages. Therefore, users need to
> > > enable the 'message' option and set up the hook function at server
> > > startup in order to receive the messages and trigger the hook
> > > function.
> >
> > I understand the intent of the proposal, but I'd like to get the
> > bigger picture first.
> >
> > Do we have any external modules that actually implement DDL
> > replication (or any of the listed use-cases) with a similar hook? Or
> > any existing discussion? I could be missing something because I
> > haven't looked at all the DDL replication related threads.
> >
> > Another thing I'm curious about - why a hook? Is the plan to implement
> > DDL replication as an external module rather than in core? If DDL
> > replication eventually gets into core, I'd expect it to be apply-side
> > logic executing the decoded DDL messages directly, not something going
> > through a hook.
> >
>
> I think it is important to have some example extension implementation
> to see how the hook could be utilized. One more use of such a hook
> could be to use for audit of DDLs replayed on subscribers.

Right. I'm implementing a basic DDL replication solution using this
hook as a sample implementation. Other than that, this feature can be
used to add additional information for the replicated transaction that
is not replicated via logical replication protocol, such as the
executed user or context-specific information, which can then be
dispatched to a CDC system connected to the subscriber.

> BTW, can we
> also consider it as a solution implementing basic DDL replication for
> tables? The key question is what if someday we have in-core DDL
> replication. I think extensions can still be used to implement
> filtering or transformation of DDL. We can implement capture of DDL
> using JSON format [1] so that it is forward compatible with in-core
> DDL replication. So considering that, the extension handlers will look
> like:

While a common JSON format might be helpful for forward compatibility
with in-core DDL replication, I think that we need to keep the generic
logical decoding messages used by this feature distinct from the
messages that would be used for DDL replication. A generic logical
decoding message can be written via pg_logical_emit_message() SQL
function, which is granted to PUBLIC, so any user could directly emit
a DDL command in the JSON format with the 'pg_ddl' prefix and create
arbitrary tables on the subscriber, which could cause a privilege
escalation problem. I don't think we should build something as
powerful as DDL execution on top of a message channel that any user
can write to.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Wed, Jun 24, 2026 at 3:02 AM Masahiko Sawada  wrote:
> Right. I'm implementing a basic DDL replication solution using this
> hook as a sample implementation. Other than that, this feature can be
> used to add additional information for the replicated transaction that
> is not replicated via logical replication protocol, such as the
> executed user or context-specific information, which can then be
> dispatched to a CDC system connected to the subscriber.

+1 for the proposed hook, although I haven't read the patch yet.

I know of a system that uses logical decoding messages to propagate data
to external systems. In that system, the application writes the data to
be propagated as logical decoding messages, and a CDC pipeline consumes
them via logical decoding and sends them to other systems, for example
through Kafka.

In that system, when the remote site is maintained by physical replication,
the same logical decoding messages can be decoded on the standby
at the remote site to deliver them to external systems there. However,
if the remote site uses logical replication instead, those messages are
currently neither delivered to nor processed on the subscriber at
the remote site. As a result, the CDC pipeline at the remote site cannot
consume the data they carry.

The proposed hook might be useful for this use case. An extension could
process the incoming logical decoding messages on the subscriber and
forward them to the local CDC pipeline, or store or re-emit them in a form
that local consumers can process.

Regards,

-- 
Fujii Masao


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Вложения:
Hi,

On Thu, Aug 6, 2026 at 9:59 AM Masahiko Sawada  wrote:
>
> > 2/
> > + /*
> > + * The message doesn't belong to any remote transaction, so there is
> > + * no remote commit LSN nor timestamp to record. Clear the state left
> > + * over by the previously applied transaction so that this commit
> > + * doesn't inherit it.
> > + */
> > + replorigin_xact_clear(false);
> >
> > Why is this a problem if we let the non-transactional message inherit it?
>
> IIUC non-transactional messages would have the same commit timestamp
> as the previously applied transaction, which is wrong to me.

Having replorigin_xact_clear there looks fine to me. The next
transaction commit would anyway set the origin LSN and timestamp.

> > Wrapping the hook with begin and end replication step is nice. This
> > lets the hook see the correct command ID, snapshot, and memory
> > context. There are callers that do the begin first and read message
> > next (insert), but it seems okay this way because read message doesn't
> > do any catalog or table accesses, so it should be fine.
> >
>
> begin_replication_step() switches the memory context to
> ApplyMessageContext. Given logicalrep_read_message() palloc's for
> messages, it should be called after begin_replication_step(). Fixed it.

Right. I verified other places and wherever the read does a palloc, it
is wrapped within begin and end replication step.

> I've attached the updated patch.

Thanks. The v4 patch looks good to me. pgindent and tests are happy. I
have no further comments. I marked the CF entry RfC
(https://commitfest.postgresql.org/patch/7092/). FWIW, the CF bot
complains with "needs rebase":
https://cfbot.cputube.org/patch_7092.log.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Thu, Aug 6, 2026 at 10:42 AM Bharath Rupireddy
 wrote:
>
> Hi,
>
> On Thu, Aug 6, 2026 at 9:59 AM Masahiko Sawada  wrote:
> >
> > > 2/
> > > + /*
> > > + * The message doesn't belong to any remote transaction, so there is
> > > + * no remote commit LSN nor timestamp to record. Clear the state left
> > > + * over by the previously applied transaction so that this commit
> > > + * doesn't inherit it.
> > > + */
> > > + replorigin_xact_clear(false);
> > >
> > > Why is this a problem if we let the non-transactional message inherit it?
> >
> > IIUC non-transactional messages would have the same commit timestamp
> > as the previously applied transaction, which is wrong to me.
>
> Having replorigin_xact_clear there looks fine to me. The next
> transaction commit would anyway set the origin LSN and timestamp.
>
> > > Wrapping the hook with begin and end replication step is nice. This
> > > lets the hook see the correct command ID, snapshot, and memory
> > > context. There are callers that do the begin first and read message
> > > next (insert), but it seems okay this way because read message doesn't
> > > do any catalog or table accesses, so it should be fine.
> > >
> >
> > begin_replication_step() switches the memory context to
> > ApplyMessageContext. Given logicalrep_read_message() palloc's for
> > messages, it should be called after begin_replication_step(). Fixed it.
>
> Right. I verified other places and wherever the read does a palloc, it
> is wrapped within begin and end replication step.
>
> > I've attached the updated patch.
>
> Thanks. The v4 patch looks good to me. pgindent and tests are happy. I
> have no further comments. I marked the CF entry RfC
> (https://commitfest.postgresql.org/patch/7092/). FWIW, the CF bot
> complains with "needs rebase":
> https://cfbot.cputube.org/patch_7092.log.

Thanks for reviewing the patch!

While I also think the patch is in good shape, I'd like to raise a
security risk this feature might introduce, particularly around
pg_logical_emit_message():

EXECUTE on that function is granted to PUBLIC, so any role that can
connect to the publisher database can emit a logical decoding message.
With this patch the apply worker hands the message to a handler that
runs with the privileges of the subscription owner, and unlike
insert/update/delete there is no table owner to switch to. One use
case I have in mind is DDL replication. If an extension implements it
on top of this hook and the subscription is owned by a superuser, any
role on the publisher can choose what the handler is given and have it
executed with superuser privileges on the subscriber. So extensions
should carefully consider this case. I think the same applies to other
extensions that might use this feature. The real problem is that there
is no reliable way for the subscriber to tell whether a message came
from the source it expects.

A practical solution is to revoke EXECUTE on pg_logical_emit_message()
from PUBLIC on the publisher and grant it to a role created for that
purpose. I think that covers most cases I did consider having the
server record the emitting role in the message so that the subscriber
could check it, but I'm not sure this feature alone justifies it. So
my current thought is to document these risks and add nothing special
for these cases.

I've added the documentation changes and rebased the patch. Any ideas
and feedback is very welcome.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Вложения:
Hi,

On Thu, Sep 17, 2026 at 5:43 PM Masahiko Sawada  wrote:
>
> Thanks for reviewing the patch!
>
> While I also think the patch is in good shape, I'd like to raise a
> security risk this feature might introduce, particularly around
> pg_logical_emit_message():

Nice catch. Thanks for bringing it up.

> EXECUTE on that function is granted to PUBLIC, so any role that can
> connect to the publisher database can emit a logical decoding message.
> With this patch the apply worker hands the message to a handler that
> runs with the privileges of the subscription owner, and unlike
> insert/update/delete there is no table owner to switch to. One use
> case I have in mind is DDL replication. If an extension implements it
> on top of this hook and the subscription is owned by a superuser, any
> role on the publisher can choose what the handler is given and have it
> executed with superuser privileges on the subscriber. So extensions
> should carefully consider this case. I think the same applies to other
> extensions that might use this feature. The real problem is that there
> is no reliable way for the subscriber to tell whether a message came
> from the source it expects.

Right. This lets a less privileged user on the publisher get more
privileged things done on the subscriber.

> A practical solution is to revoke EXECUTE on pg_logical_emit_message()
> from PUBLIC on the publisher and grant it to a role created for that
> purpose.

That seems like a good approach. Since the message emitted by
pg_logical_emit_message() can carry anything the user wants and goes
into the WAL stream, careful production systems may already restrict
the function this way. But we can't assume that is always the case.

> I think that covers most cases I did consider having the
> server record the emitting role in the message so that the subscriber
> could check it, but I'm not sure this feature alone justifies it.

I lean towards this idea, with one change. Record what the emitter can
do, not who it is. Role names and OIDs of ordinary roles on the
publisher mean nothing on the subscriber. What the apply side wants to
know is simple. What privileges did the emitter have, with role
memberships expanded recursively, so they can be compared against what
the role applying the message has. So record the emitter's role
attributes and the predefined roles it had the privileges of, and hand
that to the hook as-is. With this, a hook implementer can say "the
emitter was less privileged than me, so I'll skip this logical
message", or apply a stricter rule per message type. It also answers
the real problem mentioned above, since the subscriber can now tell
whether the logical message came from a source it trusts. I can also
think of another place where this helps. The logical message today is
replayed as-is during crash recovery, on read replicas, and in setups
where replay is moved to storage away from compute.

I quickly played with this idea using Claude Code to illustrate it
better. I haven't reviewed it in depth. Attached for reference. Please
have a look.

That said, I don't want the hook addition to be blocked on this. It
can be discussed separately since there can be other valid use cases.

> So
> my current thought is to document these risks and add nothing special
> for these cases.

Documenting the risks is good enough to proceed for now IMHO. But hook
implementers can easily miss it.

I'm also just thinking out loud here. How about a predefined role for
pg_logical_emit_message()? The apply side could switch to that role
before calling the hook, which gives logical messages the same kind of
switch that apply gets with the table owner, and limits what any
logical message can do to whatever that role is granted on the
subscriber. Or the apply side could call the hook only when the
subscription owner has been granted that role, so the hook stays off
unless someone chose to give the subscription owner that role.

> I've added the documentation changes and rebased the patch. Any ideas
> and feedback is very welcome.

I reviewed the v5 patch and the diff from the v4 patch and it looks good to me.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Fri, Sep 18, 2026 at 6:13 AM Masahiko Sawada  wrote:
>
> Thanks for reviewing the patch!
>
> While I also think the patch is in good shape, I'd like to raise a
> security risk this feature might introduce, particularly around
> pg_logical_emit_message():
>

Review comments:
===============
1. Typo (/logcal/logical): pg_logcal_emit_message().

2.
+ * The handler always runs with the privileges of the subscription owner.
+ * The payload is chosen by whoever called pg_logical_emit_message() on the
+ * publisher, which by default any role may do, so a handler that acts on the
+ * payload gives every role on the publisher the subscription owner's
+ * privileges. A handler that needs less than that can lower them itself
+ * with SwitchToUntrustedUser().

One thing to consider about this is advice is that unlike DML there's
no target role to derive, and SwitchToUntrustedUser() errors outright
if the subscription owner can't SET ROLE to whatever the handler
picks. So, it doesn't sound straight-forward to follow this advice.

3.
Restrict who can emit messages
+   on the publisher. Revoke the default privilege and grant it to a
role created
+   for this purpose:
+
+REVOKE EXECUTE ON FUNCTION pg_logical_emit_message(boolean, text,
text, boolean) FROM PUBLIC;
+REVOKE EXECUTE ON FUNCTION pg_logical_emit_message(boolean, text,
bytea, boolean) FROM PUBLIC;
+GRANT EXECUTE ON FUNCTION pg_logical_emit_message(boolean, text,
text, boolean) TO message_emitter;
+GRANT EXECUTE ON FUNCTION pg_logical_emit_message(boolean, text,
bytea, boolean) TO message_emitter;
+

That above security recipe sounds reasonable, but it asks the
subscriber's security to be enforced by an action in a cluster the
subscriber admin frequently does not control. The Security section
should say something on the lines of: if you don't administer both the
subscriber and publisher, don't install a message handler that does
anything you wouldn't let every publisher role do. Also, I think the
above REVOKE has to be performed in all databases separately.

4. Based on above two points, I think we can fill the hole with something like:

CREATE SUBSCRIPTION ... WITH (messages = true, message_handler_role =
'msg_handler')

and then run the hook under SwitchToUntrustedUser(that_role). That
gives the subscriber admin a local, explicit privilege mechanism that
does not depend on the publisher's ACLs, doesn't touch WAL or the
protocol, and reuses machinery already in usercontext.c. If the option
is unset, either don't call the hook or keep today's behavior with the
documented warning.

-- 
With Regards,
Amit Kapila.


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Mon, Sep 21, 2026 at 11:53 AM Amit Kapila  wrote:
>
> On Fri, Sep 18, 2026 at 6:13 AM Masahiko Sawada  wrote:
> >
> > Thanks for reviewing the patch!
> >
> > While I also think the patch is in good shape, I'd like to raise a
> > security risk this feature might introduce, particularly around
> > pg_logical_emit_message():
> >
>
> Review comments:
> ===============
>

One more comment:
+static void
+apply_handle_message(StringInfo s)
+{
+ LogicalRepMessageData msg;
+
+ /* Tablesync worker should never receive MESSAGE */
+ if (am_tablesync_worker())
+ ereport(ERROR,
+ errcode(ERRCODE_PROTOCOL_VIOLATION),
+ errmsg_internal("tablesync worker received a MESSAGE message"));

I think we should have a similar ERROR for parallel apply worker. I
don't think this message can reach there but we should protect it like
above.

-- 
With Regards,
Amit Kapila.


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi,

On Sun, Sep 20, 2026 at 11:24 PM Amit Kapila  wrote:
>
> 3.
> Restrict who can emit messages
> +   on the publisher. Revoke the default privilege and grant it to a
> role created
>
> That above security recipe sounds reasonable, but it asks the
> subscriber's security to be enforced by an action in a cluster the
> subscriber admin frequently does not control. The Security section
> should say something on the lines of: if you don't administer both the
> subscriber and publisher, don't install a message handler that does
> anything you wouldn't let every publisher role do. Also, I think the
> above REVOKE has to be performed in all databases separately.
>
> 4. Based on above two points, I think we can fill the hole with something like:
>
> CREATE SUBSCRIPTION ... WITH (messages = true, message_handler_role =
> 'msg_handler')
>
> and then run the hook under SwitchToUntrustedUser(that_role). That
> gives the subscriber admin a local, explicit privilege mechanism that
> does not depend on the publisher's ACLs, doesn't touch WAL or the
> protocol, and reuses machinery already in usercontext.c. If the option
> is unset, either don't call the hook or keep today's behavior with the
> documented warning.

I like this idea more than all the other approaches. The user
installing the hook would have to make a conscious choice, and even if
the role applying the message is more privileged than the emitter on
the publisher, that is the user's choice. Also, I don't think
defaulting the message handler role to the subscription owner (which
can lead to the same security concern) or not calling the hook
silently (which can lead to silent data loss) are good defaults. So, I
think requiring the handler role to be specified by the user is a good
choice, in my opinion.

That said, not having a default role would make the ALTER SUBSCRIPTION
code for this option a bit more complex I guess (I haven't checked it
in depth though).

On Sun, Sep 20, 2026 at 11:54 PM Amit Kapila  wrote:
>
> One more comment:
> +static void
> +apply_handle_message(StringInfo s)
> +{
> + LogicalRepMessageData msg;
> +
> + /* Tablesync worker should never receive MESSAGE */
> + if (am_tablesync_worker())
> + ereport(ERROR,
> + errcode(ERRCODE_PROTOCOL_VIOLATION),
> + errmsg_internal("tablesync worker received a MESSAGE message"));
>
> I think we should have a similar ERROR for parallel apply worker. I
> don't think this message can reach there but we should protect it like
> above.

Also, error out for the sequence sync worker?

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Sun, Sep 20, 2026 at 11:24 PM Amit Kapila  wrote:
>
> On Fri, Sep 18, 2026 at 6:13 AM Masahiko Sawada  wrote:
> >
> > Thanks for reviewing the patch!
> >
> > While I also think the patch is in good shape, I'd like to raise a
> > security risk this feature might introduce, particularly around
> > pg_logical_emit_message():
> >
>
> Review comments:
> ===============
> 1. Typo (/logcal/logical): pg_logcal_emit_message().

Fixed.

>
> 2.
> + * The handler always runs with the privileges of the subscription owner.
> + * The payload is chosen by whoever called pg_logical_emit_message() on the
> + * publisher, which by default any role may do, so a handler that acts on the
> + * payload gives every role on the publisher the subscription owner's
> + * privileges. A handler that needs less than that can lower them itself
> + * with SwitchToUntrustedUser().
>
> One thing to consider about this is advice is that unlike DML there's
> no target role to derive, and SwitchToUntrustedUser() errors outright
> if the subscription owner can't SET ROLE to whatever the handler
> picks. So, it doesn't sound straight-forward to follow this advice.

Right, but I think the error isn't specific to the hoo. When the apply
worker applies a change, it also switches to the table owner, and
errors could happen if the subscription owner cannot SET ROLE to the
table owner. I think it would be an extension's responsibility that
the apply worker switch to a role, whereas it's a extension user's
responsibility that the subscription owner can SET ROLE to that role.

>
> 3.
> Restrict who can emit messages
> +   on the publisher. Revoke the default privilege and grant it to a
> role created
> +   for this purpose:
> +
> +REVOKE EXECUTE ON FUNCTION pg_logical_emit_message(boolean, text,
> text, boolean) FROM PUBLIC;
> +REVOKE EXECUTE ON FUNCTION pg_logical_emit_message(boolean, text,
> bytea, boolean) FROM PUBLIC;
> +GRANT EXECUTE ON FUNCTION pg_logical_emit_message(boolean, text,
> text, boolean) TO message_emitter;
> +GRANT EXECUTE ON FUNCTION pg_logical_emit_message(boolean, text,
> bytea, boolean) TO message_emitter;
> +
>
> That above security recipe sounds reasonable, but it asks the
> subscriber's security to be enforced by an action in a cluster the
> subscriber admin frequently does not control. The Security section
> should say something on the lines of: if you don't administer both the
> subscriber and publisher, don't install a message handler that does
> anything you wouldn't let every publisher role do. Also, I think the
> above REVOKE has to be performed in all databases separately.

Agreed on both, I'll add that.

>
> 4. Based on above two points, I think we can fill the hole with something like:
>
> CREATE SUBSCRIPTION ... WITH (messages = true, message_handler_role =
> 'msg_handler')
>
> and then run the hook under SwitchToUntrustedUser(that_role). That
> gives the subscriber admin a local, explicit privilege mechanism that
> does not depend on the publisher's ACLs, doesn't touch WAL or the
> protocol, and reuses machinery already in usercontext.c. If the option
> is unset, either don't call the hook or keep today's behavior with the
> documented warning.

I think it works for the cases where the handler doesn't or forget to
switch the role when applying the message. But I think the handler
would have to switch the role to the target role that is suitable for
doing its job in most cases. So I think the option gives us two SET
ROLE chains instead of one. Today the subscription owner needs to be
able to SET ROLE to each target role, which is the same requirement we
already document for table owners. With message_handler_role the owner
needs SET ROLE to the handler role, and the handler role needs SET
ROLE to every target role. That's noe more role and one more place for
the DBA to get it wrong, and either mistake shows up as an apply
error.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Sep 21, 2026 at 9:20 AM Bharath Rupireddy
 wrote:
>
> Hi,
>
> On Sun, Sep 20, 2026 at 11:24 PM Amit Kapila  wrote:
> >
> > 3.
> > Restrict who can emit messages
> > +   on the publisher. Revoke the default privilege and grant it to a
> > role created
> >
> > That above security recipe sounds reasonable, but it asks the
> > subscriber's security to be enforced by an action in a cluster the
> > subscriber admin frequently does not control. The Security section
> > should say something on the lines of: if you don't administer both the
> > subscriber and publisher, don't install a message handler that does
> > anything you wouldn't let every publisher role do. Also, I think the
> > above REVOKE has to be performed in all databases separately.
> >
> > 4. Based on above two points, I think we can fill the hole with something like:
> >
> > CREATE SUBSCRIPTION ... WITH (messages = true, message_handler_role =
> > 'msg_handler')
> >
> > and then run the hook under SwitchToUntrustedUser(that_role). That
> > gives the subscriber admin a local, explicit privilege mechanism that
> > does not depend on the publisher's ACLs, doesn't touch WAL or the
> > protocol, and reuses machinery already in usercontext.c. If the option
> > is unset, either don't call the hook or keep today's behavior with the
> > documented warning.
>
> I like this idea more than all the other approaches. The user
> installing the hook would have to make a conscious choice, and even if
> the role applying the message is more privileged than the emitter on
> the publisher, that is the user's choice. Also, I don't think
> defaulting the message handler role to the subscription owner (which
> can lead to the same security concern) or not calling the hook
> silently (which can lead to silent data loss) are good defaults. So, I
> think requiring the handler role to be specified by the user is a good
> choice, in my opinion.
>
> That said, not having a default role would make the ALTER SUBSCRIPTION
> code for this option a bit more complex I guess (I haven't checked it
> in depth though).

 My concern is that since the handler is a C function, this doesn't
help much as a security boundary. The handler can get back to the
subscription owner by calling SetUserIdAndSecContext() with
MySubscription->owner or even switch to the superuser. That function
does no permission check, and since the security context is its second
argument, the same call clears SECURITY_RESTRICTED_OPERATION as well.
As I mentioned in the reply to Amit, the option would help in cases
where the handler doesn't switch to the target role, or forgets to,
and keeps working as the subscription owner unexpectedly. But I'm not
sure we need this option just for that case.

>
> On Sun, Sep 20, 2026 at 11:54 PM Amit Kapila  wrote:
> >
> > One more comment:
> > +static void
> > +apply_handle_message(StringInfo s)
> > +{
> > + LogicalRepMessageData msg;
> > +
> > + /* Tablesync worker should never receive MESSAGE */
> > + if (am_tablesync_worker())
> > + ereport(ERROR,
> > + errcode(ERRCODE_PROTOCOL_VIOLATION),
> > + errmsg_internal("tablesync worker received a MESSAGE message"));
> >
> > I think we should have a similar ERROR for parallel apply worker. I
> > don't think this message can reach there but we should protect it like
> > above.
>
> Also, error out for the sequence sync worker?

I agree to add a check for parallel apply workers, but I don't think
we need it for the sequence sync workers as they neither enter the
apply loop nor receive logical replication changes in the first place.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
Hi,

On Fri, Oct 16, 2026 at 2:45 PM Masahiko Sawada  wrote:
>
> > > 4. Based on above two points, I think we can fill the hole with something like:
>
> > > CREATE SUBSCRIPTION ... WITH (messages = true, message_handler_role =
> > > 'msg_handler')
>
> > > and then run the hook under SwitchToUntrustedUser(that_role). That
>
> > I like this idea more than all the other approaches.
>
>  My concern is that since the handler is a C function, this doesn't
> help much as a security boundary. The handler can get back to the
> subscription owner by calling SetUserIdAndSecContext() with
> MySubscription->owner or even switch to the superuser. That function
> does no permission check, and since the security context is its second
> argument, the same call clears SECURITY_RESTRICTED_OPERATION as well.
> As I mentioned in the reply to Amit, the option would help in cases
> where the handler doesn't switch to the target role, or forgets to,
> and keeps working as the subscription owner unexpectedly. But I'm not
> sure we need this option just for that case.

Agreed. In a way, we already trust every hook as far as switching to
whatever role with SetUserIdAndSecContext() is concerned. So
documenting the risk clearly here works for me.

> > > I think we should have a similar ERROR for parallel apply worker.
>
> > Also, error out for the sequence sync worker?
>
> I agree to add a check for parallel apply workers, but I don't think
> we need it for the sequence sync workers as they neither enter the
> apply loop nor receive logical replication changes in the first place.

Right, we don't need to error out for seq sync workers. However, do we
need to error out for the table sync worker, since we don't expect a
logical message there?

+ /*
+ * Logical messages are relation-agnostic, so they don't map cleanly onto
+ * the tablesync worker of a particular relation, and there would be no
+ * well-defined ordering between a message and the initial copy. Leave
+ * them to the (parallel) apply workers.
+ */

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Fri, Oct 16, 2026 at 3:16 PM Bharath Rupireddy
 wrote:
>
> Hi,
>
> On Fri, Oct 16, 2026 at 2:45 PM Masahiko Sawada  wrote:
> >
> > > > 4. Based on above two points, I think we can fill the hole with something like:
> >
> > > > CREATE SUBSCRIPTION ... WITH (messages = true, message_handler_role =
> > > > 'msg_handler')
> >
> > > > and then run the hook under SwitchToUntrustedUser(that_role). That
> >
> > > I like this idea more than all the other approaches.
> >
> >  My concern is that since the handler is a C function, this doesn't
> > help much as a security boundary. The handler can get back to the
> > subscription owner by calling SetUserIdAndSecContext() with
> > MySubscription->owner or even switch to the superuser. That function
> > does no permission check, and since the security context is its second
> > argument, the same call clears SECURITY_RESTRICTED_OPERATION as well.
> > As I mentioned in the reply to Amit, the option would help in cases
> > where the handler doesn't switch to the target role, or forgets to,
> > and keeps working as the subscription owner unexpectedly. But I'm not
> > sure we need this option just for that case.
>
> Agreed. In a way, we already trust every hook as far as switching to
> whatever role with SetUserIdAndSecContext() is concerned. So
> documenting the risk clearly here works for me.
>
> > > > I think we should have a similar ERROR for parallel apply worker.
> >
> > > Also, error out for the sequence sync worker?
> >
> > I agree to add a check for parallel apply workers, but I don't think
> > we need it for the sequence sync workers as they neither enter the
> > apply loop nor receive logical replication changes in the first place.
>
> Right, we don't need to error out for seq sync workers. However, do we
> need to error out for the table sync worker, since we don't expect a
> logical message there?

It seems to me worth adding a check for tablesync workers since both
the apply workers and the tablesync workers call
walrcv_startstreaming() and it would prevent mistakes by future
changes.

I've attached the updated patch.

Regards,


--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Вложения:
Hi,

On Sat, Oct 31, 2026 at 06:34 AM Masahiko Sawada wrote:
>
> It seems to me worth adding a check for tablesync workers since both
> the apply workers and the tablesync workers call
> walrcv_startstreaming() and it would prevent mistakes by future
> changes.
> 
> I've attached the updated patch.

While reviewing how transactional logical messages interact with 
subtransaction aborts, I noticed an issue with streamed transactions. In 
non-streaming mode, it works as expected (i.e., the message is not 
applied if the subtransaction is aborted). However, in streaming mode, 
if a transactional message is emitted in a subtransaction that is later 
aborted, the STREAM ABORT message does not discard or roll back that 
logical message, so it still gets applied in both streaming=on and 
streaming=parallel modes.

I think the reason is that ReorderBufferApplyMessage() passes the 
top-level txn rather than change->txn to rb->stream_message(), so 
logical decoding always sends the top-level XID instead of the 
subtransaction XID when outputting a streamed message. Thus the apply 
worker cannot associate the message with the subtransaction and cannot 
roll it back properly.

Strictly speaking, this is an existing issue, but it becomes more 
visible once subscribers can handle logical messages via this hook. So 
it may be worth considering whether to fix it along with this patch or 
separately.

Attached 0002 adds a test diff in 001_basic.pl to show the issue when 
streaming a message in an aborted subtransaction. 0001 is a draft patch 
showing that passing the subtransaction of the message when streaming 
allows the message to be rolled back properly (we may not necessarily 
fix it in this exact style, just sharing it to show the behavior change).


-- 
Best Regards,
Zhijie Hou

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Sat, Oct 31, 2026 at 6:05 PM Zhijie Hou  wrote:
>
> On Sat, Oct 31, 2026 at 06:34 AM Masahiko Sawada wrote:
> >
> > It seems to me worth adding a check for tablesync workers since both
> > the apply workers and the tablesync workers call
> > walrcv_startstreaming() and it would prevent mistakes by future
> > changes.
> >
> > I've attached the updated patch.
>
> While reviewing how transactional logical messages interact with
> subtransaction aborts, I noticed an issue with streamed transactions. In
> non-streaming mode, it works as expected (i.e., the message is not
> applied if the subtransaction is aborted). However, in streaming mode,
> if a transactional message is emitted in a subtransaction that is later
> aborted, the STREAM ABORT message does not discard or roll back that
> logical message, so it still gets applied in both streaming=on and
> streaming=parallel modes.
>
> I think the reason is that ReorderBufferApplyMessage() passes the
> top-level txn rather than change->txn to rb->stream_message(), so
> logical decoding always sends the top-level XID instead of the
> subtransaction XID when outputting a streamed message. Thus the apply
> worker cannot associate the message with the subtransaction and cannot
> roll it back properly.
>
> Strictly speaking, this is an existing issue, but it becomes more
> visible once subscribers can handle logical messages via this hook. So
> it may be worth considering whether to fix it along with this patch or
> separately.
>

Right, it didn't have any impact till now for native replication as we
were just ignoring these messages on subscribers. I think this could
have impacted output-plugins if they used this functionality. I think
we can fix this separately but it is better to fix it before this
patch as this patch can expose a hidden issue.

-- 
With Regards,
Amit Kapila.


Re: Add a hook for handling logical decoding messages on subscribers.

От:
torikoshia <torikoshia@oss.nttdata.com>
Дата:
On 2026-10-31 07:34, Masahiko Sawada wrote:
> On Fri, Oct 16, 2026 at 3:16 PM Bharath Rupireddy
>  wrote:
>> 
>> Hi,
>> 
>> On Fri, Oct 16, 2026 at 2:45 PM Masahiko Sawada 
>>  wrote:
>> >
>> > > > 4. Based on above two points, I think we can fill the hole with something like:
>> >
>> > > > CREATE SUBSCRIPTION ... WITH (messages = true, message_handler_role =
>> > > > 'msg_handler')
>> >
>> > > > and then run the hook under SwitchToUntrustedUser(that_role). That
>> >
>> > > I like this idea more than all the other approaches.
>> >
>> >  My concern is that since the handler is a C function, this doesn't
>> > help much as a security boundary. The handler can get back to the
>> > subscription owner by calling SetUserIdAndSecContext() with
>> > MySubscription->owner or even switch to the superuser. That function
>> > does no permission check, and since the security context is its second
>> > argument, the same call clears SECURITY_RESTRICTED_OPERATION as well.
>> > As I mentioned in the reply to Amit, the option would help in cases
>> > where the handler doesn't switch to the target role, or forgets to,
>> > and keeps working as the subscription owner unexpectedly. But I'm not
>> > sure we need this option just for that case.
>> 
>> Agreed. In a way, we already trust every hook as far as switching to
>> whatever role with SetUserIdAndSecContext() is concerned. So
>> documenting the risk clearly here works for me.
>> 
>> > > > I think we should have a similar ERROR for parallel apply worker.
>> >
>> > > Also, error out for the sequence sync worker?
>> >
>> > I agree to add a check for parallel apply workers, but I don't think
>> > we need it for the sequence sync workers as they neither enter the
>> > apply loop nor receive logical replication changes in the first place.
>> 
>> Right, we don't need to error out for seq sync workers. However, do we
>> need to error out for the table sync worker, since we don't expect a
>> logical message there?
> 
> It seems to me worth adding a check for tablesync workers since both
> the apply workers and the tablesync workers call
> walrcv_startstreaming() and it would prevent mistakes by future
> changes.
> 
> I've attached the updated patch.

Thanks for the proposal and patch!

As a precaution, I checked whether this patch could cause data loss
similar to the issue I previously reported with Debezium [1], where
logical messages report their end LSN while ordinary changes report
their start LSN.

Based on my code review and some tests, I haven't found a similar
issue with this patch.

The issue occurred with transactional messages.
Debezium tracks processing progress at the event level, including
individual DML operations and logical messages. In PostgreSQL's
built-in logical replication, however, the handler's changes are
committed as part of the replicated transaction, and replication
progress is tracked at the transaction boundary. Therefore, the
difference between start and end LSNs does not appear to cause
the same problem.

I also wondered whether there could be a timing window in which
consecutive non-transactional logical messages might lead to data
loss, so I checked this case as well. It seems that the following
condition in logicalmsg_decode() handles this case correctly,
so I don't see a problem here either.

   else if (!message->transactional &&
          (SnapBuildCurrentState(builder) != SNAPBUILD_CONSISTENT ||
           SnapBuildXactNeedsSkip(builder, buf->origptr)))
     return;


[1] 
https://www.postgresql.org/message-id/d99c688994ab3a998afe26e61fe4f69f%40oss.nttdata.com


-- 
Thanks,

--
Atsushi Torikoshi
Seconded from NTT DATA CORPORATION to SRA OSS K.K.


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Nov 2, 2026 at 4:47 AM Amit Kapila  wrote:
>
> On Sat, Oct 31, 2026 at 6:05 PM Zhijie Hou  wrote:
> >
> > On Sat, Oct 31, 2026 at 06:34 AM Masahiko Sawada wrote:
> > >
> > > It seems to me worth adding a check for tablesync workers since both
> > > the apply workers and the tablesync workers call
> > > walrcv_startstreaming() and it would prevent mistakes by future
> > > changes.
> > >
> > > I've attached the updated patch.
> >
> > While reviewing how transactional logical messages interact with
> > subtransaction aborts, I noticed an issue with streamed transactions. In
> > non-streaming mode, it works as expected (i.e., the message is not
> > applied if the subtransaction is aborted). However, in streaming mode,
> > if a transactional message is emitted in a subtransaction that is later
> > aborted, the STREAM ABORT message does not discard or roll back that
> > logical message, so it still gets applied in both streaming=on and
> > streaming=parallel modes.
> >
> > I think the reason is that ReorderBufferApplyMessage() passes the
> > top-level txn rather than change->txn to rb->stream_message(), so
> > logical decoding always sends the top-level XID instead of the
> > subtransaction XID when outputting a streamed message. Thus the apply
> > worker cannot associate the message with the subtransaction and cannot
> > roll it back properly.
> >
> > Strictly speaking, this is an existing issue, but it becomes more
> > visible once subscribers can handle logical messages via this hook. So
> > it may be worth considering whether to fix it along with this patch or
> > separately.
> >
>
> Right, it didn't have any impact till now for native replication as we
> were just ignoring these messages on subscribers. I think this could
> have impacted output-plugins if they used this functionality. I think
> we can fix this separately but it is better to fix it before this
> patch as this patch can expose a hidden issue.

Agreed that we should fix it before this patch.

The Hou's patch looks good. I prefer to apply it to only master as
external output plugin might require changes similar to what the patch
does for test_decoding.

And thank you for the 0002 patch. I'll include it in the next version patch.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Nov 2, 2026 at 7:06 AM torikoshia  wrote:
>
> On 2026-10-31 07:34, Masahiko Sawada wrote:
> > On Fri, Oct 16, 2026 at 3:16 PM Bharath Rupireddy
> >  wrote:
> >>
> >> Hi,
> >>
> >> On Fri, Oct 16, 2026 at 2:45 PM Masahiko Sawada
> >>  wrote:
> >> >
> >> > > > 4. Based on above two points, I think we can fill the hole with something like:
> >> >
> >> > > > CREATE SUBSCRIPTION ... WITH (messages = true, message_handler_role =
> >> > > > 'msg_handler')
> >> >
> >> > > > and then run the hook under SwitchToUntrustedUser(that_role). That
> >> >
> >> > > I like this idea more than all the other approaches.
> >> >
> >> >  My concern is that since the handler is a C function, this doesn't
> >> > help much as a security boundary. The handler can get back to the
> >> > subscription owner by calling SetUserIdAndSecContext() with
> >> > MySubscription->owner or even switch to the superuser. That function
> >> > does no permission check, and since the security context is its second
> >> > argument, the same call clears SECURITY_RESTRICTED_OPERATION as well.
> >> > As I mentioned in the reply to Amit, the option would help in cases
> >> > where the handler doesn't switch to the target role, or forgets to,
> >> > and keeps working as the subscription owner unexpectedly. But I'm not
> >> > sure we need this option just for that case.
> >>
> >> Agreed. In a way, we already trust every hook as far as switching to
> >> whatever role with SetUserIdAndSecContext() is concerned. So
> >> documenting the risk clearly here works for me.
> >>
> >> > > > I think we should have a similar ERROR for parallel apply worker.
> >> >
> >> > > Also, error out for the sequence sync worker?
> >> >
> >> > I agree to add a check for parallel apply workers, but I don't think
> >> > we need it for the sequence sync workers as they neither enter the
> >> > apply loop nor receive logical replication changes in the first place.
> >>
> >> Right, we don't need to error out for seq sync workers. However, do we
> >> need to error out for the table sync worker, since we don't expect a
> >> logical message there?
> >
> > It seems to me worth adding a check for tablesync workers since both
> > the apply workers and the tablesync workers call
> > walrcv_startstreaming() and it would prevent mistakes by future
> > changes.
> >
> > I've attached the updated patch.
>
> Thanks for the proposal and patch!
>
> As a precaution, I checked whether this patch could cause data loss
> similar to the issue I previously reported with Debezium [1], where
> logical messages report their end LSN while ordinary changes report
> their start LSN.
>
> Based on my code review and some tests, I haven't found a similar
> issue with this patch.
>
> The issue occurred with transactional messages.
> Debezium tracks processing progress at the event level, including
> individual DML operations and logical messages. In PostgreSQL's
> built-in logical replication, however, the handler's changes are
> committed as part of the replicated transaction, and replication
> progress is tracked at the transaction boundary. Therefore, the
> difference between start and end LSNs does not appear to cause
> the same problem.
>
> I also wondered whether there could be a timing window in which
> consecutive non-transactional logical messages might lead to data
> loss, so I checked this case as well. It seems that the following
> condition in logicalmsg_decode() handles this case correctly,
> so I don't see a problem here either.
>
>    else if (!message->transactional &&
>           (SnapBuildCurrentState(builder) != SNAPBUILD_CONSISTENT ||
>            SnapBuildXactNeedsSkip(builder, buf->origptr)))
>      return;

Thank you for reviewing and testing the patch!

For a non-transactional message, the apply worker commits the
handler's work as its own transaction and uses the message LSN as the
flush position. So this patch does rely on the message reporting its
end LSN in that case. If it reported the start LSN instead, the
publisher's confirmed_flush would point at the message record itself,
and the message would be decoded and sent again after a restart even
though the subscriber already committed it and sent an ack.

So I think using origptr for transactional messages and endptr for
non-transactional ones, as we discussed in that thread, is the right
thing for this patch too. I'll reply there.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Mon, Nov 9, 2026 at 11:02 AM Masahiko Sawada  wrote:
>
> On Mon, Nov 2, 2026 at 4:47 AM Amit Kapila  wrote:
> >
> > On Sat, Oct 31, 2026 at 6:05 PM Zhijie Hou  wrote:
> > >
> > > On Sat, Oct 31, 2026 at 06:34 AM Masahiko Sawada wrote:
> > > >
> > > > It seems to me worth adding a check for tablesync workers since both
> > > > the apply workers and the tablesync workers call
> > > > walrcv_startstreaming() and it would prevent mistakes by future
> > > > changes.
> > > >
> > > > I've attached the updated patch.
> > >
> > > While reviewing how transactional logical messages interact with
> > > subtransaction aborts, I noticed an issue with streamed transactions. In
> > > non-streaming mode, it works as expected (i.e., the message is not
> > > applied if the subtransaction is aborted). However, in streaming mode,
> > > if a transactional message is emitted in a subtransaction that is later
> > > aborted, the STREAM ABORT message does not discard or roll back that
> > > logical message, so it still gets applied in both streaming=on and
> > > streaming=parallel modes.
> > >
> > > I think the reason is that ReorderBufferApplyMessage() passes the
> > > top-level txn rather than change->txn to rb->stream_message(), so
> > > logical decoding always sends the top-level XID instead of the
> > > subtransaction XID when outputting a streamed message. Thus the apply
> > > worker cannot associate the message with the subtransaction and cannot
> > > roll it back properly.
> > >
> > > Strictly speaking, this is an existing issue, but it becomes more
> > > visible once subscribers can handle logical messages via this hook. So
> > > it may be worth considering whether to fix it along with this patch or
> > > separately.
> > >
> >
> > Right, it didn't have any impact till now for native replication as we
> > were just ignoring these messages on subscribers. I think this could
> > have impacted output-plugins if they used this functionality. I think
> > we can fix this separately but it is better to fix it before this
> > patch as this patch can expose a hidden issue.
>
> Agreed that we should fix it before this patch.
>
> The Hou's patch looks good. I prefer to apply it to only master as
> external output plugin might require changes similar to what the patch
> does for test_decoding.
>
> And thank you for the 0002 patch. I'll include it in the next version patch.

I've attached the new patches. I just updated the commit message for
the 0001 patch, and added some fixes and regression tests for the 0002
patch. Please review them.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Nov 9, 2026 at 5:21 PM Masahiko Sawada  wrote:
>
> On Mon, Nov 9, 2026 at 11:02 AM Masahiko Sawada  wrote:
> >
> > On Mon, Nov 2, 2026 at 4:47 AM Amit Kapila  wrote:
> > >
> > > On Sat, Oct 31, 2026 at 6:05 PM Zhijie Hou  wrote:
> > > >
> > > > On Sat, Oct 31, 2026 at 06:34 AM Masahiko Sawada wrote:
> > > > >
> > > > > It seems to me worth adding a check for tablesync workers since both
> > > > > the apply workers and the tablesync workers call
> > > > > walrcv_startstreaming() and it would prevent mistakes by future
> > > > > changes.
> > > > >
> > > > > I've attached the updated patch.
> > > >
> > > > While reviewing how transactional logical messages interact with
> > > > subtransaction aborts, I noticed an issue with streamed transactions. In
> > > > non-streaming mode, it works as expected (i.e., the message is not
> > > > applied if the subtransaction is aborted). However, in streaming mode,
> > > > if a transactional message is emitted in a subtransaction that is later
> > > > aborted, the STREAM ABORT message does not discard or roll back that
> > > > logical message, so it still gets applied in both streaming=on and
> > > > streaming=parallel modes.
> > > >
> > > > I think the reason is that ReorderBufferApplyMessage() passes the
> > > > top-level txn rather than change->txn to rb->stream_message(), so
> > > > logical decoding always sends the top-level XID instead of the
> > > > subtransaction XID when outputting a streamed message. Thus the apply
> > > > worker cannot associate the message with the subtransaction and cannot
> > > > roll it back properly.
> > > >
> > > > Strictly speaking, this is an existing issue, but it becomes more
> > > > visible once subscribers can handle logical messages via this hook. So
> > > > it may be worth considering whether to fix it along with this patch or
> > > > separately.
> > > >
> > >
> > > Right, it didn't have any impact till now for native replication as we
> > > were just ignoring these messages on subscribers. I think this could
> > > have impacted output-plugins if they used this functionality. I think
> > > we can fix this separately but it is better to fix it before this
> > > patch as this patch can expose a hidden issue.
> >
> > Agreed that we should fix it before this patch.
> >
> > The Hou's patch looks good. I prefer to apply it to only master as
> > external output plugin might require changes similar to what the patch
> > does for test_decoding.
> >
> > And thank you for the 0002 patch. I'll include it in the next version patch.
>
> I've attached the new patches. I just updated the commit message for
> the 0001 patch, and added some fixes and regression tests for the 0002
> patch. Please review them.

I think the 0001 patch can be pushed independently. So I'm going to
push it to master, barring objections.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Nov 12, 2026 at 4:10 AM Masahiko Sawada  wrote:
>
> On Mon, Nov 9, 2026 at 5:21 PM Masahiko Sawada  wrote:
> >
> > I've attached the new patches. I just updated the commit message for
> > the 0001 patch, and added some fixes and regression tests for the 0002
> > patch. Please review them.
>
> I think the 0001 patch can be pushed independently. So I'm going to
> push it to master, barring objections.
>

Few comments on 0001:
* As the parameter to stream_message callback could be a
sub-transaction which is different from other similar callbacks like
truncate and change, it would be better to add that in docs where we
describe LogicalDecodeStreamMessageCB. The one more thing which we may
consider is how to get the top txn if required by callback as the
patch did in test_decoding.
* As we are planning this as a master-only change, will it be better
if we just pass subxid as a separate parameter to keep the interface
consistent with other similar interfaces and avoid the need for
plugins to retrieve toptxn separately.
* Similar to pg_decode_stream_message, shouldn't there be a call to
stream_start if (!txndata->stream_wrote_changes). This is just a code
observation, I haven't tested it.

-- 
With Regards,
Amit Kapila.


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

Sorry for joining this discussion so late.

On Thu, Nov 12, 2026 at 03:02:44PM +0530, Amit Kapila wrote:
> On Thu, Nov 12, 2026 at 4:10 AM Masahiko Sawada  wrote:
> >
> > On Mon, Nov 9, 2026 at 5:21 PM Masahiko Sawada  wrote:
> > >
> > > I've attached the new patches. I just updated the commit message for
> > > the 0001 patch, and added some fixes and regression tests for the 0002
> > > patch. Please review them.
> >
> > I think the 0001 patch can be pushed independently. So I'm going to
> > push it to master, barring objections.
> >
> 
> Few comments on 0001:
> * As we are planning this as a master-only change, will it be better
> if we just pass subxid as a separate parameter to keep the interface
> consistent with other similar interfaces and avoid the need for
> plugins to retrieve toptxn separately.

+1. That would also prevent the crash mentioned in the commit message, as txn
would remain the top level transaction.

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Thu, Nov 12, 2026 at 2:06 AM Bertrand Drouvot
 wrote:
>
> Hi,
>
> Sorry for joining this discussion so late.
>
> On Thu, Nov 12, 2026 at 03:02:44PM +0530, Amit Kapila wrote:
> > On Thu, Nov 12, 2026 at 4:10 AM Masahiko Sawada  wrote:
> > >
> > > On Mon, Nov 9, 2026 at 5:21 PM Masahiko Sawada  wrote:
> > > >
> > > > I've attached the new patches. I just updated the commit message for
> > > > the 0001 patch, and added some fixes and regression tests for the 0002
> > > > patch. Please review them.
> > >
> > > I think the 0001 patch can be pushed independently. So I'm going to
> > > push it to master, barring objections.
> > >
> >
> > Few comments on 0001:
> > * As we are planning this as a master-only change, will it be better
> > if we just pass subxid as a separate parameter to keep the interface
> > consistent with other similar interfaces and avoid the need for
> > plugins to retrieve toptxn separately.
>
> +1. That would also prevent the crash mentioned in the commit message, as txn
> would remain the top level transaction.
>
> Regards,

Agreed. It's better for callbacks to get both top-level and
subtransaction's ids.

I've updated the patches (the 0002 patch unchanged).

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Вложения:
Hi,

On Sat, Nov14, 2026 at 07:35 AM Masahiko Sawada wrote:
>
> Agreed. It's better for callbacks to get both top-level and
> subtransaction's ids.
>
> I've updated the patches (the 0002 patch unchanged).

 > -	ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
 > +	ctx->write_xid = xid;

I think it would be better to keep the original code for consistency, as 
all the other callbacks set ctx->write_xid to txn->xid (the top-level 
transaction's XID). IIUC, this was changed to make the test pass since 
test_decoding does not otherwise output the subxid, but we could instead 
use pgoutput to test that and keep passing the top-level XID in 
ctx->write_xid. Please see the attached top-up patch for this change.


BTW, since we are changing the callback signature anyway, another wild 
idea would be to pass ReorderBufferChange directly instead so that it is 
fully consistent with the other change callbacks. That said, it would 
require more changes in third-party output plugins, so I don't insist on 
it if you disagree — just sharing for reference.

-- 
Best Regards,
Zhijie Hou

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Sun, Nov 15, 2026 at 9:13 AM Zhijie Hou  wrote:
>
> Hi,
>
> On Sat, Nov14, 2026 at 07:35 AM Masahiko Sawada wrote:
> >
> > Agreed. It's better for callbacks to get both top-level and
> > subtransaction's ids.
> >
> > I've updated the patches (the 0002 patch unchanged).
>
>  > -    ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
>  > +    ctx->write_xid = xid;
>
> I think it would be better to keep the original code for consistency, as
> all the other callbacks set ctx->write_xid to txn->xid (the top-level
> transaction's XID). IIUC, this was changed to make the test pass since
> test_decoding does not otherwise output the subxid, but we could instead
> use pgoutput to test that and keep passing the top-level XID in
> ctx->write_xid. Please see the attached top-up patch for this change.

Agreed. I've applied your patch.

> BTW, since we are changing the callback signature anyway, another wild
> idea would be to pass ReorderBufferChange directly instead so that it is
> fully consistent with the other change callbacks. That said, it would
> require more changes in third-party output plugins, so I don't insist on
> it if you disagree — just sharing for reference.

It seems overkill to me. For non-transactional messages, we don't
create a ReorderBufferChange for them, so we would have to allocate
one just for the callback and copy the prefix and the message into it.
We would still need a separate transactional argument, so I guess it
would not help us pass more information than the xid does.

I've attached the updated patches.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Mon, Nov 16, 2026 at 11:05:00AM -0800, Masahiko Sawada wrote:
> 
> I've attached the updated patches.

Thanks!

I did not look in details but I have a question. I'm wondering what would happen
with an unpatched publisher when both messages and streaming are enabled. Suppose
a message is emitted in a subtransaction that is later aborted. The publisher
sends the top level XID with the message, whereas STREAM ABORT refers to the
subtransaction XID. IIUC, the patched subscriber would therefore not discard that
message.

Should 0002 handle this case somehow?

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Tue, Nov 17, 2026 at 12:14 AM Bertrand Drouvot
 wrote:
>
> Hi,
>
> On Mon, Nov 16, 2026 at 11:05:00AM -0800, Masahiko Sawada wrote:
> >
> > I've attached the updated patches.
>
> Thanks!
>
> I did not look in details but I have a question. I'm wondering what would happen
> with an unpatched publisher when both messages and streaming are enabled. Suppose
> a message is emitted in a subtransaction that is later aborted. The publisher
> sends the top level XID with the message, whereas STREAM ABORT refers to the
> subtransaction XID. IIUC, the patched subscriber would therefore not discard that
> message.
>
> Should 0002 handle this case somehow?

Good point. In that case, the subscriber would apply the message when
the top-level transaction commits, even though the subtransaction that
emitted it was rolled back.

Given that the 0001 patch is not backpatched, I think the subscriber
should request the messages option only from v20 or later publishers,
like it doesn't send the origin option to publishers older than v16.
The patch already checks the publisher version there, so we just need
to raise it from v14 to v20. What do you think?

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Tue, Nov 17, 2026 at 02:14:15PM -0800, Masahiko Sawada wrote:
> On Tue, Nov 17, 2026 at 12:14 AM Bertrand Drouvot
>  wrote:
> >
> > Hi,
> >
> > On Mon, Nov 16, 2026 at 11:05:00AM -0800, Masahiko Sawada wrote:
> > >
> > > I've attached the updated patches.
> >
> > Thanks!
> >
> > I did not look in details but I have a question. I'm wondering what would happen
> > with an unpatched publisher when both messages and streaming are enabled. Suppose
> > a message is emitted in a subtransaction that is later aborted. The publisher
> > sends the top level XID with the message, whereas STREAM ABORT refers to the
> > subtransaction XID. IIUC, the patched subscriber would therefore not discard that
> > message.
> >
> > Should 0002 handle this case somehow?
> 
> Good point. In that case, the subscriber would apply the message when
> the top-level transaction commits, even though the subtransaction that
> emitted it was rolled back.

Yeah, thanks for confirming.

> Given that the 0001 patch is not backpatched, I think the subscriber
> should request the messages option only from v20 or later publishers,
> like it doesn't send the origin option to publishers older than v16.
> The patch already checks the publisher version there, so we just need
> to raise it from v14 to v20. What do you think?

One difference with origin is that older publishers do not support that option
at all, whereas v14 through v19 publishers support messages and the issue occurs
only when streaming is enabled.

I wonder if it would make sense to request messages from those publishers when
streaming is disabled, and require v20 or later when streaming is enabled?

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Tue, Nov 17, 2026 at 6:06 AM Masahiko Sawada  wrote:
>
> On Sun, Nov 15, 2026 at 9:13 AM Zhijie Hou  wrote:
> >
> I've attached the updated patches.
>

Hi Sawada-san,

I found an issue in 0002 with non-transactional messages.

I found this while reviewing the patch with Claude, which also helped
write the TAP test below.

In apply_handle_message(), the non-transactional branch commits the
handler's work locally but calls replorigin_xact_clear(false) first,
so the commit doesn't advance the replication origin. Until the
publisher receives feedback that this commit has been flushed, both
the origin and the slot's confirmed_flush point before the message.
Feedback lags, since apply workers default to synchronous_commit =
off. If the worker exits in that window, the message is decoded and
sent again on restart, and the handler runs again. The easiest way to
hit it is a non-transactional message followed by a transaction that
conflicts on the subscriber. Every retry re-applies the message before
failing on the conflict again. With wal_retrieve_retry_interval =
200ms I saw 42 handler invocations for a single message in 8 seconds.
Handlers are documented as needing to be idempotent, but repeating
once per retry seems avoidable, since normal transactions don't have
this problem.

The fix is to record the message's LSN as the origin LSN instead of
clearing it:

- replorigin_xact_clear(false);
+ replorigin_xact_state.origin_lsn = msg.lsn;
+ replorigin_xact_state.origin_timestamp = 0;

With origin_timestamp = 0, RecordTransactionCommit() uses the local
commit time, so the commit still doesn't inherit the previous
transaction's timestamp, which was the reason for the clear. With this
change the handler runs once across all retries, and 001_basic.pl
still passes.

Attached is a TAP test (099_nontx_redelivery.pl) that reproduces the
issue: it fails on v9 and passes with the change above.

Regards,
Ajin Cherian
Fujitsu Australia

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Nov 17, 2026 at 12:35 AM Masahiko Sawada  wrote:
>
> On Sun, Nov 15, 2026 at 9:13 AM Zhijie Hou  wrote:
> >
>
> > BTW, since we are changing the callback signature anyway, another wild
> > idea would be to pass ReorderBufferChange directly instead so that it is
> > fully consistent with the other change callbacks. That said, it would
> > require more changes in third-party output plugins, so I don't insist on
> > it if you disagree — just sharing for reference.
>
> It seems overkill to me. For non-transactional messages, we don't
> create a ReorderBufferChange for them, so we would have to allocate
> one just for the callback and copy the prefix and the message into it.
> We would still need a separate transactional argument, so I guess it
> would not help us pass more information than the xid does.
>

+1. I also thought about it but didn't see this as an improvement as
we still won't be able to remove the existing parameter like prefix
which we are separately passing extracting them from
ReorderBufferChange.

-- 
With Regards,
Amit Kapila.


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Nov 18, 2026 at 12:13 PM Bertrand Drouvot
 wrote:
>
> On Tue, Nov 17, 2026 at 02:14:15PM -0800, Masahiko Sawada wrote:
> > On Tue, Nov 17, 2026 at 12:14 AM Bertrand Drouvot
> >  wrote:
>
> > Given that the 0001 patch is not backpatched, I think the subscriber
> > should request the messages option only from v20 or later publishers,
> > like it doesn't send the origin option to publishers older than v16.
> > The patch already checks the publisher version there, so we just need
> > to raise it from v14 to v20. What do you think?
>
> One difference with origin is that older publishers do not support that option
> at all, whereas v14 through v19 publishers support messages and the issue occurs
> only when streaming is enabled.
>
> I wonder if it would make sense to request messages from those publishers when
> streaming is disabled, and require v20 or later when streaming is enabled?
>

We could use one of the ideas proposed or just leave as it is. It is
possible that there is no such use till now, so, adding more version
checking in the code for such things may not add much value.

-- 
With Regards,
Amit Kapila.


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Thu, Nov 19, 2026 at 2:49 AM Amit Kapila  wrote:
>
> On Wed, Nov 18, 2026 at 12:13 PM Bertrand Drouvot
>  wrote:
> >
> > On Tue, Nov 17, 2026 at 02:14:15PM -0800, Masahiko Sawada wrote:
> > > On Tue, Nov 17, 2026 at 12:14 AM Bertrand Drouvot
> > >  wrote:
> >
> > > Given that the 0001 patch is not backpatched, I think the subscriber
> > > should request the messages option only from v20 or later publishers,
> > > like it doesn't send the origin option to publishers older than v16.
> > > The patch already checks the publisher version there, so we just need
> > > to raise it from v14 to v20. What do you think?
> >
> > One difference with origin is that older publishers do not support that option
> > at all, whereas v14 through v19 publishers support messages and the issue occurs
> > only when streaming is enabled.
> >
> > I wonder if it would make sense to request messages from those publishers when
> > streaming is disabled, and require v20 or later when streaming is enabled?
> >
>
> We could use one of the ideas proposed or just leave as it is. It is
> possible that there is no such use till now, so, adding more version
> checking in the code for such things may not add much value.

I'd like to keep it simple and require v20 or later regardless of the
streaming option. Since streaming defaults to parallel, the
subscribers would have to give up the performance benefit of
streaming. So I don't think it's worth adding another check for them,
as Amit said.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Дата:
Hi,

On Thu, Nov 19, 2026 at 03:42:06PM -0800, Masahiko Sawada wrote:
> On Thu, Nov 19, 2026 at 2:49 AM Amit Kapila  wrote:
> >
> > On Wed, Nov 18, 2026 at 12:13 PM Bertrand Drouvot
> >  wrote:
> > >
> > > On Tue, Nov 17, 2026 at 02:14:15PM -0800, Masahiko Sawada wrote:
> > > > On Tue, Nov 17, 2026 at 12:14 AM Bertrand Drouvot
> > > >  wrote:
> > >
> > > > Given that the 0001 patch is not backpatched, I think the subscriber
> > > > should request the messages option only from v20 or later publishers,
> > > > like it doesn't send the origin option to publishers older than v16.
> > > > The patch already checks the publisher version there, so we just need
> > > > to raise it from v14 to v20. What do you think?
> > >
> > > One difference with origin is that older publishers do not support that option
> > > at all, whereas v14 through v19 publishers support messages and the issue occurs
> > > only when streaming is enabled.
> > >
> > > I wonder if it would make sense to request messages from those publishers when
> > > streaming is disabled, and require v20 or later when streaming is enabled?
> > >
> >
> > We could use one of the ideas proposed or just leave as it is. It is
> > possible that there is no such use till now, so, adding more version
> > checking in the code for such things may not add much value.
> 
> I'd like to keep it simple and require v20 or later regardless of the
> streaming option. Since streaming defaults to parallel, the
> subscribers would have to give up the performance benefit of
> streaming. So I don't think it's worth adding another check for them,
> as Amit said.

Yeah, that sounds reasonable to me.

Regards,

-- 
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com


Re: Add a hook for handling logical decoding messages on subscribers.

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Wed, Nov 18, 2026 at 4:48 PM Ajin Cherian  wrote:
>
> On Tue, Nov 17, 2026 at 6:06 AM Masahiko Sawada  wrote:
> >
> > On Sun, Nov 15, 2026 at 9:13 AM Zhijie Hou  wrote:
> > >
> > I've attached the updated patches.
> >
>
> Hi Sawada-san,
>
> I found an issue in 0002 with non-transactional messages.
>
> I found this while reviewing the patch with Claude, which also helped
> write the TAP test below.
>
> In apply_handle_message(), the non-transactional branch commits the
> handler's work locally but calls replorigin_xact_clear(false) first,
> so the commit doesn't advance the replication origin. Until the
> publisher receives feedback that this commit has been flushed, both
> the origin and the slot's confirmed_flush point before the message.
> Feedback lags, since apply workers default to synchronous_commit =
> off. If the worker exits in that window, the message is decoded and
> sent again on restart, and the handler runs again. The easiest way to
> hit it is a non-transactional message followed by a transaction that
> conflicts on the subscriber. Every retry re-applies the message before
> failing on the conflict again. With wal_retrieve_retry_interval =
> 200ms I saw 42 handler invocations for a single message in 8 seconds.
> Handlers are documented as needing to be idempotent, but repeating
> once per retry seems avoidable, since normal transactions don't have
> this problem.

Good find. Since we already treat msg.lsn as the position the message
is applied at when reporting the flush position, it makes sense to
advance the origin to it as well, as we do for commits.

Given that we’ve agreed on the 0001 patch, I’m going to push it early
next week, barring any objections. I’d like to hold off on the 0002
patch to give it more review time.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: Add a hook for handling logical decoding messages on subscribers.

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Sat, Nov 21, 2026 at 12:05 AM Masahiko Sawada  wrote:
>
> Given that we’ve agreed on the 0001 patch, I’m going to push it early
> next week, barring any objections. I’d like to hold off on the 0002
> patch to give it more review time.
>

+1.

-- 
With Regards,
Amit Kapila.


FAQ