Skip to content

add atomic saving via .tmp files and ReplaceFileW for Windows - #527

Merged
nschimme merged 1 commit into
MUME:masterfrom
nschimme:add-atomic-win
Apr 20, 2026
Merged

add atomic saving via .tmp files and ReplaceFileW for Windows#527
nschimme merged 1 commit into
MUME:masterfrom
nschimme:add-atomic-win

Conversation

@nschimme

@nschimme nschimme commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

Summary by Sourcery

Add atomic file saving support using temporary files and platform-specific rename semantics, including proper fsync handling on Windows.

Bug Fixes:

  • Ensure file data is reliably flushed to disk on Windows by implementing fsync via FlushFileBuffers.
  • Perform atomic renames on Windows using ReplaceFileW with a MoveFileExW fallback when the target file does not exist.

Enhancements:

  • Unify temporary file save behavior across platforms by always writing to .tmp files and renaming them via a shared io::rename helper.

@sourcery-ai

sourcery-ai Bot commented Apr 20, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds atomic file saving support via temporary .tmp files, implementing a cross‑platform io::rename (using ReplaceFileW/MoveFileExW on Windows and ::rename elsewhere) and wiring FileSaver to always write to a .tmp and then atomically rename, while also making fsync() functional on Windows via FlushFileBuffers and exception‑based error reporting.

Sequence diagram for atomic file saving with tmp files and io_rename

sequenceDiagram
    actor User
    participant FileSaver
    participant QFile
    participant io
    participant OS

    User->>FileSaver: save(targetFilename)
    FileSaver->>FileSaver: tmpName = targetFilename + .tmp
    FileSaver->>QFile: open(tmpName, WriteOnly)
    FileSaver->>QFile: write(data)
    FileSaver->>QFile: flush()
    FileSaver->>io: fsync(file)
    io->>OS: FlushFileBuffers or fsync
    OS-->>io: success or error
    io-->>FileSaver: return or throw IOException
    FileSaver->>io: rename(tmpName, targetFilename)
    io->>OS: ReplaceFileW or MoveFileExW or rename
    OS-->>io: success or error
    io-->>FileSaver: return or throw IOException
    FileSaver-->>User: save completed or error
Loading

Class diagram for io_namespace helpers and FileSaver tmp_rename integration

classDiagram
    class io {
        +bool fsync(QFile file) CAN_THROW
        +IOResultEnum fsyncNoexcept(QFile file) noexcept
        +void rename(QString from, QString to) CAN_THROW
    }

    class FileSaver {
        -QFile device
        -QString filename
        +~FileSaver()
        -static QString maybe_add_suffix(QString filename)
        -static void remove_tmp_suffix(QString filename) CAN_THROW
    }

    io <.. FileSaver : uses
    FileSaver : maybe_add_suffix returns filename + ".tmp"
    FileSaver : remove_tmp_suffix calls io.rename(from, to)
Loading

File-Level Changes

Change Details Files
Implement functional fsync() on Windows using FlushFileBuffers with proper error propagation.
  • Include <io.h> and <windows.h> when building for Windows so low-level APIs are available.
  • Change Windows fsync(QFile&) implementation from a stub that returns false to a real implementation calling ::_get_osfhandle and ::FlushFileBuffers.
  • Throw io::IOException with the Windows error code from ::GetLastError() if FlushFileBuffers fails, aligning error handling with POSIX branches.
src/global/io.cpp
Introduce io::rename() as a cross-platform atomic rename abstraction with Windows-specific behavior using ReplaceFileW/MoveFileExW.
  • Add io::rename(const QString&, const QString&) in io.cpp with Windows specialization using std::wstring, ReplaceFileW for atomic replacement, and a MoveFileExW fallback when the target does not exist.
  • Use QFile::encodeName plus ::rename on non-Windows platforms and translate failures into io::IOException::withCurrentErrno().
  • Declare the new rename function in io.h for shared use across the codebase.
src/global/io.cpp
src/global/io.h
Make FileSaver always save via a .tmp file and then atomically rename it into place using io::rename.
  • Remove the platform-dependent USE_TMP_SUFFIX flag so that all platforms use the .tmp suffix for temporary save files.
  • Have maybe_add_suffix() unconditionally append ".tmp" to the target filename to form the temporary path.
  • Change remove_tmp_suffix() to call io::rename(from, to) instead of directly invoking ::rename, and construct from/to as filename+".tmp" and filename, respectively, centralizing atomic rename behavior.
src/mapstorage/filesaver.cpp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • In the Windows-specific fsync implementation, consider explicitly checking for an invalid file handle (e.g., handle == -1) and throwing a clearer IOException before calling FlushFileBuffers, so failures are easier to diagnose and don't rely on the Win32 error alone.
  • In io::rename on Windows, you may want to include REPLACEFILE_WRITE_THROUGH in the ReplaceFileW flags to better mirror the durability guarantees expected from an atomic save operation in the presence of power loss.
  • The fallback from ReplaceFileW to MoveFileExW with MOVEFILE_COPY_ALLOWED can lose atomicity when the destination does not yet exist, especially across volumes; if atomic replacement semantics are required, it may be safer to detect cross-volume moves and handle them differently or fail explicitly.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the Windows-specific `fsync` implementation, consider explicitly checking for an invalid file handle (e.g., `handle == -1`) and throwing a clearer `IOException` before calling `FlushFileBuffers`, so failures are easier to diagnose and don't rely on the Win32 error alone.
- In `io::rename` on Windows, you may want to include `REPLACEFILE_WRITE_THROUGH` in the `ReplaceFileW` flags to better mirror the durability guarantees expected from an atomic save operation in the presence of power loss.
- The fallback from `ReplaceFileW` to `MoveFileExW` with `MOVEFILE_COPY_ALLOWED` can lose atomicity when the destination does not yet exist, especially across volumes; if atomic replacement semantics are required, it may be safer to detect cross-volume moves and handle them differently or fail explicitly.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@nschimme
nschimme merged commit 4909061 into MUME:master Apr 20, 2026
18 checks passed
@nschimme
nschimme deleted the add-atomic-win branch April 20, 2026 16:19
@codecov

codecov Bot commented Apr 20, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 25.40%. Comparing base (dd0c268) to head (2b78e99).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
src/global/io.cpp 0.00% 5 Missing ⚠️
src/mapstorage/filesaver.cpp 0.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #527      +/-   ##
==========================================
- Coverage   25.40%   25.40%   -0.01%     
==========================================
  Files         519      519              
  Lines       43109    43113       +4     
  Branches     4699     4699              
==========================================
  Hits        10952    10952              
- Misses      32157    32161       +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

1 participant