Avoid truncated or zero-padded copies of replaced files in backups.

Started by David Steele30 days ago13 messageshackers
Jump to latest
#1David Steele
david@pgbackrest.org

Hackers,

Base backups stat each file while scanning the data directory and later
send exactly the number of bytes reported by the stat. If the file is
shorter when it is read then the copy is zero-padded. This is harmless
for relation files since any data written after the stat will be
restored from WAL.

Some files that are not relation files are written to a temp file and
then renamed into place, e.g. postgresql.auto.conf by ALTER SYSTEM and
pg_logical/replorigin_checkpoint by every checkpoint. If the rename
happens between the stat and the open then the backup contains the new
file truncated or zero-padded to the size of the old file. WAL replay
does not repair these files. A damaged replorigin_checkpoint fails its
CRC check and the restored cluster will not start. A damaged
postgresql.auto.conf either fails to parse or, if the truncation falls
on a line boundary, silently loses settings.

Some contrib modules also write files to the data directory this way.
pg_prewarm rewrites autoprewarm.blocks every
pg_prewarm.autoprewarm_interval. A truncated autoprewarm.blocks fails to
load. The autoprewarm worker then exits and is not restarted so blocks
are neither prewarmed nor dumped. pg_stash_advice rewrites
pg_stash_advice.tsv every pg_stash_advice.persist_interval when the
stashed advice has changed. A truncated pg_stash_advice.tsv may load a
truncated advice string without error since the last line is not
required to end with a newline.

For files that are not relation files, fstat() the opened file and use
that stat for the tar header and the backup manifest. Since the rename
is atomic the opened file is always complete. Relation files are not
replaced this way and are still sent using the earlier stat. Calling
fstat() for every file would be simpler, but using the earlier stat for
relation files means that data added to relation files after the stat is
not copied. WAL replay will restore that data anyway so copying it is
wasteful.

This should be back-patched to all supported branches. Before v17,
sendFile() does not receive the relfilenumber so on those branches
sendDir() should save the result of its existing
parse_filename_for_nontemp_relation() call and pass it to sendFile().
That call is only made for database directories so relation files in
global/ are not identified and get the stat of the opened file. The copy
may then include data written between the earlier stat and the open,
which is harmless since WAL replay will overwrite that data, just as it
overwrites blocks modified while the file is being copied.

Claude Code was used to audit the server and contrib modules for files
that are written to a temp file and then renamed into place, but the
actual issue was discovered independently by me. I had just never found
the time to do the audit to determine if it was real or imagined, though
I suspected postgresql.auto.conf at least would be an issue.

Regards,
-David

Attachments:

