Initial COPY of Logical Replication is too slow

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

Initial COPY of Logical Replication is too slow

От:
Marcos Pegoraro <marcos@f10.com.br>
Дата:
Вложения:
Subscriber needs to ask publisher about tables and fields to COPY and it uses pg_get_publication_tables for that, and it is too slow when the number of tables is high because on every table it's subscribed it has to run this select. 
We can get the same result with a join on pg_publication_rel.

regards
Marcos

Re: Initial COPY of Logical Replication is too slow

От:
Marcos Pegoraro <marcos@f10.com.br>
Дата:
You can see how much time a subscriber will need to get all files which were added with this.
Run first time and will create 10 thousand tables, publish them and measure how much time to get all tables Ready on pg_subscription_rel.
Run again to add more 10 thousand tables and see that time will increase, more tables and more time.

This is just to show that if you create a subscription with a high number of tables it spends more time doing select on pg_get_publication_tables than the time spent actually copying. My use case I have 50 thousand tables, and it takes 5 seconds every time it needs to get next table to copy.

--Create a empty publication
create publication my_pub;

--Run these 3 following anonymous blocks to create schemas, tables and add them to publication.
--Need to have 3 blocks because I cannot create a table in a schema that is not committed. And the same for a publication.
do $$ declare Schemas_Add integer = 100; Actual_Schema text; begin
  for Actual_Schema in select 'test_'||(select to_char(coalesce(max(substring(nspname,'test_(\d+)')::integer),0)+g,'FM00000')
                                       from pg_namespace where nspname ~ 'test_\d+') from generate_series(1,Schemas_Add) g loop
    execute format('create schema %s',Actual_Schema);
  end loop;
end;$$;

do $$ declare Tables_Add integer = 100; Actual_Schema text; begin
  for Actual_Schema in select nspname from pg_namespace where nspname  ~ 'test_\d+' and
                      not exists(select from pg_class where relnamespace = pg_namespace.oid) loop
    for j in 1..Tables_Add loop
      execute format('create table %s.test_%s as select generate_series(1,random(0,10))::integer id;',
                     Actual_Schema,to_char(j,'FM00000'));
    end loop;
  end loop;
end;$$;

do $$ declare Schemas_To_Add text = (select string_agg(nspname,',') from pg_namespace n where nspname ~ 'test_\d+' and
                              not exists(select from pg_publication_namespace where pnnspid = n.oid)); begin
  execute format('alter publication my_pub add tables in schema %s;',Schemas_To_Add);
end;$$;

--Then you can see what was generated and go to the subscriber side to refresh the subscription and measure time spent to synchronize.
select * from pg_Namespace where nspname ~ 'test_\d+';
select pnnspid::regnamespace, * from pg_publication_namespace;
select oid::regclass, * from pg_Class where relnamespace::regnamespace::text ~ 'test_\d+' and relkind = 'r';

--Later just clean what you do.
drop publication my_pub;

do $$ declare Schema_Drop text; begin
  for Schema_Drop in select nspname from pg_Namespace where nspname ~ 'test_\d+' loop
    execute format ('drop schema %s cascade;',Schema_Drop);
  end loop;
end;$$;

regards
Marcos


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Hi,

On Sat, Dec 6, 2025 at 4:19 AM Marcos Pegoraro  wrote:
>
> Subscriber needs to ask publisher about tables and fields to COPY and it uses pg_get_publication_tables for that, and it is too slow when the number of tables is high because on every table it's subscribed it has to run this select.

Yeah, if we pass a publication that a lot of tables belong to to
pg_get_publication_tables(), it could take a long time to return as it
needs to construct many entries.

> We can get the same result with a join on pg_publication_rel.

You changed the query not to use pg_get_publication_tables():

-                                                "SELECT DISTINCT"
-                                                "  (CASE WHEN
(array_length(gpt.attrs, 1) = c.relnatts)"
-                                                "   THEN NULL ELSE
gpt.attrs END)"
-                                                "  FROM pg_publication p,"
-                                                "  LATERAL
pg_get_publication_tables(p.pubname) gpt,"
-                                                "  pg_class c"
-                                                " WHERE gpt.relid =
%u AND c.oid = gpt.relid"
-                                                "   AND p.pubname IN ( %s )",
-                                                lrel->remoteid,
-                                                pub_names->data);
+                       "SELECT CASE WHEN cardinality(r.prattrs) <>
relnatts THEN "
+                                               "r.prattrs END FROM pg_class c "
+                                               "LEFT JOIN LATERAL
(SELECT DISTINCT prattrs FROM "
+                                               "pg_publication_rel r
INNER JOIN pg_publication p "
+                                               "ON p.oid = r.prpubid
WHERE c.oid = r.prrelid AND "
+                                               "pubname in ( %s )) r
ON TRUE WHERE c.oid = %u",
+                                                pub_names->data,
+                                                lrel->remoteid);

Simply replacing pg_get_publication_tables() with joining on
pg_publication_rel doesn't work since pg_get_publication_tables()
cares for several cases, for example where the specified columns are
generated columns and the specified table is a partitioned table etc.
Therefore the patch doesn't pass the regression tests.

I think it would make more sense to introduce a dedicated SQL function
that takes the reloid as well as the list of publications and returns
the relation's the column list and row filter expression while
filtering unnecessary rows inside the function.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Marcos Pegoraro <marcos@f10.com.br>
Дата:
Em sex., 19 de dez. de 2025 às 22:59, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:
Yeah, if we pass a publication that a lot of tables belong to to
pg_get_publication_tables(), it could take a long time to return as it
needs to construct many entries.

Well, I don't know how to help but I'm sure it's working badly. 
Today I added some fields on my server, then seeing logs I could see how slow this process is. 

duration: 2213.872 ms  statement: SELECT DISTINCT  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)   THEN NULL ELSE gpt.attrs END)  FROM pg_publication p,  LATERAL pg_get_publication_tables(p.pubname) gpt,  pg_class c WHERE gpt.relid = 274376788 AND c.oid = gpt.relid   AND p.pubname IN ( 'mypub' )

2 seconds to get the list of fields of a table is really too slow.
How can we solve this ?

regards
Marcos

Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Mon, Jan 19, 2026 at 9:44 AM Marcos Pegoraro  wrote:
>
> Em sex., 19 de dez. de 2025 às 22:59, Masahiko Sawada  escreveu:
>>
>> Yeah, if we pass a publication that a lot of tables belong to to
>> pg_get_publication_tables(), it could take a long time to return as it
>> needs to construct many entries.
>
>
> Well, I don't know how to help but I'm sure it's working badly.
> Today I added some fields on my server, then seeing logs I could see how slow this process is.
>
> duration: 2213.872 ms  statement: SELECT DISTINCT  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)   THEN NULL ELSE gpt.attrs END)  FROM pg_publication p,  LATERAL pg_get_publication_tables(p.pubname) gpt,  pg_class c WHERE gpt.relid = 274376788 AND c.oid = gpt.relid   AND p.pubname IN ( 'mypub' )
>
> 2 seconds to get the list of fields of a table is really too slow.
> How can we solve this ?

After more investigation of slowness, it seems that the
list_concat_unique_oid() called below is quite slow when the database
has a lot of tables to publish:

    relids = GetPublicationRelations(pub_elem->oid,
                                     pub_elem->pubviaroot ?
                                     PUBLICATION_PART_ROOT :
                                     PUBLICATION_PART_LEAF);
    schemarelids = GetAllSchemaPublicationRelations(pub_elem->oid,
                                                     pub_elem->pubviaroot ?
                                                     PUBLICATION_PART_ROOT :
                                                     PUBLICATION_PART_LEAF);
    pub_elem_tables = list_concat_unique_oid(relids, schemarelids);

This is simply because it's O(n^2), where n is the number of oids in
schemarelids in the test case. A simple change would be to do sort &
dedup instead. With the attached experimental patch, the
pg_get_publication_tables() execution time gets halved in my
environment (796ms -> 430ms with 50k tables). If the number of tables
is not large, this method might be slower than today but it's not a
huge regression.

In the initial tablesync cases, it could be optimized further in a way
that we introduce a new SQL function that gets the column list and
expr of the specific table. This way, we can filter the result by
relid at an early stage instead of getting all information and
filtering by relid as the tablesync worker does today, avoiding
overheads of gathering system catalog scan results.

Regards,

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

Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Mon, Jan 26, 2026 at 12:30 PM Masahiko Sawada  wrote:
>
> On Mon, Jan 19, 2026 at 9:44 AM Marcos Pegoraro  wrote:
> >
> > Em sex., 19 de dez. de 2025 às 22:59, Masahiko Sawada  escreveu:
> >>
> >> Yeah, if we pass a publication that a lot of tables belong to to
> >> pg_get_publication_tables(), it could take a long time to return as it
> >> needs to construct many entries.
> >
> >
> > Well, I don't know how to help but I'm sure it's working badly.
> > Today I added some fields on my server, then seeing logs I could see how slow this process is.
> >
> > duration: 2213.872 ms  statement: SELECT DISTINCT  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)   THEN NULL ELSE gpt.attrs END)  FROM pg_publication p,  LATERAL pg_get_publication_tables(p.pubname) gpt,  pg_class c WHERE gpt.relid = 274376788 AND c.oid = gpt.relid   AND p.pubname IN ( 'mypub' )
> >
> > 2 seconds to get the list of fields of a table is really too slow.
> > How can we solve this ?
>
> After more investigation of slowness, it seems that the
> list_concat_unique_oid() called below is quite slow when the database
> has a lot of tables to publish:
>
>     relids = GetPublicationRelations(pub_elem->oid,
>                                      pub_elem->pubviaroot ?
>                                      PUBLICATION_PART_ROOT :
>                                      PUBLICATION_PART_LEAF);
>     schemarelids = GetAllSchemaPublicationRelations(pub_elem->oid,
>                                                      pub_elem->pubviaroot ?
>                                                      PUBLICATION_PART_ROOT :
>                                                      PUBLICATION_PART_LEAF);
>     pub_elem_tables = list_concat_unique_oid(relids, schemarelids);
>
> This is simply because it's O(n^2), where n is the number of oids in
> schemarelids in the test case. A simple change would be to do sort &
> dedup instead. With the attached experimental patch, the
> pg_get_publication_tables() execution time gets halved in my
> environment (796ms -> 430ms with 50k tables). If the number of tables
> is not large, this method might be slower than today but it's not a
> huge regression.
>
> In the initial tablesync cases, it could be optimized further in a way
> that we introduce a new SQL function that gets the column list and
> expr of the specific table. This way, we can filter the result by
> relid at an early stage instead of getting all information and
> filtering by relid as the tablesync worker does today, avoiding
> overheads of gathering system catalog scan results.

I've drafted this idea and I find it looks like a better approach. The
patch introduces the pg_get_publication_table_info() SQL function that
returns the column list and row filter expression like
pg_get_publication_tables() returns but it checks only the specific
table unlike pg_get_publication_tables(). On my env, the tablesync
worker's query in question becomes 0.6ms from 288 ms with 50k tables
in one publication. Feedback is very welcome.

Regards,

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

Re: Initial COPY of Logical Replication is too slow

От:
"Matheus Alcantara" <matheusssilv97@gmail.com>
Дата:
Hi

On Wed Feb 25, 2026 at 4:03 PM -03, Masahiko Sawada wrote:
>> After more investigation of slowness, it seems that the
>> list_concat_unique_oid() called below is quite slow when the database
>> has a lot of tables to publish:
>>
>>     relids = GetPublicationRelations(pub_elem->oid,
>>                                      pub_elem->pubviaroot ?
>>                                      PUBLICATION_PART_ROOT :
>>                                      PUBLICATION_PART_LEAF);
>>     schemarelids = GetAllSchemaPublicationRelations(pub_elem->oid,
>>                                                      pub_elem->pubviaroot ?
>>                                                      PUBLICATION_PART_ROOT :
>>                                                      PUBLICATION_PART_LEAF);
>>     pub_elem_tables = list_concat_unique_oid(relids, schemarelids);
>>
>> This is simply because it's O(n^2), where n is the number of oids in
>> schemarelids in the test case. A simple change would be to do sort &
>> dedup instead. With the attached experimental patch, the
>> pg_get_publication_tables() execution time gets halved in my
>> environment (796ms -> 430ms with 50k tables). If the number of tables
>> is not large, this method might be slower than today but it's not a
>> huge regression.
>>
>> In the initial tablesync cases, it could be optimized further in a way
>> that we introduce a new SQL function that gets the column list and
>> expr of the specific table. This way, we can filter the result by
>> relid at an early stage instead of getting all information and
>> filtering by relid as the tablesync worker does today, avoiding
>> overheads of gathering system catalog scan results.
>
> I've drafted this idea and I find it looks like a better approach. The
> patch introduces the pg_get_publication_table_info() SQL function that
> returns the column list and row filter expression like
> pg_get_publication_tables() returns but it checks only the specific
> table unlike pg_get_publication_tables(). On my env, the tablesync
> worker's query in question becomes 0.6ms from 288 ms with 50k tables
> in one publication. Feedback is very welcome.
>

Thanks for patch. I did a review and here are my comments:

+	values[0] = ObjectIdGetDatum(pub->oid);
+	values[1] = ObjectIdGetDatum(relid);
+
+	values[0] = ObjectIdGetDatum(pub->oid);
+	values[1] = ObjectIdGetDatum(relid);

Duplicated assignments?

--------------

+		  /* ALL TALBES publication */

Typo on TALBES

--------------

+ * Common routine for pg_get_publication_tables() and
+ * pg_get_publication_table_info() to construct the result tuple.
+ */
+static HeapTuple
+construct_published_rel_tuple(published_rel *table_info, TupleDesc tuple_desc)

