mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:50:37 +00:00
util: write JSON atomically in WriteJson #35763
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35763
Loading…
Reference in a new issue
No description provided.
Delete branch "banlist-atomic-write-json-unsafe"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Follow-up to https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299
common::WriteSettingstocommon::WriteJson.WriteJsonwrites topath + ".tmp"andRenameOver()s into place, so a failed or interrupted write cannot leave a truncated destination. Bothsettings.jsonandbanlist.jsonuse this helper..tmpis gone after success, that rename failure is detected, and that a second failed write overwrites the same.tmprather than creating another.The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
Concept ACK
Thanks for picking these up.
cc: @sys-dev @ryanofsky
ACK 07ec5af152b5bcff1b74decb9c7b729dff6c2283, with two non-blocking observations:
The test is useful, but it also passes when CBanDB::Write is changed back to direct writing. Negative control proved this. It therefore does not verify the rename behavior named by the test.
The generalized WriteJsonUnsafe helper still reports “settings file” errors when writing banlist.json.tmp. “JSON file” or “file” would be accurate for both callers.
these need attention. so, i think they are blocking
while going through this, another thought came to mind. right now
WriteJsonUnsafewrites directly to whatever path it is given and relies on the caller to do the tmp-file +RenameOver()step. both current callers (args.cppandaddrdb.cpp) do this correctly, but that guarantee only lives in a comment. nothing stops a future caller from accidentally writing straight to a live filei was wondering if it is worth making this a bit harder to misuse. two possible approaches came to mind
approach A: add
WriteJsonAtomicalongsideWriteJsonUnsafekeep the low-level helper as-is, but add a wrapper that handles the tmp-file + rename step:
callers become:
this keeps the current API intact while giving callers a safe helper for the common case. existing callers with custom tmp-file handling can keep using
WriteJsonUnsafe, while new callers can just useWriteJsonAtomic. the downside is that the footgun is still there.WriteJsonUnsafeis still publicly available, so a future caller can still accidentally bypass the atomic write path. it also means carrying two helpers that are closely relatedapproach B: make the helper always write atomically
this is quite similar to the idea @sys-dev suggested here.
instead of exposing both APIs, make the helper always write to a tmp file and rename it:
this makes the safe path the only path. every caller gets atomic writes by default, so it is no longer possible to accidentally write directly to a live file. the tradeoff is that every caller now gets
.tmp+RenameOver()semantics, even if a future use case genuinely just wants "write these bytes to this exact path" (for example, a one-off dump or export). it also bakes the tmp-file naming scheme into the helper itselfmy thinking: i lean toward approach B unless there is already a use case for exposing the raw write helper. it feels a bit simpler, and it removes the footgun instead of just documenting it. that said, i could easily be missing a future use case where writing directly to the given path is the better choice
any thoughts ?
@Herb-ops @winterrdog, can you review this again?
approach ACK
now, we can update the PR title & description to match what the current code
actually does. they still mention
WriteJsonUnsafeand callers doing theatomic rename, while the current implementation is self-contained and handles
the "temp write +
RenameOver()" itselfpremise: cleaning up
path_tmpin case one of the error pathsis explored
currently,
WriteJson()returnsfalsebut leaves the.tmpfile behind.the new test (
write_uses_rename) actually has to manually removebanlist_atomic.json.tmpafter exercising the error paths, so it lookslike we can leave stale temp files around in cases like persistent permission
problems, an antivirus file lock on Windows, or repeated rename failures,
these temp files are most likely to accumulate indefinitely
would a best-effort
fs::remove(path_tmp)on the failure path make sensehere, or do you prefer leaving the temp file around?
if implemented, one of the tradeoffs i can easily think of is the loss of
forensic evidence when debugging persistent failures.
any thoughts ?
I prefer leaving it.
The tmp name is stable (path + ".tmp"), so a later attempt opens the same file and overwrites it. You get at most one leftover per destination, not an accumulating set. That matches the old settings.json write, which also left the .tmp on rename failure.
The fs::remove(...tmp) in the test is just fixture cleanup.
I can amend the commit to add a test that asserts we don't create endless tmp files
Added this test
https://github.com/bitcoin/bitcoin/pull/35763/changes/0260a681e1f15d57b0ddf57b8bb539d8ac3dc577#diff-8e202c9cf7b0629a40c224318626d23656c0366a1f4b98f8a34ed62f7691a161R73-R81
@winterrdog let me know if this looks good to you
:( this has dragged on for quite some time. the approach and code work fine but i spotted an API naming issue that i think is worth discussing.
currently,
WriteSettingswas renamed toWriteJson, butReadSettingskept its old name. so we now have aWriteJson/ReadSettingspair that operates on the same kind of data, but has different names (asymmetry)so, i see 3 potential directions:
A. keep the
ReadSettings/WriteSettingspairprobably the simplest fix for this PR. these functions are not really generic JSON helpers anyway: they assume a flat
map<string, SettingsValue>and handle the_warning_key. the downside is that havingWriteSettingswrite to something likebanlist.jsonfeels a little oddB. rename both to a
ReadJson/WriteJsonpairthis fixes the asymmetry with a small change. the downside is that
WriteJsonsounds more generic than it actually is, because it would still have settings-specific behavior like adding the_warning_key.C. extract the generic JSON functionality from the settings functionality into separate functions
for example, have generic
ReadJsonFile/WriteJsonFilehelpers underneath, then keepReadSettings/WriteSettingsas thin wrappers for the settings-specific behavior.this seems like the cleanest long-term design if we expect more JSON-backed files to use this code, but probably more work than this PR expected.
any thoughts on this ?
makes sense. i concur
yes! good, it is
Thank you for the review, and yeah, I agree that it's strange to have them different like that. I pushed ed55f14 to do path A.
We can do a follow-up for C if we want after this is merged.
that is fine. we can do that
tACK
ed55f14404successfully built and tested on FreeBSD
15.0/clang++-19.1.7/x86_64. the changes herein LGTM as well🔵 Suggestion · Failure test does not check preservation of the previous banlist
The test deletes the valid banlist before forcing failure, so it never checks that a failed update leaves the last good banlist readable.
Location:
src/test/banman_tests.cpp:69(head).🔵 Suggestion · PR description claims a
WriteJsonrename absent from the patchThe PR title and description refer to
WriteJson, but the helper and both callers still usecommon::WriteSettings.Location:
src/common/settings.h:48(head).🔵 Suggestion · Atomic banlist replacement changes operator-managed file layouts
Replacement changes symlink, file bind-mount and custom-permission behavior for
banlist.json; documenting these upgrade effects would help, although no affected deployment was identified and the platform-specific failure was not experimentally observed.Location:
src/common/settings.cpp:153(head).🔵 Suggestion · Use different data to test repeated failed writes
Both failed writes in the rename-failure block (
src/test/banman_tests.cpp:71-72) pass the samebans_write. The block checks only thatbanlist_atomic.json.tmpexists and that exactly one.tmpfile is present, never what the file contains. A regression that appended to the existing temp file instead of truncating it would still pass. So the PR description's claim that the test shows a second failed write overwrites the same.tmpis only half checked: the test confirms the name is reused, not that the contents are replaced.Location:
src/test/banman_tests.cpp:71(head).Review coverage was incomplete.
Reviewed:
9f2077dc09c9· Review report · Previous reportspermalink
Code review ACK
ed55f14404. Thanks for following up on #35384 and for the test of the rename failure path.In commit "util: atomically write banlist.json and settings.json" (
ed55f14404)Nit: now that the function is called
WriteSettingsagain, this function's behavior doesn't change, so the restructuring here could be dropped to keep the diff to the files that actually change. Fine either way.In commit "util: atomically write banlist.json and settings.json" (
ed55f14404)This ended up different from what I suggested in https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299, and from an earlier version of this PR: keep
WriteSettingsa low-level function that writes the path it is given, rename it to make clear it is unsafe to use withoutRenameOver, and have callers do the rename. I still slightly prefer that, because I like functions that do one thing well, and once a write function also manages the temporary file it has to make choices for every caller (how the temporary file is named, whether to fsync) that some callers might want to make differently. But I don't see a problem with the current approach, and it is simpler for the two callers that exist now, so please go with whichever makes more sense to you.In commit "util: atomically write banlist.json and settings.json" (
ed55f14404)The commit message should say what behavior changes. It is only a title now, and since the commit also moves code around (the
.tmphandling moves fromWriteSettingsFileintoWriteSettings,GetSettingsPathloses itstempparameter,CBanDB::Writeis restructured), the diff makes it hard to see what the actual change is:banlist.jsonused to be written in place and is now written through a temporary file, whilesettings.jsonis written the same way as before. I'd suggest something like:It would be even easier to review as two commits: first a small commit that changes
CBanDB::Writeto writebanlist.json.tmpand callRenameOveritself, with the new test, so the behavior change is a few lines on its own; then a refactoring commit that moves the.tmphandling intoWriteSettingsand removes it from both callers, with no behavior change other than the error wording.The PR title and description also still say
WriteJson, and they go into the merge commit, so they should be updated to match too.In commit "util: atomically write banlist.json and settings.json" (
ed55f14404)Non-blocking: this protects against the process being killed or failing partway through the write, but since nothing calls fsync before the rename, a power loss can still leave an empty file on some filesystems (
SerializeFileDBinaddrdb.cppcallsCommit()before renaming for that reason). Not something this PR needs to fix, but the comment could be more specific so callers don't assume more:In commit "util: atomically write banlist.json and settings.json" (
ed55f14404)Nit:
entryhere shadows theCBanEntry entrydeclared at the top of the test, which made this a little confusing to read.@kevkevinpal do you want to take ryanofsky's suggestions?
Yes, this completely slipped my mind. Will address it right now
Thanks, this is now addressed in
4a0f4916f6Thanks, this is now addressed in
9f2077dc09Thanks, this is now addressed in
9f2077dc09Thanks, this is now addressed in
4a0f4916f6reACK
9f2077dc09successfully built and tested on FreeBSD
15.0/clang++-19.1.7/x86_64.generally, the new changes bring in more clarity which is good for future maintenance
Code review ACK
9f2077dc09.banlist.jsonis now written through a temporary file andRenameOver(), likesettings.json, so a crash or full disk during the write can no longer leave it truncated.Thanks for the updates and the clear commit messages. Remaining comments are minor: the PR title and description still describe the earlier
WriteJsonversion (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563027281), the commits could be simpler, with a minimal fix in the first commit and no second commit (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563653108), and there is a possible follow-up about how a corruptbanlist.jsonis handled (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563647011).In commit "util: write banlist.json through a temporary file" (
4a0f4916f6)The second commit reverts the changes this commit makes to
CBanDB::Write, so across the PRaddrdb.cppdoesn't change at all. That would seem more reasonable if the change being reverted were minimal, but this commit also restructures the function to return early on failure instead of on success, which the fix doesn't need.Ideally I'd like to see (1) this commit reduced to a minimal bugfix without the restructuring, something like:
and (2) the second commit dropped, which would also match the design I'd prefer (https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563641406). But I'm also happy to see this merged as-is, or in any other form that fixes the bug.
In commit "refactor: move .tmp handling into common::WriteSettings" (
9f2077dc09)Note: not for this PR, but a possible follow-up. The PR makes a truncated
banlist.jsonless likely, but the way the truncated file is handled still seems unsafe to me. A truncatedsettings.jsonfails to parse and is reported as an error at startup. A truncatedbanlist.jsonfails to parse the same way, butCBanDB::Readonly logs a warning, andBanMan::LoadBanlistresets to an empty banlist, which theBanManconstructor immediately writes over the corrupt file. So the bans are lost, and the file that would show what happened is gone.re: https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4484447375
A small example of this is error messages. Because
WriteSettingsis now shared by two kinds of files, this PR changes its errors from "settings file" to "JSON file", which is less clear forsettings.json.ReadSettingshas the opposite problem: its parse error talks about a settings file and says removing it "will reset settings to default values", which is wrong forbanlist.json(https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4563647011). This PR doesn't changeReadSettings, so it doesn't make that harder to fix, but in both cases the caller is what knows which file it is (CBanDB::Readalready adds "Cannot load banlist" to the message) and what happens if it is removed. I think messages are easier to get right if low-level functions just read and write JSON and callers add the context as I originally suggested https://github.com/bitcoin/bitcoin/pull/35384#issuecomment-4750866299. Still not a blocker for me.re: https://github.com/bitcoin/bitcoin/pull/35763#discussion_r4554141085
Thanks, the two commits are easier to review now. The PR title and description still describe the earlier version though (
WriteJson, renamingWriteSettings).