fix(saves): longshot_saves.py puts the copies on the disk before the swap #3013
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/mods
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
3 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!3013
Loading…
Reference in a new issue
No description provided.
Delete branch "PedroRossi/Longshot:fix/save-tool-flush"
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
A power loss right after the save tool says Done can lose the save it was protecting.
copy_saves(
scripts/longshot_saves.py) copies the save, backs the target up, then swaps the copy in with renames, and nothing isflushed: nothing orders the copies' data before those renames. On ext4 (Linux, and the Steam Deck's drive and SD
cards) a rename can reach the disk well before the data of the files it moves, so a power cut or a hang in that window
can leave empty or cut files in place of the slots, and the backup the same, with the old save already moved away.
on_disk, called right beforeswap_in, puts the copies on the disk first:os.sync()where Python has it (one call,every file), else each copied file's fsync (Windows).
How to see it on main: nothing shows without a power cut at that moment; the test checks the order (the copies synced
before the swap).
Read first:
on_diskand its call incopy_saves.Testing
Tested: on this PC (Debian 13, ext4 on NVMe): by hand, the real tool exported a save from a game run over
an emulator's (
export --longshot DIR --to DIR --backup-dir DIR), each copy tagged in its last bytes so the twodiffer: the emulator's folder then held Longshot's save, the backup the emulator's old one, Done. The new test fails on main and passes here, with the rest of test_longshot_saves.py; ruff.
mise run test(--strict) on main @1938a302, and on main with this change merged (together with #3009, #3010, #3011, #3012, #3014, from the same audit): 775 passed, 145 failed, 10 skipped both ways, so none fails only with it. The 145 are named at the end.Still to test:
one: that branch didn't run here)
Measurements
Verdict: an import or export takes about 8 ms more on this PC (the median), once per copy.
Setup: Debian 13, ext4 on NVMe, through the PC's job queue (
timing-cpu: nothing else running); the wholeexportcommand for a real save (account.sav, option.sav, one slot) over another, with a backup; main's script and this one
alternating, 9 runs each.
1938a302e8cfa476Risks
os.sync()flushes all of the system's pending writes, not only the copies': with much pending (a big copy justbefore, a slow SD card) Done comes a little later. The tool is run by hand, once per copy. A revert is enough.
Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
mainand passes here.tests/that reads changed source is updated, not weakened.Assisted-by:/Co-Authored-By:trailers.Ready to merge
main, measured again or a comment says why the numbers still hold.The 145 checks of
mise run testthat fail on main @1938a302on this PC too, with or without this change97 need a tool this PC doesn't have on PATH (
--strictfails them):48 fail on main itself: test_blocks_at_start.py, test_bug_report.py, test_cloth_kernels.py, test_cloth_loops.py, test_cloth_sphere.py, test_cloth_step12.py, test_cloth_step8.py, test_cloth_step9.py, test_control_picture.py, test_crash_record.py, test_crt_options.py, test_dev_update.py, test_dlssg_pace.py, test_draw_stream_visibility.py, test_framegen_resources.py, test_fsr_uniform_ownership.py, test_game_boundary.py, test_guest_holes.py, test_image_reaper_threads.py, test_image_view_retry.py, test_input_background.py, test_keyboard_option.py, test_linux_pressure.py, test_loaded_modules_drop.py, test_log_levels.py, test_menu_keys.py, test_menu_save_atomic.py, test_mesh_first_types.py, test_oot_occ_raster.py, test_option_ids.py, test_perf_send.py, test_pipeline_tour.py, test_present_acquire_ahead.py, test_present_image_free.py, test_present_source_crop.py, test_program_cache_cleanup.py, test_program_cache_one_variant.py, test_readback_timeout_reuse.py, test_recording_admission.py, test_screensaver.py, test_switch_table.py, test_target_retention.py, test_tex_desc_memo.py, test_thinlto_tls.py, test_upscaler_round_trip.py, test_vram_compact.py, test_windows_display_startup.py, test_windows_on_linux.py
Found in an AI-assisted audit of the repository. The test, the fix, the runs and this description were made with Claude Code; I reviewed them.
Co-Authored-By: Claude Opus 5.5 [email protected]
🤖 Generated with Claude Code
WIP: fix(saves): longshot_saves.py puts the copies on the disk before the swapto fix(saves): longshot_saves.py puts the copies on the disk before the swapTested again by hand with the two saves made different (each copy's option.sav and slot_00/caption.sav tagged in their last 8 bytes): the emulator's folder got Longshot's save and the backup the emulator's old one. The copies in the first run came from the same game save, so its byte-for-byte check could not have failed.
@review
Recommendation: Request changes. The copies are flushed before the swap, but the completed swap is not made durable, and Windows can silently skip failed flushes. Both cases can leave a save missing or incomplete after the tool reports success.
The tool flushes copied save data before replacing the target. This reduces one power-loss risk, but it does not yet guarantee that a completed transfer or its Windows backup survives a power loss. The Linux measurement shows an 8 ms median cost on the tested NVMe system.
Blocking (2): must change before merging.
scripts/longshot_saves.py:478: The flush precedes every rename, but nothing makes the resulting directory entries durable before reporting Done. (more on the line) Do: Make the swap and the relevant parent directory entries durable before deleting the old entries and reporting success, using the appropriate platform-specific durability operations and error handling.scripts/longshot_saves.py:505: The Windows fallback ignores every open or fsync failure and proceeds with the swap. (more on the line) Do: Flush read-only copies with a suitable handle or safely adjust their attributes, and propagate traversal, open and flush failures so the swap is not started when durability cannot be established.Should fix (1): not blocking, but worth doing before merging.
tests/test_longshot_saves.py:417: The new test creates os.sync on every platform, so it never exercises the Windows per-file flush path. (more on the line) Do: Add a test that forces the no-sync path and checks that incoming and backup files are flushed before the swap, including a flush failure and a read-only copied file.Testing before merging (1) (runs on the systems it can change; it doesn't hold the recommendation)
scripts/longshot_saves.py:497: The timing does not cover the system-wide flush when other applications have substantial dirty data or the saves are on slow storage. (more on the line) Do: Measure an export on a Steam Deck or comparable slow storage with representative pending writes, alongside the idle case. (@fixdoes its part first: Flush only the copied files and required directories instead of all pending system writes.)@fixcan do L1, L2, L3 and L4.Checks: Still running: 10 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven as a complete durability fix. The added test checks that os.sync is called before the swap; it does not check durable directory entries or the Windows fallback. Nine interleaved exports on Debian 13 measured medians of 46 ms before and 54 ms after.
Other systems: The Linux path calls system-wide sync, including writes unrelated to saves. Windows uses per-file fsync, but its failures are ignored. The final rename durability issue affects filesystems where directory updates are not durable when the rename returns. No game rendering, audio or input code changes.
Switches: None.
Reviewed:
e8cfa47699against1938a302fe: Read AGENTS.md, CONTRIBUTING.md, the pull request template, relevant standards, the diff and commits, the changed save-copy and test paths and their callers. Skimmed the rest of the two large changed files and save documentation. docs/review-checklist.md and the adjacent Tooling checkout were absent; recorded runs were read from the pull request and comment. No generated files or translations changed.; nothing run (a code review).Checked and fine:
Testing: No commands from the project or tests were run, as requested. The author reports a successful Debian manual export and a game-free test; Windows manual testing remains outstanding, and CI is still running.
Overlaps and merge order: Not established from the available offline checkout.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
@ -475,6 +475,7 @@ def copy_saves(src, dst, backup, keep_settings, dry_run):shutil.copy2(os.path.join(src, f), os.path.join(incoming, f), follow_symlinks=False)if not had:os.makedirs(dst)on_disk(incoming, *([backup] if had else []))L1 (blocking): The flush precedes every rename, but nothing makes the resulting directory entries durable before reporting Done.
When: After sync returns, swap_in moves the old slots aside and places the incoming slots, then cleanup removes the aside folder. A power cut immediately after Done can recover directory metadata from before or during those operations, leaving the target missing slots or containing an incomplete mixture even though the file contents were flushed.
Do: Make the swap and the relevant parent directory entries durable before deleting the old entries and reporting success, using the appropriate platform-specific durability operations and error handling.
@ -491,0 +494,4 @@find copies the disk never got (ext4 writes renames within seconds, data much later), the old save gone. POSIX:os.sync, every file at once; Windows: each file's fsync (a read-only one is left to the system)"""if hasattr(os, "sync"):os.sync()L4 (should fix): The timing does not cover the system-wide flush when other applications have substantial dirty data or the saves are on slow storage.
When: An export while a large unrelated write is pending waits for os.sync to flush all mounted filesystems, so Done can be delayed by that unrelated work.
Do: Measure an export on a Steam Deck or comparable slow storage with representative pending writes, alongside the idle case.
@ -491,0 +502,4 @@try:with open(os.path.join(folder, name), "rb+") as f:os.fsync(f.fileno())except OSError:L2 (blocking): The Windows fallback ignores every open or fsync failure and proceeds with the swap.
When: A copied read-only save retains its read-only attribute through copy2, so opening it with rb+ can fail on Windows. Likewise, an actual fsync I/O error is swallowed: the tool removes the old target and prints Done although the incoming file or backup was never confirmed on disk.
Do: Flush read-only copies with a suitable handle or safely adjust their attributes, and propagate traversal, open and flush failures so the swap is not started when durability cannot be established.
@ -413,0 +414,4 @@# (renames reach the disk within seconds, a copy's data much later on ext4: a power cut in between left the# target's slots and its backup empty, and the old save gone)order, real_swap = [], oot.swap_inwith mock.patch.object(oot.os, "sync", create=True, side_effect=lambda: order.append("sync")), \L3 (should fix): The new test creates os.sync on every platform, so it never exercises the Windows per-file flush path.
When: On Windows the mock makes hasattr(os, "sync") true, bypassing all file opens and fsync calls. Removing the fallback or swallowing all its errors would still pass this test.
Do: Add a test that forces the no-sync path and checks that incoming and backup files are flushed before the swap, including a flush failure and a read-only copied file.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.