construct_published_rel_tuple is only being used on
pg_get_publication_table_info(). Perhaps it can also be used on "if
(funcctx->call_cntr < list_length(table_infos))" block on
pg_get_publication_tables()?

--------------

Is new regression tests needed or the current ones already cover the new
function engouth? The code of pg_get_publication_table_info seems well
coveraged.

--------------

It seems that pgindent is missing on src/backend/catalog/pg_publication.c

--
Matheus Alcantara
EDB: https://www.enterprisedb.com


Re: Initial COPY of Logical Replication is too slow

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Feb 26, 2026, at 03:03, Masahiko Sawada  wrote:
> 
> On Mon, Jan 26, 2026 at 12:30 PM Masahiko Sawada  wrote:
>> 
>> On Mon, Jan 19, 2026 at 9:44 AM Marcos Pegoraro  wrote:
>>> 
>>> Em sex., 19 de dez. de 2025 às 22:59, Masahiko Sawada  escreveu:
>>>> 
>>>> Yeah, if we pass a publication that a lot of tables belong to to
>>>> pg_get_publication_tables(), it could take a long time to return as it
>>>> needs to construct many entries.
>>> 
>>> 
>>> Well, I don't know how to help but I'm sure it's working badly.
>>> Today I added some fields on my server, then seeing logs I could see how slow this process is.
>>> 
>>> duration: 2213.872 ms  statement: SELECT DISTINCT  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)   THEN NULL ELSE gpt.attrs END)  FROM pg_publication p,  LATERAL pg_get_publication_tables(p.pubname) gpt,  pg_class c WHERE gpt.relid = 274376788 AND c.oid = gpt.relid   AND p.pubname IN ( 'mypub' )
>>> 
>>> 2 seconds to get the list of fields of a table is really too slow.
>>> How can we solve this ?
>> 
>> After more investigation of slowness, it seems that the
>> list_concat_unique_oid() called below is quite slow when the database
>> has a lot of tables to publish:
>> 
>>    relids = GetPublicationRelations(pub_elem->oid,
>>                                     pub_elem->pubviaroot ?
>>                                     PUBLICATION_PART_ROOT :
>>                                     PUBLICATION_PART_LEAF);
>>    schemarelids = GetAllSchemaPublicationRelations(pub_elem->oid,
>>                                                     pub_elem->pubviaroot ?
>>                                                     PUBLICATION_PART_ROOT :
>>                                                     PUBLICATION_PART_LEAF);
>>    pub_elem_tables = list_concat_unique_oid(relids, schemarelids);
>> 
>> This is simply because it's O(n^2), where n is the number of oids in
>> schemarelids in the test case. A simple change would be to do sort &
>> dedup instead. With the attached experimental patch, the
>> pg_get_publication_tables() execution time gets halved in my
>> environment (796ms -> 430ms with 50k tables). If the number of tables
>> is not large, this method might be slower than today but it's not a
>> huge regression.
>> 
>> In the initial tablesync cases, it could be optimized further in a way
>> that we introduce a new SQL function that gets the column list and
>> expr of the specific table. This way, we can filter the result by
>> relid at an early stage instead of getting all information and
>> filtering by relid as the tablesync worker does today, avoiding
>> overheads of gathering system catalog scan results.
> 
> I've drafted this idea and I find it looks like a better approach. The
> patch introduces the pg_get_publication_table_info() SQL function that
> returns the column list and row filter expression like
> pg_get_publication_tables() returns but it checks only the specific
> table unlike pg_get_publication_tables(). On my env, the tablesync
> worker's query in question becomes 0.6ms from 288 ms with 50k tables
> in one publication. Feedback is very welcome.
> 
> Regards,
> 
> -- 
> Masahiko Sawada
> Amazon Web Services: https://aws.amazon.com
> <0001-Add-pg_get_publication_table_info-to-optimize-logica.patch>

A few comments:

1. pg_publication.c needs to pg_indent. When I ran pg_indent agains it, the patch code got a lot format changes.

2
```
+	values[0] = ObjectIdGetDatum(pub->oid);
+	values[1] = ObjectIdGetDatum(relid);
+
+	values[0] = ObjectIdGetDatum(pub->oid);
+	values[1] = ObjectIdGetDatum(relid);
```

Looks like a copy-pasto.

3 I think we can optimize pg_get_publication_table_info() a little bit for non-publish tables by setting funcctx->max_calls = 0. I tried this code locally, and test still passed:
```
		if (publish)
		{
			pubrel = palloc_object(published_rel);
			pubrel->relid = relid;
			pubrel->pubid = pub->oid;
			funcctx->tuple_desc = BlessTupleDesc(tupdesc);
			funcctx->user_fctx = pubrel;
			funcctx->max_calls = 1; /* return one row */
		}
		else
			funcctx->max_calls = 0; /* return no rows */

		MemoryContextSwitchTo(oldcontext);
	}

	/* stuff done on every call of the function */
	funcctx = SRF_PERCALL_SETUP();

	if (funcctx->call_cntr < funcctx->max_calls)
	{
		HeapTuple	rettuple;

		table_info = (published_rel *) funcctx->user_fctx;
		rettuple = construct_published_rel_tuple(table_info, funcctx->tuple_desc);

		SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(rettuple));
	}

	SRF_RETURN_DONE(funcctx);
```

4
```
+		int		   i;
+
+		attnums = palloc_array(int16, desc->natts);
+
+		for (i = 0; i < desc->natts; i++)
```

Nit: Peter (E) ever did some cleanup of changing for loop variable into for. So I think that style is more preferred now:
```
for (int i = 0; i < desc->natts; i++)
```

5
```
+		attnums = palloc_array(int16, desc->natts);
```

Nit: attnums array is never free-ed, is that intentional? Actually, I’m kinda lost when a memory should be free-ed and when not.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Wed, Feb 25, 2026 at 11:03 AM Masahiko Sawada  wrote:
>
> On Mon, Jan 26, 2026 at 12:30 PM Masahiko Sawada  wrote:
> >
> > On Mon, Jan 19, 2026 at 9:44 AM Marcos Pegoraro  wrote:
> > >
> > > Em sex., 19 de dez. de 2025 às 22:59, Masahiko Sawada  escreveu:
> > >>
> > >> Yeah, if we pass a publication that a lot of tables belong to to
> > >> pg_get_publication_tables(), it could take a long time to return as it
> > >> needs to construct many entries.
> > >
> > >
> > > Well, I don't know how to help but I'm sure it's working badly.
> > > Today I added some fields on my server, then seeing logs I could see how slow this process is.
> > >
> > > duration: 2213.872 ms  statement: SELECT DISTINCT  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)   THEN NULL ELSE gpt.attrs END)  FROM pg_publication p,  LATERAL pg_get_publication_tables(p.pubname) gpt,  pg_class c WHERE gpt.relid = 274376788 AND c.oid = gpt.relid   AND p.pubname IN ( 'mypub' )
> > >
> > > 2 seconds to get the list of fields of a table is really too slow.
> > > How can we solve this ?
> >
> > After more investigation of slowness, it seems that the
> > list_concat_unique_oid() called below is quite slow when the database
> > has a lot of tables to publish:
> >
> >     relids = GetPublicationRelations(pub_elem->oid,
> >                                      pub_elem->pubviaroot ?
> >                                      PUBLICATION_PART_ROOT :
> >                                      PUBLICATION_PART_LEAF);
> >     schemarelids = GetAllSchemaPublicationRelations(pub_elem->oid,
> >                                                      pub_elem->pubviaroot ?
> >                                                      PUBLICATION_PART_ROOT :
> >                                                      PUBLICATION_PART_LEAF);
> >     pub_elem_tables = list_concat_unique_oid(relids, schemarelids);
> >
> > This is simply because it's O(n^2), where n is the number of oids in
> > schemarelids in the test case. A simple change would be to do sort &
> > dedup instead. With the attached experimental patch, the
> > pg_get_publication_tables() execution time gets halved in my
> > environment (796ms -> 430ms with 50k tables). If the number of tables
> > is not large, this method might be slower than today but it's not a
> > huge regression.
> >
> > In the initial tablesync cases, it could be optimized further in a way
> > that we introduce a new SQL function that gets the column list and
> > expr of the specific table. This way, we can filter the result by
> > relid at an early stage instead of getting all information and
> > filtering by relid as the tablesync worker does today, avoiding
> > overheads of gathering system catalog scan results.
>
> I've drafted this idea and I find it looks like a better approach. The
> patch introduces the pg_get_publication_table_info() SQL function that
> returns the column list and row filter expression like
> pg_get_publication_tables() returns but it checks only the specific
> table unlike pg_get_publication_tables(). On my env, the tablesync
> worker's query in question becomes 0.6ms from 288 ms with 50k tables
> in one publication. Feedback is very welcome.

Another variant of this approach is to extend
pg_get_publication_table() so that it can accept a relid to get the
publication information of the specific table. I've attached the patch
for this idea. I'm going to add regression test cases.