t254374_1
basebackup-replaced-file-v1.patchtext/plain; charset=UTF-8; name=basebackup-replaced-file-v1.patchDownload+18-1
#2shihao zhong
zhong950419@gmail.com
In reply to: David Steele (#1)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

Hi David,

Thanks for the patch. I reproduced all three cases on master with an
injection point, and v1 fixes them.

I found one more file with the same problem. A checkpoint rewrites
pg_twophase files in place with O_TRUNC. If the backup copies one
right after the truncate, it gets an empty file. The restored cluster
then fails with

FATAL: incorrect size of file "pg_twophase/000000000000029C": 0
bytes

v1 cannot help here, since the open file really is empty. The
attached patch writes to a temp file and renames it into place.

Also, pg_verifybackup reports all of these broken backups as fine.

Thanks,
Shihao

Attachments:

nocfbot-twophase-temp-file-rename.txttext/plain; charset=US-ASCII; name=nocfbot-twophase-temp-file-rename.txtDownload+21-7
#3David Steele
david@pgbackrest.org
In reply to: shihao zhong (#2)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

Hi Shihao,

On 10/25/26 16:36, shihao zhong wrote:

I reproduced all three cases on master with an
injection point, and v1 fixes them.

Thank you for testing!

I confirmed with injection points as well but was not sure it was worth
adding them to the patch since the fix is pretty straightforward.

I found one more file with the same problem. A checkpoint rewrites
pg_twophase files in place with O_TRUNC. If the backup copies one
right after the truncate, it gets an empty file.

Good catch. My audit noticed this truncate but failed to note that the
file would be accessed before WAL replay reconstructed it.

One small correction: a checkpoint writes each state file only once and
then flags the transaction as on disk. The window therefore appears to
be between creating the file and finishing the write rather than a
truncate of existing contents.

This is not limited to backups. It appears that if the checkpointer is
killed between the open and the write, or the OS crashes before the
fsync, then the file is left empty or partial and crash recovery fails
the same way.

A few notes on the patch:

- A stale .tmp file is never removed. restoreTwoPhaseData() will need to
handle this or they will build up.

- There's a double blank line before the rename.

- In the commit message, I think "truncates and rewrites" should be
something like "creates and writes".

v1 cannot help here, since the open file really is empty.

Since v1 can't help here it should probably be a separate patch. Or, we
could include it as the first patch in a set with mine. At this point it
would be good to get some feedback from a committer to see how they want
to proceed.

Minor releases are soon but these bugs are so old that I'm not sure it
makes sense to rush.

Also, pg_verifybackup reports all of these broken backups as fine.

This is as expected. pg_verify can only work with the data it was
provided. If we fix the upstream code then pg_verify will be fine.

Regards,
-David

#4shihao zhong
zhong950419@gmail.com
In reply to: David Steele (#3)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

Hi David,

Agreed. This is an old bug on its own and not a backup issue, so it
should not hold up your patch. I will start a separate thread for it
with your comments addressed.

Thanks,
Shihao

#5Chao Li
li.evan.chao@gmail.com
In reply to: David Steele (#1)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

On Oct 25, 2026, at 05:34, David Steele <david@pgbackrest.org> wrote:

Hackers,

Base backups stat each file while scanning the data directory and later send exactly the number of bytes reported by the stat. If the file is shorter when it is read then the copy is zero-padded. This is harmless for relation files since any data written after the stat will be restored from WAL.

Some files that are not relation files are written to a temp file and then renamed into place, e.g. postgresql.auto.conf by ALTER SYSTEM and pg_logical/replorigin_checkpoint by every checkpoint. If the rename happens between the stat and the open then the backup contains the new file truncated or zero-padded to the size of the old file. WAL replay does not repair these files. A damaged replorigin_checkpoint fails its CRC check and the restored cluster will not start. A damaged postgresql.auto.conf either fails to parse or, if the truncation falls on a line boundary, silently loses settings.

Some contrib modules also write files to the data directory this way. pg_prewarm rewrites autoprewarm.blocks every pg_prewarm.autoprewarm_interval. A truncated autoprewarm.blocks fails to load. The autoprewarm worker then exits and is not restarted so blocks are neither prewarmed nor dumped. pg_stash_advice rewrites pg_stash_advice.tsv every pg_stash_advice.persist_interval when the stashed advice has changed. A truncated pg_stash_advice.tsv may load a truncated advice string without error since the last line is not required to end with a newline.

For files that are not relation files, fstat() the opened file and use that stat for the tar header and the backup manifest. Since the rename is atomic the opened file is always complete. Relation files are not replaced this way and are still sent using the earlier stat. Calling fstat() for every file would be simpler, but using the earlier stat for relation files means that data added to relation files after the stat is not copied. WAL replay will restore that data anyway so copying it is wasteful.

This should be back-patched to all supported branches. Before v17, sendFile() does not receive the relfilenumber so on those branches sendDir() should save the result of its existing parse_filename_for_nontemp_relation() call and pass it to sendFile(). That call is only made for database directories so relation files in global/ are not identified and get the stat of the opened file. The copy may then include data written between the earlier stat and the open, which is harmless since WAL replay will overwrite that data, just as it overwrites blocks modified while the file is being copied.

Claude Code was used to audit the server and contrib modules for files that are written to a temp file and then renamed into place, but the actual issue was discovered independently by me. I had just never found the time to do the audit to determine if it was real or imagined, though I suspected postgresql.auto.conf at least would be an issue.

Regards,
-David<basebackup-replaced-file-v1.patch>

Hi David,

Thanks for the patch. Overall LGTM. A couple of really nit comments:

1
```
+ * If the file is not a relation file then statbuf is replaced with the stat of
+ * the file that was opened.
```

TBH, this comment is not easy to read for non-native English speakers like me. I feel that the code change itself is easier to understand than this comment. So, how about making it more explicit, for example:
```
* For non-relation files, statbuf is updated using fstat() on the opened file.
```

2
```
+	/*
+	 * If this is not a relation file then use the stat of the file that was
+	 * actually opened rather than the caller's earlier stat. Some files, e.g.
+	 * postgresql.auto.conf, are written to a temp file and then renamed in
+	 * place. If the rename happened after the earlier stat then the opened
+	 * file may have a different size and sending the earlier size would
+	 * truncate or zero-pad the file. WAL replay will not repair these files.
+	 * Relation files are not replaced this way and any data added to relation
+	 * files after the earlier stat will be restored by WAL replay.
+	 */
```

I think we can leave the detailed explanation in the commit message. Here, explaining the race and why we need the opened file's stat should be enough. So, how about shortening it to:
```
/*
* Non-relation files may be replaced by rename between the caller's stat
* and our open. Use the opened file's stat to avoid truncating or
* zero-padding its contents, which WAL replay cannot repair.
*/
```

These are really nit comments, feel free if you don’t want to take them.

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

#6Michael Paquier
michael@paquier.xyz
In reply to: David Steele (#1)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

On Sat, Oct 24, 2026 at 09:34:56PM +0000, David Steele wrote:

For files that are not relation files, fstat() the opened file and use that
stat for the tar header and the backup manifest. Since the rename is atomic
the opened file is always complete. Relation files are not replaced this way
and are still sent using the earlier stat

+    if (!RelFileNumberIsValid(relfilenumber) && fstat(fd, statbuf) != 0)
+        ereport(ERROR,
+                (errcode_for_file_access(),
+                 errmsg("could not stat file \"%s\": %m", readfilename)));

I'm not much a fan of clobbering the stat data given in input. It's
true that it should not matter in practice for the current state of
the code on HEAD, but such practice never gives me a warm feeling as
it makes harder to track the state of the operations across the stack
of function calls. So perhaps make a copy of the input value and
update the copy if we're dealing with a non-relation file for the
mew fstat() you are adding?

Calling fstat() for every file
would be simpler, but using the earlier stat for relation files means that
data added to relation files after the stat is not copied. WAL replay will
restore that data anyway so copying it is wasteful.

Calling fstat() for everything or passing around a more consistent
picture of the stats data was my first feeling here, but yes, I'd side
with your argument that for non-relation files this is a waste as we
would send over the wire data that could be rebuilt from the WAL
anyway. The window is between the lstat() in sendDir() and the
OpenTransientFile() in sendFile(), which should be short in practice,
but I've also seen numerous systems where such short windows could
take seconds depending on what the CPU considers doing. At least
things are clearly designed so as we don't send unnecessary data over
the wire if we know that WAL will have it anyway.

You have a few more funky cases here, I think:
- If a file is truncated after the fstat(), we still send a
zero-filled file worth the initial size reported. pg_verifybackup
considers that as OK.
- File grown in place after the fstat().

None of these stand as far as we can rely on an atomic rename() with a
temporary file. You have looked at the core code and checked that we
do not have paths that use a different practice than the usual tmp
file+rename, and did not find anything fishy, right? I have double
checked myself, just to be on the safe side, but things are paired
with WAL records (2PC files, logical decoding mappings, etc.).
--
Michael

#7Michael Paquier
michael@paquier.xyz
In reply to: David Steele (#3)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

On Sun, Oct 25, 2026 at 06:01:09PM +0000, David Steele wrote:

I confirmed with injection points as well but was not sure it was worth
adding them to the patch since the fix is pretty straightforward.

If you want to post a patch with an injpoint test, please feel free to
post it to let someone else a way to reproduce a given problem.
They're useful for the purpose of reproducing an issue. Now I don't
think that this specific one is worth having in the tree, that feels
like a waste of test cycles.

I found one more file with the same problem. A checkpoint rewrites
pg_twophase files in place with O_TRUNC. If the backup copies one
right after the truncate, it gets an empty file.

Good catch. My audit noticed this truncate but failed to note that the file
would be accessed before WAL replay reconstructed it.

Ugh. F%$k.

Since v1 can't help here it should probably be a separate patch. Or, we
could include it as the first patch in a set with mine.

Minor releases are soon but these bugs are so old that I'm not sure it makes
sense to rush.

I would not mind acting on these. Both of you are pointing to two
different problems: they deserve two patches, one each.

I'd suggest to wait a bit for Robert a bit in case he'd like to
comment on the file size expectation of the on-disk stash advice file.
Saying that, could you adjust the 2PC file? I'd just fix that now and
be done with it..

At this point it
would be good to get some feedback from a committer to see how they want to
proceed.

Done.
--
Michael

#8shihao zhong
zhong950419@gmail.com
In reply to: Michael Paquier (#7)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

Hi Michael,

Saying that, could you adjust the 2PC file? I'd just fix that now
and be done with it..

Here it is, with David's points addressed. The temp file is renamed
into place and restoreTwoPhaseData() removes stale ones at startup.

Thanks,
Shihao

Attachments:

nocfbot-twophase-tmp-rename-REL14-16.txttext/plain; charset=US-ASCII; name=nocfbot-twophase-tmp-rename-REL14-16.txtDownload+35-7
nocfbot-twophase-tmp-rename-master.txttext/plain; charset=US-ASCII; name=nocfbot-twophase-tmp-rename-master.txtDownload+35-7
#9David Steele
david@pgbackrest.org
In reply to: Michael Paquier (#6)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

On 10/26/26 05:13, Michael Paquier wrote:

On Sat, Oct 24, 2026 at 09:34:56PM +0000, David Steele wrote:

I'm not much a fan of clobbering the stat data given in input. It's
true that it should not matter in practice for the current state of
the code on HEAD, but such practice never gives me a warm feeling as
it makes harder to track the state of the operations across the stack
of function calls. So perhaps make a copy of the input value and
update the copy if we're dealing with a non-relation file for the
mew fstat() you are adding?

Sure thing. This does make the patch larger, but nothing scary looking
that I can see. Done in v2.

Calling fstat() for every file
would be simpler, but using the earlier stat for relation files means that
data added to relation files after the stat is not copied. WAL replay will
restore that data anyway so copying it is wasteful.

Calling fstat() for everything or passing around a more consistent
picture of the stats data was my first feeling here, but yes, I'd side
with your argument that for non-relation files this is a waste as we
would send over the wire data that could be rebuilt from the WAL
anyway. The window is between the lstat() in sendDir() and the
OpenTransientFile() in sendFile(), which should be short in practice,
but I've also seen numerous systems where such short windows could
take seconds depending on what the CPU considers doing.

Yes, this gap is what concerns me. We assume these errors are rare since
there have been no field reports but in practice it may also be because
they would be almost impossible to reproduce.

At least
things are clearly designed so as we don't send unnecessary data over
the wire if we know that WAL will have it anyway.

Right.

You have a few more funky cases here, I think:
- If a file is truncated after the fstat(), we still send a
zero-filled file worth the initial size reported. pg_verifybackup
considers that as OK.

Yeah, I've never been too excited about this but it is a limitation of
the tar format that the file size needs to be known in advance of
sending bytes.

For relation files this is harmless since the zero-bytes will be
overwritten during WAL replay. This fix handles the case of replaced
files so their size should be stable during the copy.

- File grown in place after the fstat().

For relation files this is fine. We ignore the extra bytes and they are
reconstructed by WAL replay. Non-relation files should not grow since we
do the fstat() after open() and replaced files should never be modified.

None of these stand as far as we can rely on an atomic rename() with a
temporary file.

After this patch is applied that should be true.

You have looked at the core code and checked that we
do not have paths that use a different practice than the usual tmp
file+rename, and did not find anything fishy, right?

Yes, but I missed pg_twophase on the first pass. In this case the trick
was that the file *is* WAL-logged but then accessed before WAL replay
reconstructs it. It is possible to fix that, maybe, but it would be a
much larger change.

I have double
checked myself, just to be on the safe side, but things are paired
with WAL records (2PC files, logical decoding mappings, etc.).

My hope is that all the eyeballs have caught the only problematic case
(2pc) but we'll need to be careful when adding new files in the future.
If all the examples in the code are correct it should be easier to get
it right.

Regards,
-David

Attachments:

t254374_9
basebackup-replaced-file-v2.patchtext/plain; charset=UTF-8; name=basebackup-replaced-file-v2.patchDownload+26-10
#10David Steele
david@pgbackrest.org
In reply to: Chao Li (#5)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

On 10/26/26 01:48, Chao Li wrote:

Thanks for the patch. Overall LGTM. A couple of really nit comments:

I agree with your comment simplifications. Sometimes I use the comments
as a way to check my work but you are right that they were on the
verbose side. I reworded and added one example, but mostly kept your
wording.

That was done in v2, which was attached to my prior message with the
change Michael requested.

Regards,
-David

#11Michael Paquier
michael@paquier.xyz
In reply to: David Steele (#9)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

On Mon, Oct 26, 2026 at 10:36:30AM +0000, David Steele wrote:

My hope is that all the eyeballs have caught the only problematic case (2pc)
but we'll need to be careful when adding new files in the future. If all the
examples in the code are correct it should be easier to get it right.

I would bet a coin that somebody will include in the core code files
that break this rule at some future point. Perhaps we should be more
aggressive in terms of in-core backend sanity checks. I am not sure
what these would look like, though, and I doubt that such a thing
would be worth the long-term maintenance cost vs the number of issues
avoided.

The backpatches for v15 and v16 were not that complicated, as you said
I have just used a boolean to track if we are working on a relation
file or not and expanded sendFile() with one argument. One thing that
I have left out of the picture is v14. It is going to be EOL with the
next round of minors, and the races are edgy enough that I did not see
this branch as worth taking a risk.
--
Michael

#12David Steele
david@pgbackrest.org
In reply to: Michael Paquier (#11)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

On 10/27/26 06:02, Michael Paquier wrote:

On Mon, Oct 26, 2026 at 10:36:30AM +0000, David Steele wrote:

My hope is that all the eyeballs have caught the only problematic case (2pc)
but we'll need to be careful when adding new files in the future. If all the
examples in the code are correct it should be easier to get it right.

I would bet a coin that somebody will include in the core code files
that break this rule at some future point.

There is no way I am taking that bet.

Perhaps we should be more
aggressive in terms of in-core backend sanity checks. I am not sure
what these would look like, though, and I doubt that such a thing
would be worth the long-term maintenance cost vs the number of issues
avoided.

Hopefully having correct examples to copy from will help, otherwise this
is the purpose of review. I can't think of any way to fool-proof it.

The backpatches for v15 and v16 were not that complicated, as you said
I have just used a boolean to track if we are working on a relation
file or not and expanded sendFile() with one argument. One thing that
I have left out of the picture is v14. It is going to be EOL with the
next round of minors, and the races are edgy enough that I did not see
this branch as worth taking a risk.

Agreed, my worry on putting anything like this into the soon-to-be-EOL
release is that if we get it wrong that's a net negative for that release.

I don't know of any instances of this race actually happening in the
wild, and since pgBackRest has never had the issue I don't have any data
from that side.

Thank you for reviewing and committing!

Regards,
-David

#13Robert Haas
robertmhaas@gmail.com
In reply to: Michael Paquier (#7)
Re: Avoid truncated or zero-padded copies of replaced files in backups.

On Mon, Oct 26, 2026 at 12:21 AM Michael Paquier <michael@paquier.xyz> wrote:

I'd suggest to wait a bit for Robert a bit in case he'd like to
comment on the file size expectation of the on-disk stash advice file.
Saying that, could you adjust the 2PC file? I'd just fix that now and
be done with it..

I don't think we should be too fussed about cases like this.
Generally, the reason we rename files into place instead of just
overwriting random bytes is so that readers will see either the old or
the new version, and not some mix of old and new contents. David's
original report surfaces a case where that doesn't happen: we might
take the length of one file and then use it for a completely different
file that is meanwhile renamed into place. Fixing that makes renaming
into place work the way writers already expect it to work. I don't see
why we need to do better. If there are other cases where
rename-into-place doesn't work, I'd tend to favor trying to cut those
problems off at the source rather than complicating file formats.

Now, that's not to say that having some kind of end-of-file marker is
completely without merit. It could catch manual modifications of
files, hardware problems, software errors -- generally, failure modes
that we otherwise wouldn't notice. On the other hand, isn't it kind of
nice that the stash file format is just a plain old TSV that anyone
can edit if they so desire? I judge that to have non-zero value, and
if we add checksums or end-of-file markers or other frammishes, we
lose that property, obviously to varying degrees depending on what
exactly we do.

--
Robert Haas
Databricks