Avoid unnecessary StringInfo allocation in tablesync COPY buffer

Started by Chao Li7 months ago9 messageshackers

Thread notes

1 note#refactor
hackorum-bot#refactor
hackorum-bot
2 days ago

@global #refactor

#refactor
Jump to latest
#1Chao Li
li.evan.chao@gmail.com

Hi,

I found this issue while reviewing the patch [1]/messages/by-id/CAOzEurQKuy3RiPkd=25PEwEzaqHuGvEOf=X7vaVzhgNjaukYzA@mail.gmail.com and was suggested use a separate thread for the issue.

In tablesync.c, copy_table() currently does:
```
copybuf = makeStringInfo();
```

But copybuf is only used by copy_read_data(), and there it's really just acting as a small state holder for data, len, and cursor, rather than as a normal growable StringInfo. That means we do not need to allocate a StringInfo object or its backing buffer at all.

It would be cleaner to use a plain StringInfoData and simply reinitialize or zero it in copy_table(). See the attached patch for the proposed change.

David Rowley has made several cleanup changes in this area to prefer stack-allocated StringInfoData, for example a63bbc811d41b3567eb37fe2636e660a852dbbf2. This change seems consistent with that direction.

[1]: /messages/by-id/CAOzEurQKuy3RiPkd=25PEwEzaqHuGvEOf=X7vaVzhgNjaukYzA@mail.gmail.com

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

Attachments:

