Skip to content

Check close() before publishing temp files with rename() in AOF manifest, CONFIG, ACL and replica RDB load - #4594

Open
KewangZhili wants to merge 4 commits into
valkey-io:unstablefrom
KewangZhili:fix-close-before-rename
Open

KewangZhili wants to merge 4 commits into
valkey-io:unstablefrom
KewangZhili:fix-close-before-rename

Conversation

@KewangZhili

@KewangZhili KewangZhili commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #4489, opened at @enjoy-binbin's suggestion there: he asked whether RDB/AOF/CONFIG/ACL share the close-before-rename problem being fixed for nodes.conf. They do.

The problem

A write error the kernel deferred is not reported by write() or fsync() — only by close(). Publishing a temp file with rename() before checking close() can therefore install a truncated file over a good one.

write()  ──▶ ok        (buffered, error not yet surfaced)
fsync()  ──▶ ok        (does not surface a deferred error either)
rename() ──▶ published ◀── truncated file is now live
close()  ──▶ EIO       ◀── too late, and the result was discarded

Audit of every rename() in src/

Path closes before rename() result checked
RDB save, rdb.c:1690 → rename 1743 yes yes already correct
AOF rewrite, aof.c:2555 → rename 2563 yes yes already correct
AOF manifest, rename aof.c:567 no no fixed
CONFIG REWRITE, rename config.c:1817 no no fixed
Replica RDB load, rename replication.c:2620 no no fixed
ACL, acl.c:2788 → rename 2792 yes no fixed

RDB save and AOF rewrite already do it right and are the precedent followed here. One commit per subsystem.

Impact

  • AOF manifest is the closest analogue to nodes.conf: small, rewritten on every AOF state change, and aofLoadManifestFromFile() refuses to start on a corrupt manifest.
  • Replica RDB load publishes the file a replica will then load and persist.
  • CONFIG REWRITE is operator-triggered, so less exposed, but a truncated config is silently persisted.
  • ACL already had the ordering right; only the check was missing.

Notes on each change

AOF manifest — close and check between the fsync() and the rename(). The error path leaves the temp manifest behind, matching the existing fsync()-failure path.

CONFIG REWRITE — fchmod() needs the descriptor, so the close goes between it and the rename. That turns the fsync/fchmod/rename/fsyncFileDir else-if chain into guard clauses. Short-circuiting is unchanged: the first failure logs, leaves retval at -1, and reaches cleanup:, which unlinks the temp. The cleanup close() is now guarded against a double close, and close_errno is placed in errno so the caller still gets a meaningful error, as the function contract promises.

ACL — check the existing close().

Replica RDB load — this one needs care. The descriptor cannot simply be closed and set to -1, because cleanupTransferResources() asserts that repl_transfer_fd and repl_transfer_tmpfile are unset together:

if (server.repl_transfer_fd == -1) {
    serverAssert(server.repl_transfer_tmpfile == NULL);
    return;
}
serverAssert(server.repl_transfer_tmpfile != NULL);

Every error path in replicaLoadPrimaryRDBFromDisk() reaches that function via cancelReplicationHandshake(), so clearing only the descriptor makes the assertion fail and takes the replica down. I confirmed that by building it: the replica dies with === ASSERTION FAILED ===.

So the filename is taken into a local instead and both fields are cleared at once, with the temp file unlinked and freed on the paths that previously relied on cleanupTransferResources() to do it. rdbLoad() reopens the file by name, so nothing needs the descriptor after the close.

Every exit leaves the pairing intact:

Exit repl_transfer_fd repl_transfer_tmpfile
fsync fails (before the change) open set — unchanged
close fails -1 NULL, freed
rename fails -1 NULL, freed
fsyncFileDir / rdbLoad fail -1 NULL, freed
success -1 NULL, freed

Tests

Replica survives a full sync whose RDB rename fails obstructs the rename by turning the replica's dbfilename into a directory, giving EISDIR, which reaches the teardown above with the descriptor already closed. It asserts the replica is still answering, that a retry then syncs, and that no temp RDB is left behind.

Its value is guarding the pairing, so I checked it actually does that:

Build Result
before this change passes (fd open + filename set is self-consistent)
with this change passes
descriptor cleared without the filename === ASSERTION FAILED ===

1148 tests pass across unit/acl, unit/acl-v2, unit/introspection, unit/introspection-2, unit/other, unit/auth, unit/info, unit/info-command, unit/commandlog, integration/aof, integration/aof-multi-part, integration/rdb, integration/replication{,-2,-3,-4,-psync,-buffer}, integration/dual-channel-replication, unit/cluster/diskless-load-swapdb, and the cluster suites that call CONFIG REWRITE.

No test covers a failing close() itself: it cannot be forced from Tcl, the same limitation noted in #4489. No existing test asserts on these failure messages, so the CONFIG restructure changes no expectations. On-disk formats are unchanged.

Still not addressed: open handles across a rename

Separate from the integrity bug above, two places deliberately hold a handle across a rename. replication.c opens the rename destination on purpose so bioCreateCloseJob() can drop the old inode off the main thread, and aof.c:2828 renames the temp incr AOF while server.aof_fd is still appending to it. Both are correct on POSIX and are not integrity bugs, but they are why AOF and replica full-sync still fail on SMB-backed volumes. Neither #4489 nor this PR makes Valkey generally SMB-safe.

Himangshu Deka added 2 commits September 2, 2026 11:49
writeAofManifestFile() writes the manifest to a temp file and renames it over
the real one, but it renames while the temp file's descriptor is still open and
only closes it afterwards in the cleanup block, discarding the result.