pg_get_publication_table() is a VARIACID array function so the patch
changes its signature to {text[] [, oid]}, breaking the tool
compatibility. Given this function is mostly an internal-use function
(we don't have the documentation for it), it would probably be okay
with it. I find it's clearer than the other approach of introducing
pg_get_publication_table_info(). Feedback is very welcome.

Regards,

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

RE: Initial COPY of Logical Replication is too slow

От:
"Zhijie Hou (Fujitsu)" <houzj.fnst@fujitsu.com>
Дата:
On Saturday, February 28, 2026 7:48 AM Masahiko Sawada  wrote:
> To: Marcos Pegoraro 
> Cc: PostgreSQL Hackers 
> Subject: Re: Initial COPY of Logical Replication is too slow
> 
> Another variant of this approach is to extend
> pg_get_publication_table() so that it can accept a relid to get the publication
> information of the specific table. I've attached the patch for this idea. I'm
> going to add regression test cases.
> 
> pg_get_publication_table() is a VARIACID array function so the patch changes
> its signature to {text[] [, oid]}, breaking the tool compatibility. Given this
> function is mostly an internal-use function (we don't have the documentation
> for it), it would probably be okay with it. I find it's clearer than the other
> approach of introducing pg_get_publication_table_info(). Feedback is very
> welcome.

Thanks for updating the patch.

I have few comments for the function change:

1.

If we change the function signature, will it affect use cases where the
publisher version is newer and the subscriber version is older ? E.g., when
publisher is passing text style publication name to pg_get_publication_tables().

Besides, for upgrade scenarios where the publisher version is older, I think
the patch needs to add version checks to avoid passing the relid to
pg_get_publication_tables.

2.

In the following example, I expected it to output a table with valid row
filter, but it returns 0 row after applying the patch.

CREATE TABLE measurements (
    city_id         int not null,
    logdate         date not null,
    peaktemp        int,
    unitsales       int
) PARTITION BY RANGE (logdate);

-- Create partitions
CREATE TABLE measurements_2023_q1 PARTITION OF measurements
    FOR VALUES FROM ('2023-01-01') TO ('2023-04-01');

CREATE PUBLICATION pub FOR TABLE measurements_2023_q1 WHERE (city_id = 2);

select pg_get_publication_tables(ARRAY['pub2'], 'measurements_2023_q1'::regclass);
 pg_get_publication_tables
---------------------------
(0 rows)

Best Regards,
Hou zj

Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Tue, Mar 3, 2026 at 2:22 AM Zhijie Hou (Fujitsu)
 wrote:
>
> On Saturday, February 28, 2026 7:48 AM Masahiko Sawada  wrote:
> > To: Marcos Pegoraro 
> > Cc: PostgreSQL Hackers 
> > Subject: Re: Initial COPY of Logical Replication is too slow
> >
> > Another variant of this approach is to extend
> > pg_get_publication_table() so that it can accept a relid to get the publication
> > information of the specific table. I've attached the patch for this idea. I'm
> > going to add regression test cases.
> >
> > pg_get_publication_table() is a VARIACID array function so the patch changes
> > its signature to {text[] [, oid]}, breaking the tool compatibility. Given this
> > function is mostly an internal-use function (we don't have the documentation
> > for it), it would probably be okay with it. I find it's clearer than the other
> > approach of introducing pg_get_publication_table_info(). Feedback is very
> > welcome.
>
> Thanks for updating the patch.
>
> I have few comments for the function change:
>
> 1.
>
> If we change the function signature, will it affect use cases where the
> publisher version is newer and the subscriber version is older ? E.g., when
> publisher is passing text style publication name to pg_get_publication_tables().

Good point.

I noticed that changing the function signature of
pg_get_publication_tables() breaks logical replication setups where
the subscriber is 18 or older. In the latest patch, I've switched the
approach back to the pg_get_publication_table_info() idea.

>
> 2.
>
> In the following example, I expected it to output a table with valid row
> filter, but it returns 0 row after applying the patch.
>
> CREATE TABLE measurements (
>     city_id         int not null,
>     logdate         date not null,
>     peaktemp        int,
>     unitsales       int
> ) PARTITION BY RANGE (logdate);
>
> -- Create partitions
> CREATE TABLE measurements_2023_q1 PARTITION OF measurements
>     FOR VALUES FROM ('2023-01-01') TO ('2023-04-01');
>
> CREATE PUBLICATION pub FOR TABLE measurements_2023_q1 WHERE (city_id = 2);
>
> select pg_get_publication_tables(ARRAY['pub2'], 'measurements_2023_q1'::regclass);
>  pg_get_publication_tables
> ---------------------------
> (0 rows)

Thank you for testing the patch. I've fixed it and added regression
tests in the latest patch.

I've attached the updated patch.


Regards,

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

Re: Initial COPY of Logical Replication is too slow

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Mar 10, 2026 at 3:40 AM Masahiko Sawada  wrote:
>
> On Tue, Mar 3, 2026 at 2:22 AM Zhijie Hou (Fujitsu)
>  wrote:
> >
> > On Saturday, February 28, 2026 7:48 AM Masahiko Sawada  wrote:
> > > To: Marcos Pegoraro 
> > > Cc: PostgreSQL Hackers 
> > > Subject: Re: Initial COPY of Logical Replication is too slow
> > >
> > > Another variant of this approach is to extend
> > > pg_get_publication_table() so that it can accept a relid to get the publication
> > > information of the specific table. I've attached the patch for this idea. I'm
> > > going to add regression test cases.
> > >
> > > pg_get_publication_table() is a VARIACID array function so the patch changes
> > > its signature to {text[] [, oid]}, breaking the tool compatibility. Given this
> > > function is mostly an internal-use function (we don't have the documentation
> > > for it), it would probably be okay with it. I find it's clearer than the other
> > > approach of introducing pg_get_publication_table_info(). Feedback is very
> > > welcome.
> >
> > Thanks for updating the patch.
> >
> > I have few comments for the function change:
> >
> > 1.
> >
> > If we change the function signature, will it affect use cases where the
> > publisher version is newer and the subscriber version is older ? E.g., when
> > publisher is passing text style publication name to pg_get_publication_tables().
>
> Good point.
>
> I noticed that changing the function signature of
> pg_get_publication_tables() breaks logical replication setups where
> the subscriber is 18 or older.
>

Why adding a new function with additional parameters (Oid relid)
couldn't help with such a case? I am asking because your previous
version code looks simpler as compared to the new patch version.

-- 
With Regards,
Amit Kapila.


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Wed, Mar 18, 2026 at 6:56 AM Amit Kapila  wrote:
>
> On Tue, Mar 10, 2026 at 3:40 AM Masahiko Sawada  wrote:
> >
> > On Tue, Mar 3, 2026 at 2:22 AM Zhijie Hou (Fujitsu)
> >  wrote:
> > >
> > > On Saturday, February 28, 2026 7:48 AM Masahiko Sawada  wrote:
> > > > To: Marcos Pegoraro 
> > > > Cc: PostgreSQL Hackers 
> > > > Subject: Re: Initial COPY of Logical Replication is too slow
> > > >
> > > > Another variant of this approach is to extend
> > > > pg_get_publication_table() so that it can accept a relid to get the publication
> > > > information of the specific table. I've attached the patch for this idea. I'm
> > > > going to add regression test cases.
> > > >
> > > > pg_get_publication_table() is a VARIACID array function so the patch changes
> > > > its signature to {text[] [, oid]}, breaking the tool compatibility. Given this
> > > > function is mostly an internal-use function (we don't have the documentation
> > > > for it), it would probably be okay with it. I find it's clearer than the other
> > > > approach of introducing pg_get_publication_table_info(). Feedback is very
> > > > welcome.
> > >
> > > Thanks for updating the patch.
> > >
> > > I have few comments for the function change:
> > >
> > > 1.
> > >
> > > If we change the function signature, will it affect use cases where the
> > > publisher version is newer and the subscriber version is older ? E.g., when
> > > publisher is passing text style publication name to pg_get_publication_tables().
> >
> > Good point.
> >
> > I noticed that changing the function signature of
> > pg_get_publication_tables() breaks logical replication setups where
> > the subscriber is 18 or older.
> >
>
> Why adding a new function with additional parameters (Oid relid)
> couldn't help with such a case? I am asking because your previous
> version code looks simpler as compared to the new patch version.

I tried to pass a relid to pg_get_publication_tables() but we cannot
avoid changing its signature because it's a VARIADIC array function.
The previous patch changed pg_get_publication_tables(VARIADIC text[])
to pg_get_publication_tables(text[] {, relid}). However, changing the
function signature would break the logical replication from v19 to an
older version.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Jan Wieck <jan@wi3ck.info>
Дата:
On 3/18/26 12:44, Masahiko Sawada wrote:
> On Wed, Mar 18, 2026 at 6:56 AM Amit Kapila  wrote:
>>
>> On Tue, Mar 10, 2026 at 3:40 AM Masahiko Sawada  wrote:
>> >
>> > On Tue, Mar 3, 2026 at 2:22 AM Zhijie Hou (Fujitsu)
>> >  wrote:
>> > >
>> > > On Saturday, February 28, 2026 7:48 AM Masahiko Sawada  wrote:
>> > > > To: Marcos Pegoraro 
>> > > > Cc: PostgreSQL Hackers 
>> > > > Subject: Re: Initial COPY of Logical Replication is too slow
>> > > >
>> > > > Another variant of this approach is to extend
>> > > > pg_get_publication_table() so that it can accept a relid to get the publication
>> > > > information of the specific table. I've attached the patch for this idea. I'm
>> > > > going to add regression test cases.
>> > > >
>> > > > pg_get_publication_table() is a VARIACID array function so the patch changes
>> > > > its signature to {text[] [, oid]}, breaking the tool compatibility. Given this
>> > > > function is mostly an internal-use function (we don't have the documentation
>> > > > for it), it would probably be okay with it. I find it's clearer than the other
>> > > > approach of introducing pg_get_publication_table_info(). Feedback is very
>> > > > welcome.
>> > >
>> > > Thanks for updating the patch.
>> > >
>> > > I have few comments for the function change:
>> > >
>> > > 1.
>> > >
>> > > If we change the function signature, will it affect use cases where the
>> > > publisher version is newer and the subscriber version is older ? E.g., when
>> > > publisher is passing text style publication name to pg_get_publication_tables().
>> >
>> > Good point.
>> >
>> > I noticed that changing the function signature of
>> > pg_get_publication_tables() breaks logical replication setups where
>> > the subscriber is 18 or older.
>> >
>>
>> Why adding a new function with additional parameters (Oid relid)
>> couldn't help with such a case? I am asking because your previous
>> version code looks simpler as compared to the new patch version.
> 
> I tried to pass a relid to pg_get_publication_tables() but we cannot
> avoid changing its signature because it's a VARIADIC array function.
> The previous patch changed pg_get_publication_tables(VARIADIC text[])
> to pg_get_publication_tables(text[] {, relid}). However, changing the
> function signature would break the logical replication from v19 to an
> older version.

Would it be possible to use function overloading to provide both 
signatures handled by different C functions internally?


Best Regards, Jan



Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Wed, Mar 18, 2026 at 1:11 PM Jan Wieck  wrote:
>
> On 3/18/26 12:44, Masahiko Sawada wrote:
> > On Wed, Mar 18, 2026 at 6:56 AM Amit Kapila  wrote:
> >>
> >> On Tue, Mar 10, 2026 at 3:40 AM Masahiko Sawada  wrote:
> >> >
> >> > On Tue, Mar 3, 2026 at 2:22 AM Zhijie Hou (Fujitsu)
> >> >  wrote:
> >> > >
> >> > > On Saturday, February 28, 2026 7:48 AM Masahiko Sawada  wrote:
> >> > > > To: Marcos Pegoraro 
> >> > > > Cc: PostgreSQL Hackers 
> >> > > > Subject: Re: Initial COPY of Logical Replication is too slow
> >> > > >
> >> > > > Another variant of this approach is to extend
> >> > > > pg_get_publication_table() so that it can accept a relid to get the publication
> >> > > > information of the specific table. I've attached the patch for this idea. I'm
> >> > > > going to add regression test cases.
> >> > > >
> >> > > > pg_get_publication_table() is a VARIACID array function so the patch changes
> >> > > > its signature to {text[] [, oid]}, breaking the tool compatibility. Given this
> >> > > > function is mostly an internal-use function (we don't have the documentation
> >> > > > for it), it would probably be okay with it. I find it's clearer than the other
> >> > > > approach of introducing pg_get_publication_table_info(). Feedback is very
> >> > > > welcome.
> >> > >
> >> > > Thanks for updating the patch.
> >> > >
> >> > > I have few comments for the function change:
> >> > >
> >> > > 1.
> >> > >
> >> > > If we change the function signature, will it affect use cases where the
> >> > > publisher version is newer and the subscriber version is older ? E.g., when
> >> > > publisher is passing text style publication name to pg_get_publication_tables().
> >> >
> >> > Good point.
> >> >
> >> > I noticed that changing the function signature of
> >> > pg_get_publication_tables() breaks logical replication setups where
> >> > the subscriber is 18 or older.
> >> >
> >>
> >> Why adding a new function with additional parameters (Oid relid)
> >> couldn't help with such a case? I am asking because your previous
> >> version code looks simpler as compared to the new patch version.
> >
> > I tried to pass a relid to pg_get_publication_tables() but we cannot
> > avoid changing its signature because it's a VARIADIC array function.
> > The previous patch changed pg_get_publication_tables(VARIADIC text[])
> > to pg_get_publication_tables(text[] {, relid}). However, changing the
> > function signature would break the logical replication from v19 to an
> > older version.
>
> Would it be possible to use function overloading to provide both
> signatures handled by different C functions internally?

Yes, we can define both pg_get_publication_tables(VARIADIC text[]) and
pg_get_publication_tables(text, oid), which seems like a less invasive
approach. I'll give this idea a shot and see how it goes.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Wed, Mar 18, 2026 at 3:31 PM Masahiko Sawada  wrote:
>
> On Wed, Mar 18, 2026 at 1:11 PM Jan Wieck  wrote:
> >
> > On 3/18/26 12:44, Masahiko Sawada wrote:
> > > On Wed, Mar 18, 2026 at 6:56 AM Amit Kapila  wrote:
> > >>
> > >> On Tue, Mar 10, 2026 at 3:40 AM Masahiko Sawada  wrote:
> > >> >
> > >> > On Tue, Mar 3, 2026 at 2:22 AM Zhijie Hou (Fujitsu)
> > >> >  wrote:
> > >> > >
> > >> > > On Saturday, February 28, 2026 7:48 AM Masahiko Sawada  wrote:
> > >> > > > To: Marcos Pegoraro 
> > >> > > > Cc: PostgreSQL Hackers 
> > >> > > > Subject: Re: Initial COPY of Logical Replication is too slow
> > >> > > >
> > >> > > > Another variant of this approach is to extend
> > >> > > > pg_get_publication_table() so that it can accept a relid to get the publication
> > >> > > > information of the specific table. I've attached the patch for this idea. I'm
> > >> > > > going to add regression test cases.
> > >> > > >
> > >> > > > pg_get_publication_table() is a VARIACID array function so the patch changes
> > >> > > > its signature to {text[] [, oid]}, breaking the tool compatibility. Given this
> > >> > > > function is mostly an internal-use function (we don't have the documentation
> > >> > > > for it), it would probably be okay with it. I find it's clearer than the other
> > >> > > > approach of introducing pg_get_publication_table_info(). Feedback is very
> > >> > > > welcome.
> > >> > >
> > >> > > Thanks for updating the patch.
> > >> > >
> > >> > > I have few comments for the function change:
> > >> > >
> > >> > > 1.
> > >> > >
> > >> > > If we change the function signature, will it affect use cases where the
> > >> > > publisher version is newer and the subscriber version is older ? E.g., when
> > >> > > publisher is passing text style publication name to pg_get_publication_tables().
> > >> >
> > >> > Good point.
> > >> >
> > >> > I noticed that changing the function signature of
> > >> > pg_get_publication_tables() breaks logical replication setups where
> > >> > the subscriber is 18 or older.
> > >> >
> > >>
> > >> Why adding a new function with additional parameters (Oid relid)
> > >> couldn't help with such a case? I am asking because your previous
> > >> version code looks simpler as compared to the new patch version.
> > >
> > > I tried to pass a relid to pg_get_publication_tables() but we cannot
> > > avoid changing its signature because it's a VARIADIC array function.
> > > The previous patch changed pg_get_publication_tables(VARIADIC text[])
> > > to pg_get_publication_tables(text[] {, relid}). However, changing the
> > > function signature would break the logical replication from v19 to an
> > > older version.
> >
> > Would it be possible to use function overloading to provide both
> > signatures handled by different C functions internally?
>
> Yes, we can define both pg_get_publication_tables(VARIADIC text[]) and
> pg_get_publication_tables(text, oid), which seems like a less invasive
> approach. I'll give this idea a shot and see how it goes.

I've attached the patch to implement this idea. The patch still
introduces a new function but it overloads
pg_get_publication_tables(). We might be able to handle different
input (array or text) in pg_get_publication_tables() better, but it's
enough for discussion at least.

Regards,

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

Re: Initial COPY of Logical Replication is too slow

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

On Wed, Mar 18, 2026 at 4:29 PM Masahiko Sawada  wrote:
>
> I've attached the patch to implement this idea. The patch still
> introduces a new function but it overloads
> pg_get_publication_tables(). We might be able to handle different
> input (array or text) in pg_get_publication_tables() better, but it's
> enough for discussion at least.

Overall, the intent of this patch looks good to me. It avoids the cost
of the table sync worker querying all the pg_publication_rel tables to
filter them out later in the join.

I quickly reviewed the patch and here are some comments:

1/ Typo: s/pg_get_publication_table_info/pg_get_publication_tables

2/ I think it's good to have some quick numbers on how the query
latency looks for pre-V19 and the new one that the table sync worker
executes on the publisher, say, with 100, 1000, and 10000 tables at
least.

3/ + Assert(OidIsValid(target_relid));

Why not error out (by treating it as function input parameter
validation) when target_relid is invalid because asserts go unnoticed
on production systems?

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


Re: Initial COPY of Logical Replication is too slow

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
On Thu, Mar 19, 2026 at 10:30 AM Masahiko Sawada  wrote:
>
> I've attached the patch to implement this idea. The patch still
> introduces a new function but it overloads
> pg_get_publication_tables(). We might be able to handle different
> input (array or text) in pg_get_publication_tables() better, but it's
> enough for discussion at least.
>

The patch looks like a good performance improvement. Some minor comments:

1. src/test/regress/expected/publication.out

+-- Clean up
+DROP FUNCTION test_gpt(text[], relname);
+ERROR:  type "relname" does not exist

Cleanup actually fails. Second parameter should be text, not relname.

2. src/include/catalog/pg_proc.dat

+  proallargtypes => '{text,oid,oid,oid,int2vector,pg_node_tree}',
+  proargmodes => '{i,i,o,o,o,o}',
+  proargnames => '{pubname,relid,pubid,relid,attrs,qual}',

Having two arguments with the same name "relid" seems odd, although
one is input and other is output parameter, how about calling input
parameter as target_relid?

3. src/backend/replication/logical/tablesync.c

+
+        if (server_version >= 190000)
+        {
+            /*
+             * We can pass relid to pg_get_publication_table_info() since
+             * version 19.
+             */
+            appendStringInfo(&cmd,
+                             "SELECT DISTINCT"

In multiple places in the code pg_get_publication_table_info() is
used, instead of pg_get_publication_tables()

thanks,
Ajin Cherian
Fujitsu Australia


Re: Initial COPY of Logical Replication is too slow

От:
Peter Smith <smithpb2250@gmail.com>
Дата:
Вложения:
Hi Sawada-San.

Here are some review comments for the v3-0001 test code.

======
src/test/regress/expected/publication.out

1.
+-- Clean up
+DROP FUNCTION test_gpt(text[], relname);
+ERROR:  type "relname" does not exist

This seems a mistake. If the DROP FUNCTION was differently written
there there would be no error. PSA.

======
src/test/regress/sql/publication.sql

2.
+SELECT * FROM test_gpt('pub_normal', 'tbl_normal');
+SELECT * FROM test_gpt('pub_schema', 'tbl_normal'); -- no result

These tests seem strangely different from all the others because
everything else has both a "good result" test and a "no result" test
for every publication.

So I think there should be a "no result" test for 'pub_normal'

So I think there should be a "good result" test for 'pub_schema'

~~~

3.
Consider renaming that 'tbl_parent' to something like 'tbl_root'.
because 'parent' always makes me think of INHERITED parent/child
tables, rather than partitioned tables and their partitions. If you do
this, then you might also want to tweak several publication names --
e.g. 'pub_part_parent' -> 'pub_part_root'

~~~

PSA a diff file that makes those suggested changes #1 and #2.

======
Kind Regards,
Peter Smith.
Fujitsu Australia

Re: Initial COPY of Logical Replication is too slow

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Mar 19, 2026 at 4:59 AM Masahiko Sawada  wrote:
>
> On Wed, Mar 18, 2026 at 3:31 PM Masahiko Sawada  wrote:
> >
>
> I've attached the patch to implement this idea. The patch still
> introduces a new function but it overloads
> pg_get_publication_tables(). We might be able to handle different
> input (array or text) in pg_get_publication_tables() better, but it's
> enough for discussion at least.
>

*
+ /*
+ * We can pass relid to pg_get_publication_table_info() since
+ * version 19.
+ */
+ appendStringInfo(&cmd,
+ "SELECT DISTINCT"
+ "  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)"
+ "   THEN NULL ELSE gpt.attrs END)"
+ "  FROM pg_publication p,"
+ "  LATERAL pg_get_publication_tables(p.pubname, %u) gpt,"
+ "  pg_class c"
+ " WHERE c.oid = gpt.relid"
+ "   AND p.pubname IN ( %s )",
+ lrel->remoteid,
+ pub_names->data);

Why in the above query we need a join with pg_publication? Can't we
directly pass 'pub_names' and 'relid' to pg_get_publication_tables()
to get the required information?


--
With Regards,
Amit Kapila.


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Mar 23, 2026 at 5:54 PM Bharath Rupireddy
 wrote:
>
> Hi,
>
> On Wed, Mar 18, 2026 at 4:29 PM Masahiko Sawada  wrote:
> >
> > I've attached the patch to implement this idea. The patch still
> > introduces a new function but it overloads
> > pg_get_publication_tables(). We might be able to handle different
> > input (array or text) in pg_get_publication_tables() better, but it's
> > enough for discussion at least.
>
> Overall, the intent of this patch looks good to me. It avoids the cost
> of the table sync worker querying all the pg_publication_rel tables to
> filter them out later in the join.
>
> I quickly reviewed the patch and here are some comments:

Thank you for reviewing the patch!

>
> 1/ Typo: s/pg_get_publication_table_info/pg_get_publication_tables

Fixed.

>
> 2/ I think it's good to have some quick numbers on how the query
> latency looks for pre-V19 and the new one that the table sync worker
> executes on the publisher, say, with 100, 1000, and 10000 tables at
> least.

You can refer to the performance test results that I previously
shared[1]. The patch I used was somewhat different from the current
patch but the performance trend should be similar as the both are
using the same approach.

>
> 3/ + Assert(OidIsValid(target_relid));
>
> Why not error out (by treating it as function input parameter
> validation) when target_relid is invalid because asserts go unnoticed
> on production systems?

Agreed. It would return no row if the specified relid is invalid or
there is no corresponding table.

I'll share the updated patch soon.

Regards,

[1] https://www.postgresql.org/message-id/CAD21AoDQM62GOtaTzD_CVMSsFhv6o9c0Au1dSM1QuxeKFkWAKw%40mail.gmail.com

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Mar 23, 2026 at 11:54 PM Ajin Cherian  wrote:
>
> On Thu, Mar 19, 2026 at 10:30 AM Masahiko Sawada  wrote:
> >
> > I've attached the patch to implement this idea. The patch still
> > introduces a new function but it overloads
> > pg_get_publication_tables(). We might be able to handle different
> > input (array or text) in pg_get_publication_tables() better, but it's
> > enough for discussion at least.
> >
>
> The patch looks like a good performance improvement. Some minor comments:
>
> 1. src/test/regress/expected/publication.out
>
> +-- Clean up
> +DROP FUNCTION test_gpt(text[], relname);
> +ERROR:  type "relname" does not exist
>
> Cleanup actually fails. Second parameter should be text, not relname.
>
> 2. src/include/catalog/pg_proc.dat
>
> +  proallargtypes => '{text,oid,oid,oid,int2vector,pg_node_tree}',
> +  proargmodes => '{i,i,o,o,o,o}',
> +  proargnames => '{pubname,relid,pubid,relid,attrs,qual}',
>
> Having two arguments with the same name "relid" seems odd, although
> one is input and other is output parameter, how about calling input
> parameter as target_relid?
>
> 3. src/backend/replication/logical/tablesync.c
>
> +
> +        if (server_version >= 190000)
> +        {
> +            /*
> +             * We can pass relid to pg_get_publication_table_info() since
> +             * version 19.
> +             */
> +            appendStringInfo(&cmd,
> +                             "SELECT DISTINCT"
>
> In multiple places in the code pg_get_publication_table_info() is
> used, instead of pg_get_publication_tables()

Thank you for reviewing the patch! I agree with all the above points.
I'll share the updated patch soon.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Mar 23, 2026 at 11:59 PM Peter Smith  wrote:
>
> Hi Sawada-San.
>
> Here are some review comments for the v3-0001 test code.

Thank you for reviewing the patch!

>
> ======
> src/test/regress/expected/publication.out
>
> 1.
> +-- Clean up
> +DROP FUNCTION test_gpt(text[], relname);
> +ERROR:  type "relname" does not exist
>
> This seems a mistake. If the DROP FUNCTION was differently written
> there there would be no error. PSA.

Fixed.

>
> ======
> src/test/regress/sql/publication.sql
>
> 2.
> +SELECT * FROM test_gpt('pub_normal', 'tbl_normal');
> +SELECT * FROM test_gpt('pub_schema', 'tbl_normal'); -- no result
>
> These tests seem strangely different from all the others because
> everything else has both a "good result" test and a "no result" test
> for every publication.
>
> So I think there should be a "no result" test for 'pub_normal'
>
> So I think there should be a "good result" test for 'pub_schema'

Added.

>
> ~~~
>
> 3.
> Consider renaming that 'tbl_parent' to something like 'tbl_root'.
> because 'parent' always makes me think of INHERITED parent/child
> tables, rather than partitioned tables and their partitions. If you do
> this, then you might also want to tweak several publication names --
> e.g. 'pub_part_parent' -> 'pub_part_root'

Hmm, there are already some queries using 'parent' in the same .sql
file. I'll leave these names.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Tue, Mar 24, 2026 at 3:47 AM Amit Kapila  wrote:
>
> On Thu, Mar 19, 2026 at 4:59 AM Masahiko Sawada  wrote:
> >
> > On Wed, Mar 18, 2026 at 3:31 PM Masahiko Sawada  wrote:
> > >
> >
> > I've attached the patch to implement this idea. The patch still
> > introduces a new function but it overloads
> > pg_get_publication_tables(). We might be able to handle different
> > input (array or text) in pg_get_publication_tables() better, but it's
> > enough for discussion at least.
> >
>
> *
> + /*
> + * We can pass relid to pg_get_publication_table_info() since
> + * version 19.
> + */
> + appendStringInfo(&cmd,
> + "SELECT DISTINCT"
> + "  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)"
> + "   THEN NULL ELSE gpt.attrs END)"
> + "  FROM pg_publication p,"
> + "  LATERAL pg_get_publication_tables(p.pubname, %u) gpt,"
> + "  pg_class c"
> + " WHERE c.oid = gpt.relid"
> + "   AND p.pubname IN ( %s )",
> + lrel->remoteid,
> + pub_names->data);
>
> Why in the above query we need a join with pg_publication? Can't we
> directly pass 'pub_names' and 'relid' to pg_get_publication_tables()
> to get the required information?

Since the 'pub_names' is the list of publication names we cannot
directly pass it to the pg_get_publication_tables(). But if we make
pg_get_publication_tables() take {pubname text[], target_relid oid}
instead of {pubname text, target_relid oid}, yes. And it seems to help
somewhat simplify the patch. If having both
pg_get_publication_tables(VARIADIC text[]) and
pg_get_publication_tables(text[], oid) is not odd, it would be worth
trying it.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Tue, Mar 24, 2026 at 11:57 AM Masahiko Sawada  wrote:
>
> On Tue, Mar 24, 2026 at 3:47 AM Amit Kapila  wrote:
> >
> > On Thu, Mar 19, 2026 at 4:59 AM Masahiko Sawada  wrote:
> > >
> > > On Wed, Mar 18, 2026 at 3:31 PM Masahiko Sawada  wrote:
> > > >
> > >
> > > I've attached the patch to implement this idea. The patch still
> > > introduces a new function but it overloads
> > > pg_get_publication_tables(). We might be able to handle different
> > > input (array or text) in pg_get_publication_tables() better, but it's
> > > enough for discussion at least.
> > >
> >
> > *
> > + /*
> > + * We can pass relid to pg_get_publication_table_info() since
> > + * version 19.
> > + */
> > + appendStringInfo(&cmd,
> > + "SELECT DISTINCT"
> > + "  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)"
> > + "   THEN NULL ELSE gpt.attrs END)"
> > + "  FROM pg_publication p,"
> > + "  LATERAL pg_get_publication_tables(p.pubname, %u) gpt,"
> > + "  pg_class c"
> > + " WHERE c.oid = gpt.relid"
> > + "   AND p.pubname IN ( %s )",
> > + lrel->remoteid,
> > + pub_names->data);
> >
> > Why in the above query we need a join with pg_publication? Can't we
> > directly pass 'pub_names' and 'relid' to pg_get_publication_tables()
> > to get the required information?
>
> Since the 'pub_names' is the list of publication names we cannot
> directly pass it to the pg_get_publication_tables(). But if we make
> pg_get_publication_tables() take {pubname text[], target_relid oid}
> instead of {pubname text, target_relid oid}, yes. And it seems to help
> somewhat simplify the patch. If having both
> pg_get_publication_tables(VARIADIC text[]) and
> pg_get_publication_tables(text[], oid) is not odd, it would be worth
> trying it.
>

I figured out that the join with pg_publication works as a filter;
non-existence publication names are not passed to the function. If we
pass the list of publication names to the new function signature,
while we can simplify the patch and avoid a join, we would change the
existing function behavior so that it ignores non-existence
publications.

I've attached the updated patch. The 0001 patch just incorporated the
review comments so far, and the 0002 patch is a draft change for the
above idea. Since pg_get_publication_tables(VARIADIC text) is not a
documented function, I think we can accept small behavior changes. So
I'm going to go with this direction. Feedback is very welcome.

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

Re: Initial COPY of Logical Replication is too slow

От:
Peter Smith <smithpb2250@gmail.com>
Дата:
Hi Swada-San. Here are some minor review comments for v4-0001/2 combined.

======
src/backend/catalog/pg_publication.c

is_table_publishable_in_publication:

1.
This function logic has a format like

if (cond)
{
 ...
 return;
}

if (cond2)
{
 ...
 return;
}

etc.

There are many return points, and most of those "if" blocks cannot
fall through (they return).

I found it slightly difficult to read the code because I kept having
to think, "OK, if we reached here, it means pubviaroot must be false,"
or "OK, if we reached this far, then puballtables must be false, and
pubviaroot must be false," etc.

Maybe a few more if/else, or a few Assert() can make it easier to
understand how we reached points deeper in this function.

~~~

pg_get_publication_tables:

2.
Several code comments appear to wrap prematurely. It looks as if
pg_indent was run when the code was different to what it is now.

~~~

pg_get_publication_tables_b:

3.
  /* Get the information of the specified table in the given publication */
- return pg_get_publication_tables(fcinfo, NULL, PG_GETARG_TEXT_P(0),
PG_GETARG_OID(1));
+ return pg_get_publication_tables(fcinfo, PG_GETARG_ARRAYTYPE_P(0), relid);

Should that comment be plural now, the same as the other one?
/publication/publications/

======
src/include/catalog/pg_proc.dat

4.
proargnames => '{pubname,pubid,relid,attrs,qual}',
prosrc => 'pg_get_publication_tables_a' },

Shouldn’t the original function proargnames here also be calling the
first arg 'pubnames' instead of 'pubname'

======
src/test/regress/sql/publication.sql

5.
-- Test pg_get_publication_tables(text, oid) function

Should that comment now say text[] instead of text?

~~~

6.
Many of those tests have a "good result" test and a "no result" test
for each publication. It might be better if they were consistently in
the same order (eg, good then none, or none then good).

~~~

7.
Only 3 of the tests are passing multiple publications. Maybe those can
be separated from the others (e.g. put last, just to keep all the ones
that look alike together).

======
Kind Regards,
Peter Smith.
Fujitsu Australia


RE: Initial COPY of Logical Replication is too slow

От:
"Zhijie Hou (Fujitsu)" <houzj.fnst@fujitsu.com>
Дата:
On Wednesday, March 25, 2026 2:07 PM Masahiko Sawada  wrote:
> On Tue, Mar 24, 2026 at 11:57 AM Masahiko Sawada
> 
> I figured out that the join with pg_publication works as a filter; non-existence
> publication names are not passed to the function. If we pass the list of
> publication names to the new function signature, while we can simplify the
> patch and avoid a join, we would change the existing function behavior so that
> it ignores non-existence publications.
> 
> I've attached the updated patch. The 0001 patch just incorporated the review
> comments so far, and the 0002 patch is a draft change for the above idea. Since
> pg_get_publication_tables(VARIADIC text) is not a documented function, I think
> we can accept small behavior changes. So I'm going to go with this direction.
> Feedback is very welcome.

Thanks for updating the patches. I have few comments for 0001:

1.

+ * specific table. Otherwise, if returns information for all tables within the
+ * specified publications.

if => it

2.

I think the function shall reject relids that do not reference a valid
publishable table (e.g., sequences, views, or materialized views).

3.

With publish_via_root = true, when both a partitioned table and its child are in
a publication, I expected passing the child's relid will return NULL (changes are
published via the root). Currently it returns the child's relid:

CREATE TABLE sales (
    id SERIAL,
    sale_date DATE NOT NULL
) PARTITION BY RANGE (sale_date);

CREATE TABLE sales_2024_q1 PARTITION OF sales
FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');

CREATE publication pub for table sales, sales_2024_q1 with ( publish_via_partition_root );

select pg_get_publication_tables('pub', 'sales_2024_q1'::regclass);

Best Regards,
Hou zj

RE: Initial COPY of Logical Replication is too slow

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Вложения:
Dear Sawada-san,
(Sending again because blocked by some rules)

I ran the performance testing independently for the 0001 patch. Overall performance looked
very nice, new function spent O(1) time based on the total number of tables.
It seems good enough.

Source code:
----------------
HEAD (4287c50f) + v4-0001 patch.

Setup:
---------
A database cluster was set up with shared_buffers=100GB. Several tables were
defined on the public schema, and same number of tables were on the sch1.
Total number of tables were {50, 500, 5000, 50000}.
A publication included a schema sch1 and all public tables individually.

Attached script setup the same. The suffix is changed to .txt to pass the rule.

Workload Run:
--------------------
I ran two types of SQLs and measured the execution time via \timing metacommand.
Cases were emulated which tablesync worker would do.

Case 1: old SQL
```
SELECT DISTINCT
  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)
   THEN NULL ELSE gpt.attrs END)
  FROM pg_publication p,
  LATERAL pg_get_publication_tables(p.pubname) gpt,
  pg_class c
 WHERE gpt.relid = 17885 AND c.oid = gpt.relid
   AND p.pubname IN ( 'pub' );
```

Case 2: new SQL
```
SELECT DISTINCT
  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)
   THEN NULL ELSE gpt.attrs END)
  FROM pg_publication p,
  LATERAL pg_get_publication_tables(p.pubname, 16535) gpt,
  pg_class c
 WHERE c.oid = gpt.relid
   AND p.pubname IN ( 'pub' );
```

Result Observations:
---------------
Attached bar graph shows the result. A logarithmic scale is used for the execution
time (y-axis) to see both small/large scale case. The spent time became approximately
10x longer for 500->5000, and 5000->50000, in case of old SQL is used.
Apart from that, the spent time for the new SQL is mostly the stable based on the
number of tables.

Detailed Result:
--------------
Each cell are the median of 10 runs.

Total tables	Execution time for the old SQL was done [ms]	Execution time for the old SQL was done [ms]
50		5.77						4.19
500		15.75						4.28
5000		120.39						4.22
50000		1741.89						4.60
500000		73287.16					4.95


Also, here is a small code comment. I think we can have an Assert at the
begining of the pg_get_publication_tables(), something like below.

```
@@ -1392,6 +1392,9 @@ pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
        FuncCallContext *funcctx;
        List       *table_infos = NIL;
 
+       Assert((pubnames && (!pubname && !OidIsValid(target_relid))) ||
+                  (!pubnames && (pubname && OidIsValid(target_relid))));
```

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: Initial COPY of Logical Replication is too slow

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Mar 25, 2026 at 10:37 AM Masahiko Sawada  wrote:
>
> I figured out that the join with pg_publication works as a filter;
> non-existence publication names are not passed to the function. If we
> pass the list of publication names to the new function signature,
> while we can simplify the patch and avoid a join, we would change the
> existing function behavior so that it ignores non-existence
> publications.
>
> I've attached the updated patch. The 0001 patch just incorporated the
> review comments so far, and the 0002 patch is a draft change for the
> above idea. Since pg_get_publication_tables(VARIADIC text) is not a
> documented function, I think we can accept small behavior changes. So
> I'm going to go with this direction.
>

What behaviour change are you referring to? In general, the direction
appears right to me.

-- 
With Regards,
Amit Kapila.


RE: Initial COPY of Logical Replication is too slow

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Вложения:
> I ran the performance testing independently for the 0001 patch. Overall
> performance looked
> very nice, new function spent O(1) time based on the total number of tables.
> It seems good enough.

...and I tested 0002 as well with the same settings, and the trend was the same as 0001.

Both 0001 and 0002 were applied and below SQL was run, which was same was what
tablesync worker would try:

```
SELECT DISTINCT
  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)
   THEN NULL ELSE gpt.attrs END)
  FROM pg_get_publication_tables(ARRAY['pub'], 16535) gpt,
  pg_class c
 WHERE c.oid = gpt.relid;
```

And below is the result. Each cell shows the execution time of the SQL. HEAD
column is the case when [1] was done. 0001 column is the case for [2].
Looks like the SQL used by 0002 looks slightly faster, which is same as the
expectation. JOIN was removed once.

Total tables	HEAD [ms]	0001 [ms]	0001 + 0002 [ms]
50		5.77		4.19		3.74
500		15.75		4.28		3.76
5000		120.39		4.22		3.79
50000		1741.89		4.60		4.11
500000		73287.16	4.95		4.38

Attached graph visualized the table.

[1]:
```
SELECT DISTINCT
  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)
   THEN NULL ELSE gpt.attrs END)
  FROM pg_publication p,
  LATERAL pg_get_publication_tables(p.pubname) gpt,
  pg_class c
 WHERE gpt.relid = 17885 AND c.oid = gpt.relid
   AND p.pubname IN ( 'pub' );
```

[2]:
```
SELECT DISTINCT
  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)
   THEN NULL ELSE gpt.attrs END)
  FROM pg_publication p,
  LATERAL pg_get_publication_tables(p.pubname, 16535) gpt,
  pg_class c
 WHERE c.oid = gpt.relid
   AND p.pubname IN ( 'pub' );
```

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Thu, Mar 26, 2026 at 3:44 AM Amit Kapila  wrote:
>
> On Wed, Mar 25, 2026 at 10:37 AM Masahiko Sawada  wrote:
> >
> > I figured out that the join with pg_publication works as a filter;
> > non-existence publication names are not passed to the function. If we
> > pass the list of publication names to the new function signature,
> > while we can simplify the patch and avoid a join, we would change the
> > existing function behavior so that it ignores non-existence
> > publications.
> >
> > I've attached the updated patch. The 0001 patch just incorporated the
> > review comments so far, and the 0002 patch is a draft change for the
> > above idea. Since pg_get_publication_tables(VARIADIC text) is not a
> > documented function, I think we can accept small behavior changes. So
> > I'm going to go with this direction.
> >
>
> What behaviour change are you referring to? In general, the direction
> appears right to me.

When passing a non-existent publication name, the current behavior
raises an error while the new behavior does nothing (i.e., the
difference is calling GetPublicationByName() with missing_ok = true or
false).

Regards,

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


RE: Initial COPY of Logical Replication is too slow

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Sawada-san,

> When passing a non-existent publication name, the current behavior
> raises an error while the new behavior does nothing (i.e., the
> difference is calling GetPublicationByName() with missing_ok = true or
> false).

To confirm; It's because in PG18-, p.pubname was chosen from the pg_publication
in the publisher, but this patch the name list is taken from the subscriber, right?
If some publications are dropped on the publisher, the ERROR could be raised.

For the backward compatibility I suggest switching the policy based on the API
version. E.g.,

```
 static Datum
 pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
-                                                 Oid target_relid)
+                                                 Oid target_relid, bool missing_ok)
...
@@ -1631,7 +1631,7 @@ Datum
 pg_get_publication_tables_a(PG_FUNCTION_ARGS)
 {
        /* Get the information of the tables in the given publications */
-       return pg_get_publication_tables(fcinfo, PG_GETARG_ARRAYTYPE_P(0), InvalidOid);
+       return pg_get_publication_tables(fcinfo, PG_GETARG_ARRAYTYPE_P(0), InvalidOid, false);
```

Another comment for publication.sql.

```
-- Clean up
DROP FUNCTION test_gpt(text, text);
```

It should be test_gpt(text[], text);

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: Initial COPY of Logical Replication is too slow

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Fri, Mar 27, 2026 at 8:46 AM Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Sawada-san,
>
> > When passing a non-existent publication name, the current behavior
> > raises an error while the new behavior does nothing (i.e., the
> > difference is calling GetPublicationByName() with missing_ok = true or
> > false).
>
> To confirm; It's because in PG18-, p.pubname was chosen from the pg_publication
> in the publisher, but this patch the name list is taken from the subscriber, right?
> If some publications are dropped on the publisher, the ERROR could be raised.
>
> For the backward compatibility I suggest switching the policy based on the API
> version. E.g.,
>
> ```
>  static Datum
>  pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
> -                                                 Oid target_relid)
> +                                                 Oid target_relid, bool missing_ok)
> ...
> @@ -1631,7 +1631,7 @@ Datum
>  pg_get_publication_tables_a(PG_FUNCTION_ARGS)
>  {
>         /* Get the information of the tables in the given publications */
> -       return pg_get_publication_tables(fcinfo, PG_GETARG_ARRAYTYPE_P(0), InvalidOid);
> +       return pg_get_publication_tables(fcinfo, PG_GETARG_ARRAYTYPE_P(0), InvalidOid, false);
> ```
>

Sounds like a good idea for backward compatibility.

-- 
With Regards,
Amit Kapila.


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Thu, Mar 26, 2026 at 8:51 PM Amit Kapila  wrote:
>
> On Fri, Mar 27, 2026 at 8:46 AM Hayato Kuroda (Fujitsu)
>  wrote:
> >
> > Dear Sawada-san,
> >
> > > When passing a non-existent publication name, the current behavior
> > > raises an error while the new behavior does nothing (i.e., the
> > > difference is calling GetPublicationByName() with missing_ok = true or
> > > false).
> >
> > To confirm; It's because in PG18-, p.pubname was chosen from the pg_publication
> > in the publisher, but this patch the name list is taken from the subscriber, right?
> > If some publications are dropped on the publisher, the ERROR could be raised.
> >
> > For the backward compatibility I suggest switching the policy based on the API
> > version. E.g.,
> >
> > ```
> >  static Datum
> >  pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
> > -                                                 Oid target_relid)
> > +                                                 Oid target_relid, bool missing_ok)
> > ...
> > @@ -1631,7 +1631,7 @@ Datum
> >  pg_get_publication_tables_a(PG_FUNCTION_ARGS)
> >  {
> >         /* Get the information of the tables in the given publications */
> > -       return pg_get_publication_tables(fcinfo, PG_GETARG_ARRAYTYPE_P(0), InvalidOid);
> > +       return pg_get_publication_tables(fcinfo, PG_GETARG_ARRAYTYPE_P(0), InvalidOid, false);
> > ```
> >
>
> Sounds like a good idea for backward compatibility.

+1.

I've attached the updated patch. I believe I've addressed all comments
I got so far. In addition to that, I've refactored
is_table_publishable_in_publication() and added more regression tests.

Regards,

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

Re: Initial COPY of Logical Replication is too slow

От:
Marcos Pegoraro <marcos@f10.com.br>
Дата:
Em sex., 27 de mar. de 2026 às 03:20, Masahiko Sawada <sawada.mshk@gmail.com> escreveu:
I've attached the updated patch. I believe I've addressed all comments
I got so far. In addition to that, I've refactored
is_table_publishable_in_publication() and added more regression tests.

Today I had to create a few more schemas and see that problem again, how the publisher is affected, almost crashing due to the overload. 
That was because max_sync_workers_per_subscription was set to 10, which caused 10 simultaneous connections to call this function immediately after the refresh publication command. 
Wouldn't it be good to document on this GUC that if your publisher server is running version <= 18 then is it advisable to set this GUC to a really low value ?
Because ok, version 19 is fine, will be covered, but all publisher servers that are not updated will continue to have this trouble.
The publisher will be severely penalized when the subscription refreshes its publication.

What do you think, change something on DOCs too ?

regards
Marcos

RE: Initial COPY of Logical Replication is too slow

От:
"Zhijie Hou (Fujitsu)" <houzj.fnst@fujitsu.com>
Дата:
On Friday, March 27, 2026 2:20 PM Masahiko Sawada  wrote:
> I've attached the updated patch. I believe I've addressed all comments I got
> so far. In addition to that, I've refactored
> is_table_publishable_in_publication() and added more regression tests.

Thanks for updating the patch.

The latest patch looks mostly good to me. However, I noticed one issue: the
function returns table information even for unlogged or temporary tables. I
think we should return NULL for those cases instead.

BTW, I think we could use is_publishable_class() as a reference to check once
whether all unpublishable table types are properly ignored in this function.

Best Regards,
Hou zj

RE: Initial COPY of Logical Replication is too slow

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Sawada-san,

Thanks for updating the patch. I think the patch has a good shape.
Below contains minor comments.


```
+               if (filter_by_relid)
+                       relkind = get_rel_relkind(target_relid);
```

Can we return here if the relkind is not RELKIND_RELATION nor RELKIND_PARTITIONED_TABLE?
Key assumption here is that pg_get_publication_tables_b() returns at most one
tuple, thus this is would be called only once.

```
+       /*
+        * Non-alltables
+        */
+       if (relispartition)
```

else-if might be usalbe to clarify we're in the non-alltables case.

```
+               Assert(pubnames != NULL);
```

Personally I prefer to do Assert() before the SRF_FIRSTCALL_INIT(). Because it's
only related with argument and not related with other function calls.

```
+  proname => 'pg_get_publication_tables', prorows => '10',
```

Can prorows be 1? Because only a row would be returned here.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Thu, Mar 26, 2026 at 1:35 AM Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Sawada-san,
> (Sending again because blocked by some rules)
>
> I ran the performance testing independently for the 0001 patch. Overall performance looked
> very nice, new function spent O(1) time based on the total number of tables.
> It seems good enough.
>
> Source code:
> ----------------
> HEAD (4287c50f) + v4-0001 patch.
>
> Setup:
> ---------
> A database cluster was set up with shared_buffers=100GB. Several tables were
> defined on the public schema, and same number of tables were on the sch1.
> Total number of tables were {50, 500, 5000, 50000}.
> A publication included a schema sch1 and all public tables individually.
>
> Attached script setup the same. The suffix is changed to .txt to pass the rule.
>
> Workload Run:
> --------------------
> I ran two types of SQLs and measured the execution time via \timing metacommand.
> Cases were emulated which tablesync worker would do.
>
> Case 1: old SQL
> ```
> SELECT DISTINCT
>   (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)
>    THEN NULL ELSE gpt.attrs END)
>   FROM pg_publication p,
>   LATERAL pg_get_publication_tables(p.pubname) gpt,
>   pg_class c
>  WHERE gpt.relid = 17885 AND c.oid = gpt.relid
>    AND p.pubname IN ( 'pub' );
> ```
>
> Case 2: new SQL
> ```
> SELECT DISTINCT
>   (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)
>    THEN NULL ELSE gpt.attrs END)
>   FROM pg_publication p,
>   LATERAL pg_get_publication_tables(p.pubname, 16535) gpt,
>   pg_class c
>  WHERE c.oid = gpt.relid
>    AND p.pubname IN ( 'pub' );
> ```
>
> Result Observations:
> ---------------
> Attached bar graph shows the result. A logarithmic scale is used for the execution
> time (y-axis) to see both small/large scale case. The spent time became approximately
> 10x longer for 500->5000, and 5000->50000, in case of old SQL is used.
> Apart from that, the spent time for the new SQL is mostly the stable based on the
> number of tables.
>
> Detailed Result:
> --------------
> Each cell are the median of 10 runs.
>
> Total tables    Execution time for the old SQL was done [ms]    Execution time for the old SQL was done [ms]
> 50              5.77                                            4.19
> 500             15.75                                           4.28
> 5000            120.39                                          4.22
> 50000           1741.89                                         4.60
> 500000          73287.16                                        4.95

Thank you for doing the performance tests! These observation match the
results of my local performance test.

BTW the new is_table_publishable_in_publication() can be useful other
places too where we check if the particular table is published by the
publication, for example get-rel_sync_entry(). It would be a separate
patch though.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Mon, Mar 30, 2026 at 12:42 AM Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Sawada-san,
>
> Thanks for updating the patch. I think the patch has a good shape.
> Below contains minor comments.

Thank you for the comments!

>
>
> ```
> +               if (filter_by_relid)
> +                       relkind = get_rel_relkind(target_relid);
> ```
>
> Can we return here if the relkind is not RELKIND_RELATION nor RELKIND_PARTITIONED_TABLE?
> Key assumption here is that pg_get_publication_tables_b() returns at most one
> tuple, thus this is would be called only once.

Yeah, I refactored these logic and do the preliminary check before
checking the publications.

>
> ```
> +       /*
> +        * Non-alltables
> +        */
> +       if (relispartition)
> ```
>
> else-if might be usalbe to clarify we're in the non-alltables case.

Hmm, we have the return statement at the end of the if branch so we
don't necessarily need else-if. Adding a new line after the comment
might help readability.

>
> ```
> +               Assert(pubnames != NULL);
> ```
>
> Personally I prefer to do Assert() before the SRF_FIRSTCALL_INIT(). Because it's
> only related with argument and not related with other function calls.

If we move it before the SRF_FIRSTCALL_INIT(), we would end up
executing the assertion every time we call
pg_get_publication_table_b() since it could return more than one
tuple, which seems unnecessary to me. I think we can remove this
assertion because both _a() and _b() are strict functions.

>
> ```
> +  proname => 'pg_get_publication_tables', prorows => '10',
> ```
>
> Can prorows be 1? Because only a row would be returned here.
>

If multiple publications are specified, it could return more than one tuples.

I'll submit the updated patch soon.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Mon, Mar 30, 2026 at 12:16 AM Zhijie Hou (Fujitsu)
 wrote:
>
> On Friday, March 27, 2026 2:20 PM Masahiko Sawada  wrote:
> > I've attached the updated patch. I believe I've addressed all comments I got
> > so far. In addition to that, I've refactored
> > is_table_publishable_in_publication() and added more regression tests.
>
> Thanks for updating the patch.
>
> The latest patch looks mostly good to me. However, I noticed one issue: the
> function returns table information even for unlogged or temporary tables. I
> think we should return NULL for those cases instead.

Indeed. Good catch!

>
> BTW, I think we could use is_publishable_class() as a reference to check once
> whether all unpublishable table types are properly ignored in this function.
>

+1. I've added is_publishable_class() check.

I've attached the updated patch.

Regards,

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

Re:Re: Initial COPY of Logical Replication is too slow

От:
王好燕 <wanghaoyan20@163.com>
Дата:
At 2026-03-31 12:08:52, "Masahiko Sawada" <sawada.mshk@gmail.com> wrote:
>On Mon, Mar 30, 2026 at 12:16 AM Zhijie Hou (Fujitsu)
><houzj.fnst@fujitsu.com> wrote:
>>
>> On Friday, March 27, 2026 2:20 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>> > I've attached the updated patch. I believe I've addressed all comments I got
>> > so far. In addition to that, I've refactored
>> > is_table_publishable_in_publication() and added more regression tests.
>>
>> Thanks for updating the patch.
>>
>> The latest patch looks mostly good to me. However, I noticed one issue: the
>> function returns table information even for unlogged or temporary tables. I
>> think we should return NULL for those cases instead.
>
>Indeed. Good catch!
>
>>
>> BTW, I think we could use is_publishable_class() as a reference to check once
>> whether all unpublishable table types are properly ignored in this function.
>>
>
>+1. I've added is_publishable_class() check.
>
>I've attached the updated patch.
>
>Regards,
>
>-- 
>Masahiko Sawada
>Amazon Web Services: https://aws.amazon.com

Hi, thanks for the patch. I just reviewed v6, here comes some comments.

+/*
+ * Similar to is_publishable_calss() but checks whether the given OID
+ * is a publishable "table" or not.
+ */
+static bool
+is_publishable_table(Oid tableoid)
+{
+	HeapTuple	tuple;
+	Form_pg_class relform;
+
+	tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(tableoid));
+	if (!HeapTupleIsValid(tuple))
+		return false;
+
+	relform = (Form_pg_class) GETSTRUCT(tuple);
+
+	/*
+	 * Sequences are publishable according to is_publishable_class() so
+	 * explicitly exclude here.
+	 */
+	if (relform->relkind != RELKIND_SEQUENCE &&
+		is_publishable_class(tableoid, relform))
+	{
+		ReleaseSysCache(tuple);
+		return true;
+	}
+
+	ReleaseSysCache(tuple);
+	return true;
+}

I think the last return should return false.

+ * Similar to is_publishable_calss() but checks whether the given OID

“calss" should be “class”.

Re: Initial COPY of Logical Replication is too slow

От:
"Haoyan Wang" <wanghaoyan20@163.com>
Дата:
At 2026-03-31 14:15:18, "王好燕 " <wanghaoyan20@163.com> wrote:
At 2026-03-31 12:08:52, "Masahiko Sawada" <sawada.mshk@gmail.com> wrote:
>On Mon, Mar 30, 2026 at 12:16 AM Zhijie Hou (Fujitsu)
><houzj.fnst@fujitsu.com> wrote:
>>
>> On Friday, March 27, 2026 2:20 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
>> > I've attached the updated patch. I believe I've addressed all comments I got
>> > so far. In addition to that, I've refactored
>> > is_table_publishable_in_publication() and added more regression tests.
>>
>> Thanks for updating the patch.
>>
>> The latest patch looks mostly good to me. However, I noticed one issue: the
>> function returns table information even for unlogged or temporary tables. I
>> think we should return NULL for those cases instead.
>
>Indeed. Good catch!
>
>>
>> BTW, I think we could use is_publishable_class() as a reference to check once
>> whether all unpublishable table types are properly ignored in this function.
>>
>
>+1. I've added is_publishable_class() check.
>
>I've attached the updated patch.
>
>Regards,
>
>-- 
>Masahiko Sawada
>Amazon Web Services: https://aws.amazon.com

Hi, thanks for the patch. I just reviewed v6, here comes some comments.

+/*
+ * Similar to is_publishable_calss() but checks whether the given OID
+ * is a publishable "table" or not.
+ */
+static bool
+is_publishable_table(Oid tableoid)
+{
+	HeapTuple	tuple;
+	Form_pg_class relform;
+
+	tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(tableoid));
+	if (!HeapTupleIsValid(tuple))
+		return false;
+
+	relform = (Form_pg_class) GETSTRUCT(tuple);
+
+	/*
+	 * Sequences are publishable according to is_publishable_class() so
+	 * explicitly exclude here.
+	 */
+	if (relform->relkind != RELKIND_SEQUENCE &&
+		is_publishable_class(tableoid, relform))
+	{
+		ReleaseSysCache(tuple);
+		return true;
+	}
+
+	ReleaseSysCache(tuple);
+	return true;
+}

I think the last return should return false.

+ * Similar to is_publishable_calss() but checks whether the given OID

“calss" should be “class”.

One more nit comment on the commit message:

"The existing a VARIADIC array form of pg_get_publication_tables() is"

In this line, “a” seems not needed.

Regards,
Haoyan Wang

Re: Initial COPY of Logical Replication is too slow

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Mar 25, 2026 at 2:19 PM Peter Smith  wrote:
>
> Hi Swada-San. Here are some minor review comments for v4-0001/2 combined.
>
> ======
> src/backend/catalog/pg_publication.c
>
> is_table_publishable_in_publication:
>
> 1.
> This function logic has a format like
>
> if (cond)
> {
>  ...
>  return;
> }
>
> if (cond2)
> {
>  ...
>  return;
> }
>
> etc.
>
> There are many return points, and most of those "if" blocks cannot
> fall through (they return).
>
> I found it slightly difficult to read the code because I kept having
> to think, "OK, if we reached here, it means pubviaroot must be false,"
> or "OK, if we reached this far, then puballtables must be false, and
> pubviaroot must be false," etc.
>

I can't say exactly why, but I find it difficult to read this
function. So, I share your concerns about the code of this function.
Because of its complexity it is difficult to ascertain that the
functionality is correct or we missed something. Also, considering it
is correct today, in its current form, it may become difficult to
enhance it in future.

One more comment on latest patch:
*
+static Datum
+pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
+                          Oid target_relid, bool filter_by_relid,

Why do we need filter_by_relid as a separate parameter? Isn't the
valid value of target_relid the same? If so, can't we use target_relid
for the required checks?

--
With Regards,
Amit Kapila.


RE: Initial COPY of Logical Replication is too slow

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Sawada-san,

Thanks for updating the patch! Few comments.

01.
```
+/*
+ * Similar to is_publishable_calss() but checks whether the given OID
+ * is a publishable "table" or not.
+ */
+static bool
+is_publishable_table(Oid tableoid)
```

s/is_publishable_calss/is_publishable_class/.

02.
```
+       ReleaseSysCache(tuple);
+       return true;
```

Is it correct? I expected to return false here.

03.
```
+               /*
+                * Preliminary check if the specified table can be published in the
+                * first place. If not, we can return early without checking the given
+                * publications and the table.
+                */
+               if (filter_by_relid && !is_publishable_table(target_relid))
+                       SRF_RETURN_DONE(funcctx);
```

I think we must switch to the old context.

04.
```
+CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT TABLE (tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false);
+CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT TABLE (tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true);
```

It needs to be rebased due to 5984ea86.

05.
```
CREATE VIEW pg_publication_tables AS
    SELECT
        P.pubname AS pubname,
        N.nspname AS schemaname,
        C.relname AS tablename,
        ( SELECT array_agg(a.attname ORDER BY a.attnum)
          FROM pg_attribute a
          WHERE a.attrelid = GPT.relid AND
                a.attnum = ANY(GPT.attrs)
        ) AS attnames,
        pg_get_expr(GPT.qual, GPT.relid) AS rowfilter
     FROM pg_publication P,
          LATERAL pg_get_publication_tables(P.pubname) GPT,
          pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)
     WHERE C.oid = GPT.relid;
```

Can we use the new API of pg_get_publication_tables() here? Below change can pass
tests on my env.

```
-         LATERAL pg_get_publication_tables(P.pubname) GPT,
-         pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)
-    WHERE C.oid = GPT.relid;
+         pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace),
+         LATERAL pg_get_publication_tables(ARRAY[P.pubname], C.oid) GPT;
```

Best regards,
Hayato Kuroda
FUJITSU LIMITED

RE: Initial COPY of Logical Replication is too slow

От:
"Zhijie Hou (Fujitsu)" <houzj.fnst@fujitsu.com>
Дата:
Вложения:
On Tuesday, March 31, 2026 5:36 PM Amit Kapila  wrote:
> 
> On Wed, Mar 25, 2026 at 2:19 PM Peter Smith 
> wrote:
> >
> > There are many return points, and most of those "if" blocks cannot
> > fall through (they return).
> >
> > I found it slightly difficult to read the code because I kept having
> > to think, "OK, if we reached here, it means pubviaroot must be false,"
> > or "OK, if we reached this far, then puballtables must be false, and
> > pubviaroot must be false," etc.
> >
> 
> I can't say exactly why, but I find it difficult to read this function. So, I share
> your concerns about the code of this function.
> Because of its complexity it is difficult to ascertain that the functionality is
> correct or we missed something. Also, considering it is correct today, in its
> current form, it may become difficult to enhance it in future.
> 

I attempted to refactor the code a bit based on my preferred style, as shown in
the attachment. While the number of return points couldn't be reduced, I tried
to eliminate if-else branches where possible. Sharing this top-up patch as a
reference for an alternative style that reduces code size.

Best Regards,
Hou zj

Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Tue, Mar 31, 2026 at 2:36 AM Amit Kapila  wrote:
>
> On Wed, Mar 25, 2026 at 2:19 PM Peter Smith  wrote:
> >
> > Hi Swada-San. Here are some minor review comments for v4-0001/2 combined.
> >
> > ======
> > src/backend/catalog/pg_publication.c
> >
> > is_table_publishable_in_publication:
> >
> > 1.
> > This function logic has a format like
> >
> > if (cond)
> > {
> >  ...
> >  return;
> > }
> >
> > if (cond2)
> > {
> >  ...
> >  return;
> > }
> >
> > etc.
> >
> > There are many return points, and most of those "if" blocks cannot
> > fall through (they return).
> >
> > I found it slightly difficult to read the code because I kept having
> > to think, "OK, if we reached here, it means pubviaroot must be false,"
> > or "OK, if we reached this far, then puballtables must be false, and
> > pubviaroot must be false," etc.
> >
>
> I can't say exactly why, but I find it difficult to read this
> function. So, I share your concerns about the code of this function.
> Because of its complexity it is difficult to ascertain that the
> functionality is correct or we missed something. Also, considering it
> is correct today, in its current form, it may become difficult to
> enhance it in future.

Okay, I'll refactor that function.

>
> One more comment on latest patch:
> *
> +static Datum
> +pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
> +                          Oid target_relid, bool filter_by_relid,
>
> Why do we need filter_by_relid as a separate parameter? Isn't the
> valid value of target_relid the same? If so, can't we use target_relid
> for the required checks?

If we don't have filter_by_relid, we would end up not filtering
anything if users pass 0 (InvalidOid) as the target_relid to the new
pg_get_publication_tables(). This is the same as the behavior of the
existing pg_get_publication_tables(), so I'm concerned that it could
be confusing that the function behaves the same even though passing
different arguments . We can check whether the given target_relid is
valid in pg_get_publication_b() but we would end up checking it
multiple times unnecessarily.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Tue, Mar 31, 2026 at 4:39 AM Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Sawada-san,
>
> Thanks for updating the patch! Few comments.

Thank you for the comments!

>
> 01.
> ```
> +/*
> + * Similar to is_publishable_calss() but checks whether the given OID
> + * is a publishable "table" or not.
> + */
> +static bool
> +is_publishable_table(Oid tableoid)
> ```
>
> s/is_publishable_calss/is_publishable_class/.
>
> 02.
> ```
> +       ReleaseSysCache(tuple);
> +       return true;
> ```
>
> Is it correct? I expected to return false here.
>
> 03.
> ```
> +               /*
> +                * Preliminary check if the specified table can be published in the
> +                * first place. If not, we can return early without checking the given
> +                * publications and the table.
> +                */
> +               if (filter_by_relid && !is_publishable_table(target_relid))
> +                       SRF_RETURN_DONE(funcctx);
> ```
>
> I think we must switch to the old context.
>
> 04.
> ```
> +CREATE PUBLICATION pub_all_except FOR ALL TABLES EXCEPT TABLE (tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = false);
> +CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT TABLE (tbl_parent, gpt_test_sch.tbl_sch) WITH (publish_via_partition_root = true);
> ```
>
> It needs to be rebased due to 5984ea86.

Agreed with the all above points. I'll fix them in the next version patch.

>
> 05.
> ```
> CREATE VIEW pg_publication_tables AS
>     SELECT
>         P.pubname AS pubname,
>         N.nspname AS schemaname,
>         C.relname AS tablename,
>         ( SELECT array_agg(a.attname ORDER BY a.attnum)
>           FROM pg_attribute a
>           WHERE a.attrelid = GPT.relid AND
>                 a.attnum = ANY(GPT.attrs)
>         ) AS attnames,
>         pg_get_expr(GPT.qual, GPT.relid) AS rowfilter
>      FROM pg_publication P,
>           LATERAL pg_get_publication_tables(P.pubname) GPT,
>           pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)
>      WHERE C.oid = GPT.relid;
> ```
>
> Can we use the new API of pg_get_publication_tables() here? Below change can pass
> tests on my env.
>
> ```
> -         LATERAL pg_get_publication_tables(P.pubname) GPT,
> -         pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)
> -    WHERE C.oid = GPT.relid;
> +         pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace),
> +         LATERAL pg_get_publication_tables(ARRAY[P.pubname], C.oid) GPT;
> ```

I'm not sure the new API of pg_get_publication_tables() is better here
since this view is going to get the publication information of all
published tables, in which case the existing one might be faster.
Also, if a few tables among a huge number of tables (or whatever
relations) are published, checking all relations with the new API of
pg_get_publication_tables() would be quite slow.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Tue, Mar 31, 2026 at 5:07 AM Zhijie Hou (Fujitsu)
 wrote:
>
> On Tuesday, March 31, 2026 5:36 PM Amit Kapila  wrote:
> >
> > On Wed, Mar 25, 2026 at 2:19 PM Peter Smith 
> > wrote:
> > >
> > > There are many return points, and most of those "if" blocks cannot
> > > fall through (they return).
> > >
> > > I found it slightly difficult to read the code because I kept having
> > > to think, "OK, if we reached here, it means pubviaroot must be false,"
> > > or "OK, if we reached this far, then puballtables must be false, and
> > > pubviaroot must be false," etc.
> > >
> >
> > I can't say exactly why, but I find it difficult to read this function. So, I share
> > your concerns about the code of this function.
> > Because of its complexity it is difficult to ascertain that the functionality is
> > correct or we missed something. Also, considering it is correct today, in its
> > current form, it may become difficult to enhance it in future.
> >
>
> I attempted to refactor the code a bit based on my preferred style, as shown in
> the attachment. While the number of return points couldn't be reduced, I tried
> to eliminate if-else branches where possible. Sharing this top-up patch as a
> reference for an alternative style that reduces code size.
>

Thanks. It looks like a good refactoring! I'd prefer to free the
ancestors list to avoid memory leak.

I've attached the patch that incorporated all comments I got so far.
Feedback is very welcome.

Regards,

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

Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Fri, Mar 27, 2026 at 6:07 AM Marcos Pegoraro  wrote:
>
> Em sex., 27 de mar. de 2026 às 03:20, Masahiko Sawada  escreveu:
>>
>> I've attached the updated patch. I believe I've addressed all comments
>> I got so far. In addition to that, I've refactored
>> is_table_publishable_in_publication() and added more regression tests.
>
>
> Today I had to create a few more schemas and see that problem again, how the publisher is affected, almost crashing due to the overload.
> That was because max_sync_workers_per_subscription was set to 10, which caused 10 simultaneous connections to call this function immediately after the refresh publication command.
> Wouldn't it be good to document on this GUC that if your publisher server is running version <= 18 then is it advisable to set this GUC to a really low value ?
> Because ok, version 19 is fine, will be covered, but all publisher servers that are not updated will continue to have this trouble.
> The publisher will be severely penalized when the subscription refreshes its publication.
>
> What do you think, change something on DOCs too ?

I agree that the publisher overload is a serious issue that users
should be aware of. But I'm not sure it's a good idea to broadly
suggest lowing the GUC value as it ultimatly depends on multiple
factors. A value of 10 or more is perfectly fine depending on the
hardware and the number of tables etc. A definition of a large number
of tables also varies on systems. I guess the release note would be a
better place to mention this.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Mar 31, 2026 at 10:58 PM Masahiko Sawada  wrote:
>
> On Tue, Mar 31, 2026 at 2:36 AM Amit Kapila  wrote:
> >
> > On Wed, Mar 25, 2026 at 2:19 PM Peter Smith  wrote:
> > >
> > > Hi Swada-San. Here are some minor review comments for v4-0001/2 combined.
> > >
> > > ======
> > > src/backend/catalog/pg_publication.c
> > >
> > > is_table_publishable_in_publication:
> > >
> > > 1.
> > > This function logic has a format like
> > >
> > > if (cond)
> > > {
> > >  ...
> > >  return;
> > > }
> > >
> > > if (cond2)
> > > {
> > >  ...
> > >  return;
> > > }
> > >
> > > etc.
> > >
> > > There are many return points, and most of those "if" blocks cannot
> > > fall through (they return).
> > >
> > > I found it slightly difficult to read the code because I kept having
> > > to think, "OK, if we reached here, it means pubviaroot must be false,"
> > > or "OK, if we reached this far, then puballtables must be false, and
> > > pubviaroot must be false," etc.
> > >
> >
> > I can't say exactly why, but I find it difficult to read this
> > function. So, I share your concerns about the code of this function.
> > Because of its complexity it is difficult to ascertain that the
> > functionality is correct or we missed something. Also, considering it
> > is correct today, in its current form, it may become difficult to
> > enhance it in future.
>
> Okay, I'll refactor that function.
>
> >
> > One more comment on latest patch:
> > *
> > +static Datum
> > +pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
> > +                          Oid target_relid, bool filter_by_relid,
> >
> > Why do we need filter_by_relid as a separate parameter? Isn't the
> > valid value of target_relid the same? If so, can't we use target_relid
> > for the required checks?
>
> If we don't have filter_by_relid, we would end up not filtering
> anything if users pass 0 (InvalidOid) as the target_relid to the new
> pg_get_publication_tables(). This is the same as the behavior of the
> existing pg_get_publication_tables(),
>

Isn't that what we want when a user passes InvalidOid? What is the
expected behavior in that case?

-- 
With Regards,
Amit Kapila.


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Tue, Mar 31, 2026 at 10:04 PM Amit Kapila  wrote:
>
> On Tue, Mar 31, 2026 at 10:58 PM Masahiko Sawada  wrote:
> >
> > On Tue, Mar 31, 2026 at 2:36 AM Amit Kapila  wrote:
> > >
> > > On Wed, Mar 25, 2026 at 2:19 PM Peter Smith  wrote:
> > > >
> > > > Hi Swada-San. Here are some minor review comments for v4-0001/2 combined.
> > > >
> > > > ======
> > > > src/backend/catalog/pg_publication.c
> > > >
> > > > is_table_publishable_in_publication:
> > > >
> > > > 1.
> > > > This function logic has a format like
> > > >
> > > > if (cond)
> > > > {
> > > >  ...
> > > >  return;
> > > > }
> > > >
> > > > if (cond2)
> > > > {
> > > >  ...
> > > >  return;
> > > > }
> > > >
> > > > etc.
> > > >
> > > > There are many return points, and most of those "if" blocks cannot
> > > > fall through (they return).
> > > >
> > > > I found it slightly difficult to read the code because I kept having
> > > > to think, "OK, if we reached here, it means pubviaroot must be false,"
> > > > or "OK, if we reached this far, then puballtables must be false, and
> > > > pubviaroot must be false," etc.
> > > >
> > >
> > > I can't say exactly why, but I find it difficult to read this
> > > function. So, I share your concerns about the code of this function.
> > > Because of its complexity it is difficult to ascertain that the
> > > functionality is correct or we missed something. Also, considering it
> > > is correct today, in its current form, it may become difficult to
> > > enhance it in future.
> >
> > Okay, I'll refactor that function.
> >
> > >
> > > One more comment on latest patch:
> > > *
> > > +static Datum
> > > +pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
> > > +                          Oid target_relid, bool filter_by_relid,
> > >
> > > Why do we need filter_by_relid as a separate parameter? Isn't the
> > > valid value of target_relid the same? If so, can't we use target_relid
> > > for the required checks?
> >
> > If we don't have filter_by_relid, we would end up not filtering
> > anything if users pass 0 (InvalidOid) as the target_relid to the new
> > pg_get_publication_tables(). This is the same as the behavior of the
> > existing pg_get_publication_tables(),
> >
>
> Isn't that what we want when a user passes InvalidOid? What is the
> expected behavior in that case?
>

While it could be contrivarsial what we expect when "users wants to
filter the result by InvalidOid", I think the new
pg_get_publication_tables() should not return anything in this case
rather than return all table information. I think this behavior is
consistent with the case where users pass non-table OID to the
function. I don't want to make passing InvalidOid a special case in
the new function.

Regards,

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


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Tue, Mar 31, 2026 at 12:40 PM Masahiko Sawada  wrote:
>
> On Tue, Mar 31, 2026 at 5:07 AM Zhijie Hou (Fujitsu)
>  wrote:
> >
> > On Tuesday, March 31, 2026 5:36 PM Amit Kapila  wrote:
> > >
> > > On Wed, Mar 25, 2026 at 2:19 PM Peter Smith 
> > > wrote:
> > > >
> > > > There are many return points, and most of those "if" blocks cannot
> > > > fall through (they return).
> > > >
> > > > I found it slightly difficult to read the code because I kept having
> > > > to think, "OK, if we reached here, it means pubviaroot must be false,"
> > > > or "OK, if we reached this far, then puballtables must be false, and
> > > > pubviaroot must be false," etc.
> > > >
> > >
> > > I can't say exactly why, but I find it difficult to read this function. So, I share
> > > your concerns about the code of this function.
> > > Because of its complexity it is difficult to ascertain that the functionality is
> > > correct or we missed something. Also, considering it is correct today, in its
> > > current form, it may become difficult to enhance it in future.
> > >
> >
> > I attempted to refactor the code a bit based on my preferred style, as shown in
> > the attachment. While the number of return points couldn't be reduced, I tried
> > to eliminate if-else branches where possible. Sharing this top-up patch as a
> > reference for an alternative style that reduces code size.
> >
>
> Thanks. It looks like a good refactoring! I'd prefer to free the
> ancestors list to avoid memory leak.
>
> I've attached the patch that incorporated all comments I got so far.
> Feedback is very welcome.
>

I decided to simplify the code flow in the
is_table_publishable_in_publication() by taking more proposed changes
from Hou-san while accepting some memory leak. This function is
limited to be used only in per-call-memory context so we don't need to
worry about the actual memory leak. While we would need to change this
function in the futuer when we want to use it other places too, I
think it would be better to keep the function simple until then. I
hope the added new comment also help understand the code flow of this
function.

I think the patch is good shape, so planning to push it barring any objections.

Regards,

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

Re: Initial COPY of Logical Replication is too slow

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Apr 1, 2026 at 11:06 PM Masahiko Sawada  wrote:
>
> On Tue, Mar 31, 2026 at 10:04 PM Amit Kapila  wrote:
> >
> > On Tue, Mar 31, 2026 at 10:58 PM Masahiko Sawada  wrote:
> > >
> > > On Tue, Mar 31, 2026 at 2:36 AM Amit Kapila  wrote:
> > > >
> > > > On Wed, Mar 25, 2026 at 2:19 PM Peter Smith  wrote:
> > > > >
> > > > > Hi Swada-San. Here are some minor review comments for v4-0001/2 combined.
> > > > >
> > > > > ======
> > > > > src/backend/catalog/pg_publication.c
> > > > >
> > > > > is_table_publishable_in_publication:
> > > > >
> > > > > 1.
> > > > > This function logic has a format like
> > > > >
> > > > > if (cond)
> > > > > {
> > > > >  ...
> > > > >  return;
> > > > > }
> > > > >
> > > > > if (cond2)
> > > > > {
> > > > >  ...
> > > > >  return;
> > > > > }
> > > > >
> > > > > etc.
> > > > >
> > > > > There are many return points, and most of those "if" blocks cannot
> > > > > fall through (they return).
> > > > >
> > > > > I found it slightly difficult to read the code because I kept having
> > > > > to think, "OK, if we reached here, it means pubviaroot must be false,"
> > > > > or "OK, if we reached this far, then puballtables must be false, and
> > > > > pubviaroot must be false," etc.
> > > > >
> > > >
> > > > I can't say exactly why, but I find it difficult to read this
> > > > function. So, I share your concerns about the code of this function.
> > > > Because of its complexity it is difficult to ascertain that the
> > > > functionality is correct or we missed something. Also, considering it
> > > > is correct today, in its current form, it may become difficult to
> > > > enhance it in future.
> > >
> > > Okay, I'll refactor that function.
> > >
> > > >
> > > > One more comment on latest patch:
> > > > *
> > > > +static Datum
> > > > +pg_get_publication_tables(FunctionCallInfo fcinfo, ArrayType *pubnames,
> > > > +                          Oid target_relid, bool filter_by_relid,
> > > >
> > > > Why do we need filter_by_relid as a separate parameter? Isn't the
> > > > valid value of target_relid the same? If so, can't we use target_relid
> > > > for the required checks?
> > >
> > > If we don't have filter_by_relid, we would end up not filtering
> > > anything if users pass 0 (InvalidOid) as the target_relid to the new
> > > pg_get_publication_tables(). This is the same as the behavior of the
> > > existing pg_get_publication_tables(),
> > >
> >
> > Isn't that what we want when a user passes InvalidOid? What is the
> > expected behavior in that case?
> >
>
> While it could be contrivarsial what we expect when "users wants to
> filter the result by InvalidOid", I think the new
> pg_get_publication_tables() should not return anything in this case
> rather than return all table information. I think this behavior is
> consistent with the case where users pass non-table OID to the
> function. I don't want to make passing InvalidOid a special case in
> the new function.
>

Fair enough. I am fine with this definition.

-- 
With Regards,
Amit Kapila.


Re: Initial COPY of Logical Replication is too slow

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Apr 2, 2026 at 3:53 AM Masahiko Sawada  wrote:
>
> On Tue, Mar 31, 2026 at 12:40 PM Masahiko Sawada  wrote:
> >
> > On Tue, Mar 31, 2026 at 5:07 AM Zhijie Hou (Fujitsu)
> >  wrote:
> > >
> > > On Tuesday, March 31, 2026 5:36 PM Amit Kapila  wrote:
> > > >
> > > > On Wed, Mar 25, 2026 at 2:19 PM Peter Smith 
> > > > wrote:
> > > > >
> > > > > There are many return points, and most of those "if" blocks cannot
> > > > > fall through (they return).
> > > > >
> > > > > I found it slightly difficult to read the code because I kept having
> > > > > to think, "OK, if we reached here, it means pubviaroot must be false,"
> > > > > or "OK, if we reached this far, then puballtables must be false, and
> > > > > pubviaroot must be false," etc.
> > > > >
> > > >
> > > > I can't say exactly why, but I find it difficult to read this function. So, I share
> > > > your concerns about the code of this function.
> > > > Because of its complexity it is difficult to ascertain that the functionality is
> > > > correct or we missed something. Also, considering it is correct today, in its
> > > > current form, it may become difficult to enhance it in future.
> > > >
> > >
> > > I attempted to refactor the code a bit based on my preferred style, as shown in
> > > the attachment. While the number of return points couldn't be reduced, I tried
> > > to eliminate if-else branches where possible. Sharing this top-up patch as a
> > > reference for an alternative style that reduces code size.
> > >
> >
> > Thanks. It looks like a good refactoring! I'd prefer to free the
> > ancestors list to avoid memory leak.
> >
> > I've attached the patch that incorporated all comments I got so far.
> > Feedback is very welcome.
> >
>
> I decided to simplify the code flow in the
> is_table_publishable_in_publication() by taking more proposed changes
> from Hou-san while accepting some memory leak. This function is
> limited to be used only in per-call-memory context so we don't need to
> worry about the actual memory leak. While we would need to change this
> function in the futuer when we want to use it other places too, I
> think it would be better to keep the function simple until then. I
> hope the added new comment also help understand the code flow of this
> function.
>

Yes, the function looks better and helps to understand the flow.
Thanks for improving it.

-- 
With Regards,
Amit Kapila.


Re: Initial COPY of Logical Replication is too slow

От:
Peter Smith <smithpb2250@gmail.com>
Дата:
Hi Sawada-San

Some review comments for v8-0001.

======
Commit message

1.
The existing a VARIADIC array form of pg_get_publication_tables() is
preserved for backward compatibility. Tablesync workers use the new
two-argument form when connected to a publisher running PostgreSQL 19
or later.

~

Typo? "The existing a VARIADIC"

======
src/backend/catalog/pg_publication.c

is_publishable_table:

2.
+ /*
+ * Sequences are publishable according to is_publishable_class() so
+ * explicitly exclude here.
+ */
+ if (relform->relkind != RELKIND_SEQUENCE &&
+ is_publishable_class(tableoid, relform))
+ {
+ ReleaseSysCache(tuple);
+ return true;
+ }

It seemed strange to say that "sequences are publishable according to
is_publishable_class() so explicitly exclude", but then you proceed to
call is_publishable_class() anyway.

Maybe using a variable, and a different comment could be a better way
of expressing this?

SUGGESTION
bool ret;
...
/* Sequences are not tables, so this function returns false. */
if (relform->relkind == RELKIND_SEQUENCE)
    ret = false;
else
    ret = is_publishable_class(tableoid, relform);

ReleaseSysCache(tuple);
return ret;

~~~

is_table_publishable_in_publication:

3.
+ * A helper function for pg_get_publication_tables() to check whether the
+ * table of the given relid is published for the specified publication.

/table of the given relid/table with the given relid/

/is published for the/is published in the/

~~~

pg_get_publication_tables:

4.
+ * If filter_by_relid is true, only the row for target_relid is returned;
+ * if target_relid does not exist or is not part of the publications, zero
+ * rows are returned.  If filter_by_relid is false, rows for all tables
+ * within the specified publications are returned and target_relid is
+ * ignored.

Should that say "only the row(s) for target_relid", e.g. possibly
plural, because if same table is in multiple publications then there
are be multiple result rows, right?

======
src/include/catalog/pg_proc.dat

5.
Missed my previous [1] review comment #4?

First arg of pg_get_publication_tables_a should be plural 'pubnames',
same as first arg of pg_get_publication_tables_b.

======
src/test/regress/sql/publication.sql

6.
+CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT
(TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH
(publish_via_partition_root = true);

Why is this publication called '...no_viaroot' when
publish_via_partition_root = true?

~~~

7.
+-- test for the EXCLUDE clause

Typo? /EXCLUDE clause/EXCEPT clause/

======
[1] https://www.postgresql.org/message-id/CAHut%2BPuSkabUB8H_hcwQz%3DBX5TWEj-8Ba%2BCP_PX78zN1fkhtKA%40mail.gmail.com


Kind Regards,
Peter Smith.
Fujitsu Australia


Re: Initial COPY of Logical Replication is too slow

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Wed, Apr 1, 2026 at 11:12 PM Peter Smith  wrote:
>
> Hi Sawada-San
>
> Some review comments for v8-0001.
>
> ======
> Commit message
>
> 1.
> The existing a VARIADIC array form of pg_get_publication_tables() is
> preserved for backward compatibility. Tablesync workers use the new
> two-argument form when connected to a publisher running PostgreSQL 19
> or later.
>
> ~
>
> Typo? "The existing a VARIADIC"
>
> ======
> src/backend/catalog/pg_publication.c
>
> is_publishable_table:
>
> 2.
> + /*
> + * Sequences are publishable according to is_publishable_class() so
> + * explicitly exclude here.
> + */
> + if (relform->relkind != RELKIND_SEQUENCE &&
> + is_publishable_class(tableoid, relform))
> + {
> + ReleaseSysCache(tuple);
> + return true;
> + }
>
> It seemed strange to say that "sequences are publishable according to
> is_publishable_class() so explicitly exclude", but then you proceed to
> call is_publishable_class() anyway.
>
> Maybe using a variable, and a different comment could be a better way
> of expressing this?
>
> SUGGESTION
> bool ret;
> ...
> /* Sequences are not tables, so this function returns false. */
> if (relform->relkind == RELKIND_SEQUENCE)
>     ret = false;
> else
>     ret = is_publishable_class(tableoid, relform);
>
> ReleaseSysCache(tuple);
> return ret;
>
> ~~~
>
> is_table_publishable_in_publication:
>
> 3.
> + * A helper function for pg_get_publication_tables() to check whether the
> + * table of the given relid is published for the specified publication.
>
> /table of the given relid/table with the given relid/
>
> /is published for the/is published in the/
>
> ~~~
>
> pg_get_publication_tables:
>
> 4.
> + * If filter_by_relid is true, only the row for target_relid is returned;
> + * if target_relid does not exist or is not part of the publications, zero
> + * rows are returned.  If filter_by_relid is false, rows for all tables
> + * within the specified publications are returned and target_relid is
> + * ignored.
>
> Should that say "only the row(s) for target_relid", e.g. possibly
> plural, because if same table is in multiple publications then there
> are be multiple result rows, right?
>
> ======
> src/include/catalog/pg_proc.dat
>
> 5.
> Missed my previous [1] review comment #4?
>
> First arg of pg_get_publication_tables_a should be plural 'pubnames',
> same as first arg of pg_get_publication_tables_b.
>
> ======
> src/test/regress/sql/publication.sql
>
> 6.
> +CREATE PUBLICATION pub_all_except_no_viaroot FOR ALL TABLES EXCEPT
> (TABLE tbl_parent, gpt_test_sch.tbl_sch) WITH
> (publish_via_partition_root = true);
>
> Why is this publication called '...no_viaroot' when
> publish_via_partition_root = true?
>
> ~~~
>
> 7.
> +-- test for the EXCLUDE clause
>
> Typo? /EXCLUDE clause/EXCEPT clause/
>

Thank you for the comments!

I've pushed the patch after incorporating these points.

Regards,

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


FAQ