v1-0001-Avoid-unnecessary-StringInfo-allocation-in-tables.patchapplication/octet-stream; name=v1-0001-Avoid-unnecessary-StringInfo-allocation-in-tables.patch; x-unix-mode=0644Download+11-12
#2Alvaro Herrera
alvherre@kurilemu.de
In reply to: Chao Li (#1)
Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

Hello,

On 2026-May-09, Chao Li wrote:

I found this issue while reviewing the patch [1] and was suggested use
a separate thread for the issue.

In tablesync.c, copy_table() currently does:
```
copybuf = makeStringInfo();
```

But copybuf is only used by copy_read_data(), and there it's really
just acting as a small state holder for data, len, and cursor, rather
than as a normal growable StringInfo.

I find this coding pattern weird and ugly and confusing. If what we
need is three variables, shouldn't we have three variables instead of
this strange misuse of the StringInfo abstraction?

--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
"We have labored long to build a heaven, only (Prof. Milton Glass)
to find it populated with horrors" (Watchmen, Alan Moore)

#3Chao Li
li.evan.chao@gmail.com
In reply to: Alvaro Herrera (#2)
Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

On May 9, 2026, at 23:35, Álvaro Herrera <alvherre@kurilemu.de> wrote:

Hello,

On 2026-May-09, Chao Li wrote:

I found this issue while reviewing the patch [1] and was suggested use
a separate thread for the issue.

In tablesync.c, copy_table() currently does:
```
copybuf = makeStringInfo();
```

But copybuf is only used by copy_read_data(), and there it's really
just acting as a small state holder for data, len, and cursor, rather
than as a normal growable StringInfo.

I find this coding pattern weird and ugly and confusing. If what we
need is three variables, shouldn't we have three variables instead of
this strange misuse of the StringInfo abstraction?

Yep, I first considered adding a file-local structure, but decided to keep the changes minimal in the first version.

In v2, I switched to using a small file-local CopyBuf structure.

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

Attachments:

t139597_3
v2-0001-Use-simple-struct-for-table-sync-COPY-buffer-stat.patchapplication/octet-stream; name=v2-0001-Use-simple-struct-for-table-sync-COPY-buffer-stat.patch; x-unix-mode=0644Download+18-12
#4Denis Smirnov
darthunix@gmail.com
In reply to: Chao Li (#3)
Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

Hi,

I am not sure that introducing a separate CopyBuf type is an
improvement over v1.

StringInfoData is not limited to text strings. It is also used for
arbitrary binary data, and initReadOnlyStringInfo() exists specifically
for wrapping an externally owned, possibly non-NUL-terminated buffer.
It initializes data and len, sets cursor to zero, and marks the buffer
as read-only by setting maxlen to zero.

The same pattern is already used in nearby replication code. For
example, walreceiver.c and logical/worker.c use
initReadOnlyStringInfo() to process external binary protocol messages.

Therefore, I think v1 could keep the static StringInfoData and use:

initReadOnlyStringInfo(&copybuf, buf, len);

when a new buffer is received. The memset before starting COPY can
remain to clear any previous state.

V1 already removes both allocations performed by makeStringInfo().
Since copybuf is static, the unused maxlen field occupies only a few
bytes in the worker process; it does not cause a per-table or
per-callback allocation. I would not expect any measurable performance
difference between v1 and v2.

A separate structure can be useful when it represents additional state
or invariants that are not covered by an existing abstraction. In this
case, however, CopyBuf contains only a subset of StringInfoData, while
the documented read-only StringInfoData representation already matches
the required ownership and cursor semantics.

For these reasons, my preference would be to keep the approach from v1
and initialize each received buffer with initReadOnlyStringInfo().

Best regards,
Denis Smirnov

Show quoted text

On 11 May 2026, at 14:09, Chao Li <li.evan.chao@gmail.com> wrote:

On May 9, 2026, at 23:35, Álvaro Herrera <alvherre@kurilemu.de> wrote:

Hello,

On 2026-May-09, Chao Li wrote:

I found this issue while reviewing the patch [1] and was suggested use
a separate thread for the issue.

In tablesync.c, copy_table() currently does:
```
copybuf = makeStringInfo();
```

But copybuf is only used by copy_read_data(), and there it's really
just acting as a small state holder for data, len, and cursor, rather
than as a normal growable StringInfo.

I find this coding pattern weird and ugly and confusing. If what we
need is three variables, shouldn't we have three variables instead of
this strange misuse of the StringInfo abstraction?

Yep, I first considered adding a file-local structure, but decided to keep the changes minimal in the first version.

In v2, I switched to using a small file-local CopyBuf structure.

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

<v2-0001-Use-simple-struct-for-table-sync-COPY-buffer-stat.patch>

#5ZizhuanLiu X-MAN
44973863@qq.com
In reply to: Denis Smirnov (#4)
Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

Original

From: Denis Smirnov <darthunix@gmail.com>
Date: 2026-07-18 15:42
To: Chao Li <li.evan.chao@gmail.com>
Cc: álvaro Herrera <alvherre@kurilemu.de>, PostgreSQL-development <pgsql-hackers@postgresql.org>, David Rowley <dgrowleyml@gmail.com>, Fujii Masao <masao.fujii@gmail.com>
Subject: Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

Hi,
I am not sure that introducing a separate CopyBuf type is an
improvement over v1.
StringInfoData is not limited to text strings. It is also used for
arbitrary binary data, and initReadOnlyStringInfo() exists specifically
for wrapping an externally owned, possibly non-NUL-terminated buffer.
It initializes data and len, sets cursor to zero, and marks the buffer
as read-only by setting maxlen to zero.
The same pattern is already used in nearby replication code. For
example, walreceiver.c and logical/worker.c use
initReadOnlyStringInfo() to process external binary protocol messages.
Therefore, I think v1 could keep the static StringInfoData and use:
initReadOnlyStringInfo(&copybuf, buf, len);
when a new buffer is received. The memset before starting COPY can
remain to clear any previous state.
V1 already removes both allocations performed by makeStringInfo().
Since copybuf is static, the unused maxlen field occupies only a few
bytes in the worker process; it does not cause a per-table or
per-callback allocation. I would not expect any measurable performance
difference between v1 and v2.
A separate structure can be useful when it represents additional state
or invariants that are not covered by an existing abstraction. In this
case, however, CopyBuf contains only a subset of StringInfoData, while
the documented read-only StringInfoData representation already matches
the required ownership and cursor semantics.
For these reasons, my preference would be to keep the approach from v1
and initialize each received buffer with initReadOnlyStringInfo().

Best regards,
Denis Smirnov

Hi Denis and álvaro,

Thanks for the reviews and suggestions.

I revised the patch based on the discussion. Instead of introducing a separate CopyBuf abstraction,
v3 reuses the existing StringInfoData mechanism.

copybuf is now a function-scope static StringInfoData in copy_read_data(), initialized to zero and
re-initialized with initReadOnlyStringInfo() for each incoming buffer. This avoids the heap allocation
from makeStringInfo() while preserving the existing handling of leftover unconsumed data across
function invocations.

Using StringInfoData as a read-only buffer is already an established pattern in the PostgreSQL codebase.
I found it being used in several places, including:
backend/replication/logical/applyparallelworker.c
backend/replication/logical/worker.c
backend/replication/walreceiver.c
backend/tcop/postgres.c
backend/utils/adt/arrayfuncs.c
backend/utils/adt/array_userfuncs.c
backend/utils/adt/numeric.c
backend/utils/adt/rowtypes.c
backend/utils/adt/timestamp.c
backend/utils/adt/varlena.c

Therefore, I think reusing StringInfoData with initReadOnlyStringInfo() is preferable to introducing another
CopyBuf abstraction, while also keeping the buffer-related state local to copy_read_data().

The updated patch is attached for review.

Thanks again for the feedback.

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Attachments:

t139597_5
v3-0001-Avoid-unnecessary-allocation-for-tablesync.c-COPY.patchapplication/octet-stream; charset=utf-8; name=v3-0001-Avoid-unnecessary-allocation-for-tablesync.c-COPY.patchDownload+8-14
#6Aleksander Alekseev
aleksander@tigerdata.com
In reply to: ZizhuanLiu X-MAN (#5)
Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

Hi,

I revised the patch based on the discussion. Instead of introducing a separate CopyBuf abstraction,
v3 reuses the existing StringInfoData mechanism.

I fail to understand the value of v3 except the fact that it saves 3
lines of code. Arguably right now we have much larger problems e.g.
actual bugs to fix and we better spend the time of the reviewers on
these problems.

Considering the fact that Álvaro was not enthusiastic about the
previous version of the patch I doubt it will be accepted. Marking as
Rejected.

--
Best regards,
Aleksander Alekseev

#7Alvaro Herrera
alvherre@kurilemu.de
In reply to: Aleksander Alekseev (#6)
Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

On 2026-Nov-23, Aleksander Alekseev wrote:

Hi,

I revised the patch based on the discussion. Instead of introducing
a separate CopyBuf abstraction, v3 reuses the existing
StringInfoData mechanism.

I fail to understand the value of v3 except the fact that it saves 3
lines of code. Arguably right now we have much larger problems e.g.
actual bugs to fix and we better spend the time of the reviewers on
these problems.

I agree that there are more important things to fix. I thought using a
read-only StringInfo and getting rid of the global wasn't a completely
bad idea. I was reading this patch thinking it could be a quick push,
but I realized that it's not trivial to see from eyeballing alone that
we don't call walrcv_receive() one more time before consuming the whole
buffer (which libpqrcv_receive warns against). Admittedly, the same can
be said of the original code, so this is not a new concern. Maybe a few
extra comments would make this business clearer.

Another thing I noticed is that minread is always 1 in current callers
of CopyGetData(). We used to have callers passing other values, but
that code's gone. Not sure this insight buys us anything, as I don't
see changing it to hardcode a 1, although we could remove the parameter
in all the callers that pass a copy_data_source_cb to BeginCopyFrom ...
which is only the one being patched here, curiously.

--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/

#8Alvaro Herrera
alvherre@kurilemu.de
In reply to: Alvaro Herrera (#7)
Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

On 2026-Nov-23, Álvaro Herrera wrote:

I agree that there are more important things to fix. I thought using a
read-only StringInfo and getting rid of the global wasn't a completely
bad idea. I was reading this patch thinking it could be a quick push,
but I realized that it's not trivial to see from eyeballing alone that
we don't call walrcv_receive() one more time before consuming the whole
buffer (which libpqrcv_receive warns against). Admittedly, the same can
be said of the original code, so this is not a new concern. Maybe a few
extra comments would make this business clearer.

I pushed this after all, thanks.

--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
"Los minutos y los segundos son mercadería de la ciudad, donde un infeliz se
afana por no perder ni siquiera un segundo y no advierte que obrando de ese
modo pierde una vida." ("La vuelta de Don Camilo", G. Guareschi)

#9Chao Li
li.evan.chao@gmail.com
In reply to: Alvaro Herrera (#8)
Re: Avoid unnecessary StringInfo allocation in tablesync COPY buffer

On Nov 25, 2026, at 04:39, Álvaro Herrera <alvherre@kurilemu.de> wrote:

On 2026-Nov-23, Álvaro Herrera wrote:

I agree that there are more important things to fix. I thought using a
read-only StringInfo and getting rid of the global wasn't a completely
bad idea. I was reading this patch thinking it could be a quick push,
but I realized that it's not trivial to see from eyeballing alone that
we don't call walrcv_receive() one more time before consuming the whole
buffer (which libpqrcv_receive warns against). Admittedly, the same can
be said of the original code, so this is not a new concern. Maybe a few
extra comments would make this business clearer.

I pushed this after all, thanks.

--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
"Los minutos y los segundos son mercadería de la ciudad, donde un infeliz se
afana por no perder ni siquiera un segundo y no advierte que obrando de ese
modo pierde una vida." ("La vuelta de Don Camilo", G. Guareschi)

Thanks a lot for pushing this patch, and sorry for missing the previous discussion.

I wasn’t aware of read-only StringInfo, but after reading f0efa5aec193, I agree it’s a perfect fit for copybuf.

While reading the pushed commit, I just found a pre-existing bug in copy_read_data():
```
/* If there are some leftover data from previous read, use it. */
avail = copybuf.len - copybuf.cursor;
if (avail)
{
if (avail > maxread)
avail = maxread;
memcpy(outbuf, &copybuf.data[copybuf.cursor], avail);
copybuf.cursor += avail;
maxread -= avail;
bytesread += avail;
}
```

After copying the leftover bytes, copy_read_data() doesn’t advance outbuf. If those bytes are less then minread, the next memcpy() would overwrite them. The current caller only passes 1 for minread, so this bug cannot be triggered today. I’ll propose a patch in a new thread.

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