A write error the kernel deferred is not reported by write() or fsync(), only
by close(). Because close() runs after the rename and its return value is
thrown away, a short write can be published as the live manifest.
aofLoadManifestFromFile() refuses to start on a corrupt manifest, so the node
would fail to load its AOF on the next start.

The manifest is the AOF analogue of nodes.conf: small, rewritten on every AOF
state change, and fatal to the load path when corrupt. Close the descriptor
before the rename and check the result, so the temp file is only published once
it is known to be complete. rdbSaveInternal() and rewriteAppendOnlyFile()
already do this.

Signed-off-by: Himangshu Deka <[email protected]>
rewriteConfigOverwriteFile() renames the temp config over the real one while
the temp file's descriptor is still open, and closes it afterwards in the
cleanup block, discarding the result. A write error the kernel deferred is
reported only by close(), so a truncated config file can be published.

Close the descriptor before the rename and check the result. The fchmod() call
needs the descriptor, so the close goes between it and the rename, which turns
the fsync/fchmod/rename/fsyncFileDir else-if chain into guard clauses. The
short-circuiting behaviour is unchanged: the first failure logs, leaves retval
at -1 and reaches the cleanup label, which unlinks the temp file. The cleanup
close() is now guarded so the descriptor is not closed twice, and close_errno
is placed in errno so the caller still sees a meaningful error, as the function
contract promises.

Signed-off-by: Himangshu Deka <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 0881637b-f392-4037-a3e4-1043a032b05a

📥 Commits

Reviewing files that changed from the base of the PR and between 439e7cf and 23c175f.

📒 Files selected for processing (1)
  • src/acl.c

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

Temporary ACL, AOF manifest, configuration, and replication RDB files now check close() results before rename(). Failures prevent publication and trigger cleanup. Replication tests cover rename failure recovery and temporary file removal.

Changes

Atomic file publication

Layer / File(s) Summary
ACL and AOF close validation
src/acl.c, src/aof.c
ACL and AOF manifest writers detect close-time write errors before renaming temporary files. Failed closes prevent replacement and avoid double-closing descriptors.
Configuration rewrite close validation
src/config.c
Configuration rewrites close the temporary file before rename(), preserve close errors, and use guarded cleanup.
Replication temporary file cleanup
src/replication.c, tests/integration/replication.tcl
Disk-based replication cleans up temporary RDB files after close or rename failures. Integration coverage verifies recovery, replicated data, and cleanup.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Merge Risk: ⚪ Minimal · up to 23c17

ACL file saves now avoid publishing a temporary file when closing it reports a deferred write error, preserving the existing ACL file instead. No merge-blocking risk remains.

Suggested reviewers: enjoy-binbin

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: checking close() results before publishing temporary files with rename() across the affected subsystems.
Description check ✅ Passed The description directly explains the deferred close() error problem, the affected code paths, cleanup behavior, and test coverage.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@KewangZhili KewangZhili changed the title Check close() before publishing temp files with rename() in AOF manifest, CONFIG and ACL Check close() before publishing temp files with rename() in AOF manifest, CONFIG, ACL and replica RDB load Sep 2, 2026
Comment thread src/acl.c Outdated
* published, or a truncated file replaces a good one. */
if (close(fd) == -1) {
fd = -1;
serverLog(LL_WARNING, "Closing temp ACL file for ACL SAVE: %s", strerror(errno));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the message is stating an action ("closing"), while it should be stating that the action failed.

Use something similar to the message below:

serverLog(LL_WARNING, "Failed to close temp ACL file for ACL SAVE. %s.", strerror(errno));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 23c175f, used your wording — thanks!

Himangshu Deka added 2 commits September 3, 2026 12:11
ACLSaveToFile() already closes the temp file before renaming it into place, but
discards what close() returns. A write error the kernel deferred is not
reported by write() or fsync(), only by close(), so a short write can still be
published as the live ACL file.

Check the result and abort the save instead, leaving the previous ACL file in
place.

Signed-off-by: Himangshu Deka <[email protected]>
replicaLoadPrimaryRDBFromDisk() renames the fully received temp RDB over the
persistence file while the transfer descriptor is still open, and closes it
afterwards, only on the success path. A write error the kernel deferred is
reported by close() and by nothing before it, so a short write could be
published as the node's RDB.

Close the descriptor before the rename and check the result. rdbLoad() reopens
the file by name, so the descriptor is not needed past that point.

The descriptor cannot simply be closed and set to -1, because
cleanupTransferResources() asserts that repl_transfer_fd and
repl_transfer_tmpfile are unset together, and every error path here reaches it
through cancelReplicationHandshake(). Clearing only the descriptor makes that
assertion fail and takes the replica down. Take ownership of the filename
locally instead and clear both fields at once, then unlink and free the temp
file on the paths that previously relied on cleanupTransferResources() to do
it.

The added test obstructs the rename by turning the replica's dbfilename into a
directory, which reaches that teardown with the descriptor already closed. It
passes before this change and with it, and fails with an assertion if the
descriptor is cleared without the filename.

Signed-off-by: Himangshu Deka <[email protected]>
@rainsupreme

Copy link
Copy Markdown
Contributor

Sorry for the long wait on this one! Are you still interested in working on this PR? We hope to review it in the next couple of weeks. If you are, please take care of these first:

  • Rebase or merge with unstable and resolve the merge conflicts.

🤖 Comment by Robo-Rain, for my human

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants