From 26d9e540597904f7043022c00eda2a4fbaa4ffc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 19 Oct 2026 20:18:47 +0200 Subject: [PATCH] SaveState: Don't fold a save into one from before a load A save to a path with a save still being written counted as a repeated key press, even with a load applied in between, so save, load, save didn't save the loaded state. Now a repeat only joins the earlier save if no load has been applied or queued since its snapshot. Co-Authored-By: Claude Opus 5.5 (1M context) --- Core/SaveState.cpp | 89 ++++++++++++++++++++++++++++------------ docs/async-savestates.md | 17 ++++---- 2 files changed, 72 insertions(+), 34 deletions(-) diff --git a/Core/SaveState.cpp b/Core/SaveState.cpp index e1e5db5272..130e1e9912 100644 --- a/Core/SaveState.cpp +++ b/Core/SaveState.cpp @@ -127,6 +127,15 @@ struct PendingRead { std::string savedBy; }; +// A save from when it's asked for until its file is written. +struct SaveRecord { + Path path; + // How many loads had been applied when its snapshot was taken, or -1 before that. + int loadCount = -1; + // Callbacks of repeats of it (a save key pressed twice). They hear its result, with no message. + std::vector repeats; +}; + struct Operation { // The slot number is for visual purposes only. Set to -1 for operations where we don't display a message for example. Operation(OperationType t, const Path &f, int slot_, Callback cb) @@ -143,15 +152,18 @@ struct Operation { // worker part is done. bool started = false; std::shared_ptr read; + // For a save. Its fields are under mutex. + std::shared_ptr save; }; // Front to back, each operation's emu thread part runs in turn. A load or rewind that's still // waiting for the worker holds up the operations behind it. static std::deque g_pendingOperations; -// Saves asked for and not yet written, by path, with the callbacks of any repeats of them (a save -// key pressed again before the first save finished). Under mutex. -static std::map> g_pendingSaves; +// Saves asked for and not yet written, oldest first. Under mutex. +static std::vector> g_pendingSaves; +// Loads (and rewinds) applied, so a save can tell whether one came after its snapshot. +static std::atomic g_loadCount; // Save snapshots in memory, waiting to be compressed and written. Each is a whole state. static std::atomic g_saveSnapshots; constexpr int MAX_SAVE_SNAPSHOTS = 2; @@ -233,6 +245,7 @@ int g_screenshotFailures; // the JIT keeps its blocks, so they don't all have to be compiled again. Memory::RamCompare codeCompare; if (p.mode == p.MODE_READ) { + g_loadCount++; hookedOps = Replacement_GetHookedOps(); RestoreReplacedInstructions(0, 0xFFFFFFFF); codeCompare.ranges = __KernelModuleCodeRanges(); @@ -348,39 +361,52 @@ int g_screenshotFailures; static bool IsSavePending(const Path &path) { std::lock_guard guard(mutex); - return g_pendingSaves.find(path.ToString()) != g_pendingSaves.end(); + for (const auto &save : g_pendingSaves) { + if (save->path == path) { + return true; + } + } + return false; } - // If a save to path is already pending, this is a repeat of it (a key pressed twice): the callback - // hears that save's result, with no message so it's only shown once. Returns true if so. + // If a save to path hasn't finished yet, this is a repeat of it (a key pressed twice): the + // callback hears that save's result, with no message so it's only shown once. Returns true if so. + // Unless a load was applied after that save's snapshot: then this saves something else. static bool AttachToPendingSave(const Path &path, const Callback &callback) { std::lock_guard guard(mutex); - auto iter = g_pendingSaves.find(path.ToString()); - if (iter == g_pendingSaves.end()) { - return false; + // One queued and not yet applied comes before this save too. + for (const Operation &op : g_pendingOperations) { + if (op.type == OperationType::Load || op.type == OperationType::Rewind) { + return false; + } } - if (callback) { - iter->second.push_back(callback); + for (auto iter = g_pendingSaves.rbegin(); iter != g_pendingSaves.rend(); ++iter) { + SaveRecord &save = **iter; + if (!(save.path == path)) { + continue; + } + if (save.loadCount != -1 && save.loadCount != g_loadCount) { + return false; + } + if (callback) { + save.repeats.push_back(callback); + } + return true; } - return true; + return false; } - // Takes a save out of g_pendingSaves, returning the callbacks of its repeats. - static std::vector TakePendingSave(const Path &path) { + // A save is done (written, failed or refused). Returns the callbacks of its repeats. + static std::vector FinishPendingSave(const std::shared_ptr &save) { std::lock_guard guard(mutex); - std::vector repeats; - auto iter = g_pendingSaves.find(path.ToString()); - if (iter != g_pendingSaves.end()) { - repeats = std::move(iter->second); - g_pendingSaves.erase(iter); - } - return repeats; + g_pendingSaves.erase(std::remove(g_pendingSaves.begin(), g_pendingSaves.end(), save), g_pendingSaves.end()); + return std::move(save->repeats); } static void RefuseOperation(const Operation &op) { CallbackRefused(op.callback); - if (op.type == OperationType::Save) { - for (const Callback &repeat : TakePendingSave(op.path)) { + if (op.type == OperationType::Save && op.save) { + for (const Callback &repeat : FinishPendingSave(op.save)) { CallbackRefused(repeat); } } @@ -402,10 +428,13 @@ int g_screenshotFailures; } std::lock_guard guard(mutex); - if (op.type == OperationType::Save) { - g_pendingSaves.emplace(op.path.ToString(), std::vector()); - } g_pendingOperations.push_back(op); + if (op.type == OperationType::Save) { + Operation &queued = g_pendingOperations.back(); + queued.save = std::make_shared(); + queued.save->path = op.path; + g_pendingSaves.push_back(queued.save); + } // Don't actually run it until next frame. needsProcess = true; @@ -1076,6 +1105,7 @@ int g_screenshotFailures; bool keepUndo = false; Path undoPath; Callback callback; + std::shared_ptr save; }; // Emu thread, once the file is written (or failed to be). @@ -1103,7 +1133,7 @@ int g_screenshotFailures; status = Status::FAILURE; } - std::vector repeats = TakePendingSave(job.path); + std::vector repeats = FinishPendingSave(job.save); if (!callCallbacks) { return; } @@ -1128,6 +1158,7 @@ int g_screenshotFailures; job.slotGamePrefix = op.slotGamePrefix; job.slot = op.slot; job.callback = op.callback; + job.save = op.save; if (!op.slotGamePrefix.empty()) { job.keepUndo = g_Config.bEnableStateUndo; job.undoPath = GenerateSaveSlotPath(op.slotGamePrefix, op.slot, UNDO_STATE_EXTENSION); @@ -1426,6 +1457,10 @@ int g_screenshotFailures; // Enqueue() only appends, which leaves this reference alone. Unlocked, since callbacks can // queue more. Operation &op = g_pendingOperations.front(); + if (op.save) { + // Its snapshot is next: nothing can be loaded in between, it's first in the queue. + op.save->loadCount = g_loadCount; + } lock.unlock(); const bool finished = RunOperation(op); lock.lock(); diff --git a/docs/async-savestates.md b/docs/async-savestates.md index a4f616ba2f..70b742a14a 100644 --- a/docs/async-savestates.md +++ b/docs/async-savestates.md @@ -50,9 +50,11 @@ doesn't (worker). The thumbnail screenshot is already asynchronous and doesn't change. -**A save to a path that already has a save queued or in flight is a duplicate keypress.** It isn't -queued again. Its callback is attached to the save in flight and called with that save's status and -an empty message (so it shows nothing, and the in-flight save's own callback shows the result once). +**A save to a path that already has a save queued, and not yet snapshotted, is a duplicate +keypress.** It isn't queued again. Its callback is attached to the queued save and called with that +save's status and an empty message (so it shows nothing, and the queued save's own callback shows +the result once). Once the snapshot is taken, another save to the path is a new save: the game may +have moved on, or a load been applied, since. A save to a different path is queued, and takes its snapshot right away like any other. **At most two save snapshots exist at once**: a third save, while two are still being written, waits for the @@ -84,8 +86,7 @@ Operations still take effect in the order they were asked for: and snapshots the loaded state, as it does today when both run in the same `Process()`. A load waiting for its file holds up only the emu phases queued behind it. - **Worker jobs run in queue order**, so a save to a slot followed by a load of it writes before it - reads. As a shortcut, a load whose path has a write pending takes that save's uncompressed - snapshot directly and skips the file round trip. + reads. - **UI-thread file operations on slots wait for the worker** (`WaitForWorker()`, for all jobs, since it's rare and short): `UndoSaveSlot` and `DeleteSlot`. `UndoLoad` is a load, so it's queued behind the load undo write like anything else. `LoadSlot`'s existence check counts a slot with a save @@ -100,9 +101,11 @@ need the emu thread, so it can't deadlock. they are. So does the freeze-frame feature (`SaveToRam`/`LoadFromRam` every frame). - **Verify** stays synchronous. - **Shutdown and game switch** (`SaveState::Shutdown()`, from the kernel's shutdown, which app exit - goes through too): wait for the worker, so a save that was asked for is never lost. Then run the + goes through too): wait for the worker, so a save whose snapshot was taken is written. Then run the completions' bookkeeping (the undo slot in the config) without their callbacks, which can refer to - an EmuScreen that's going away, and drop whatever is still queued, as before. + an EmuScreen that's going away, and drop whatever is still queued, as before. A save still queued + at that point (asked for in the pause menu, which doesn't run `Process()`, then quitting) is lost + like it always was: by then most of the kernel has shut down, too late to take a snapshot. - Loads at boot (auto-load, `--state`, opening a `.ppst`) and the debugger's `game.state.*` with `wait` already work through callbacks, and need no special handling. The game already ran at least a frame before a boot-time load applied.