Skip to content

fix(savedata): recover from metadata setup failure - #1680

Merged
oneandonlydean merged 3 commits into
boykopovar:mainfrom
emirplus:fix/savedata-memory-metadata
Oct 12, 2026
Merged

oneandonlydean merged 3 commits into
boykopovar:mainfrom
emirplus:fix/savedata-memory-metadata

Conversation

@emirplus

@emirplus emirplus commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What

Fixes #1667.

sceSaveDataSetupSaveDataMemory2 ignored the result of write_file_replace for the initial SaveDataParam. After a failed param write it returned success, and a retry with the same size skipped initialization because the blob already existed.

Now the param is written before the blob, setup re-runs when the param is missing (needParam && !haveParam), and a failed param or blob write returns SAVE_DATA_ERROR_INTERNAL (0x809F000B) without touching the result struct, as setSaveDataMemory2 does for the same failure. A host exception is not used: it does not cross the PRX frame on Linux (see the thread).

Tested

  • Linux, Release, PR merged onto current main: savedata_memory_metadata, savedata_memory_growth, savedata_memory_growth_read_failure, savedata_core_write_replacement, savedata_native_write_replacement, savedata_replace_file_failure pass.
  • New cases in SaveDataMemoryMetadata.cpp: fresh slot with param failure and retry, growth with param failure and retry, blob failure after param, no init_param/option 0, per-slot and per-user isolation, orphan blob without param.
  • Windows (MinGW-w64 GCC 15.2, Release) run by @popcoder565 on a8c2100f: savedata_memory_metadata passes.
  • No title run.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes

Report SAVE_DATA_ERROR_INTERNAL when setupSaveDataMemory2 fails to persist initial SaveDataParam metadata, and restore previous state so retrying setup can initialize cleanly. Closes boykopovar#1667.
@github-actions github-actions Bot added the prx label Oct 8, 2026
@Sanjaysrinivas

Copy link
Copy Markdown
Contributor

Reviewed c4c3ed7711332b61a1cd05d924b2b1ffa1442487 against #1667. The ordinary metadata failure, successful rollback/retry, error code, unchanged failure result, and mutex behavior are handled appropriately. Two gaps remain before this closes the issue:

  1. P1: rollback failures still allow false success on the same-size retry. At Export.cpp:644-650, both the fresh-blob removal error and the existing-blob restoration result are ignored. If rollback fails, the blob remains at the requested size. The next identical setup call skips initialization and returns success with missing or stale metadata. This violates [Data integrity] Fix save-memory metadata failures and setup recovery #1667's requirements to ensure correct same-size retries and define the state after every intermediate failure. Recovery needs to remain correct when rollback fails; checking the rollback result alone does not make a later retry safe.

    I reproduced both paths against this commit's unmodified production Export.cpp in Linux Release (Ubuntu 24.04/WSL2, GCC 13.3, -O3 -DNDEBUG). An isolated test executable interposed libc filesystem calls: metadata failure came from the documented .param.tmp directory obstruction; fresh rollback injected EACCES into blob removal, and growth rollback injected EIO into the second blob replacement's rename. After removing the injected failure:

    fresh: first=0x809f000b, remaining_blob=128
    fresh: same_size_retry=0x00000000, metadata_exists=false
    growth: first=0x809f000b, remaining_blob=256
    growth: same_size_retry=0x00000000, persisted_user_param=100, requested_user_param=200
    

    These are synthetic filesystem tests, not observed title-save failures.

  2. P2: the required regression matrix is incomplete. The new growth-failure test starts with an all-zero blob, so it does not establish preservation of meaningful existing bytes on this path. Please seed nonzero data and cover rollback failure, blob-write failure before metadata with the old pair/result unchanged, and fresh-process readback after a successful retry. Existing successful-growth coverage already checks prefix preservation and zero filling; it does not cover these setup failure states. Document the failed-rollback recovery policy alongside the tests.

I compiled and ran SaveDataMemoryMetadata, SaveDataMemoryGrowth, native SaveDataWriteReplacement, and SaveDataFileWriteFailure from this head in Linux Release; all four passed. No actionable standards findings in the changed hunks. Review and reproduction were AI-assisted.

…ck recovery

Write initial SaveDataParam metadata before replacing the memory blob so metadata failure cannot leave a prematurely grown blob. Handle blob write failure with metadata rollback, and allow retries to recover slots with missing metadata. Expand tests with nonzero data, blob failure, and fresh readback.
@emirplus

emirplus commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Sanjaysrinivas for the detailed review and the concrete failure reproductions.

Pushed �8c2100f addressing both P1 and P2:

  1. P1 (Metadata-first ordering & retry safety):
    • setupSaveDataMemory2 now persists paramPath (.param) before replacing the memory blob path (.bin). If metadata persistence fails, the blob is never touched or prematurely grown, eliminating inconsistent blob sizing without relying on fallible blob rollback renames.
    • If blob write subsequently fails, metadata is rolled back (restoring pre-existing param or removing it if fresh).
    • Setup condition updated to if (!have || existed < setup_param->memory_size || (needParam && !haveParam)) so any slot with missing metadata cannot skip initialization on a same-size retry.
  2. P2 (Expanded regression coverage):
    • Seeded nonzero bytes in the existing blob to verify exact byte preservation during growth failures and prefix preservation upon successful retry.
    • Added deterministic blob write failure injection via .bin.tmp directory collision, verifying that old blob, old metadata, and failure results remain completely unchanged.
    • Added missing metadata recovery test where only the blob is present on disk.
    • Added fresh-process termination, direct filesystem readback, and re-initialization verification.

All 6 savedata suites pass 100% locally under ctest.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

Please drop the .param rollback in setupSaveDataMemory2 (libSceSaveData.native/Export.cpp, the remove/rewrite after the blob write fails) and throw a std::runtime_error when write_file_replace fails for the param. A host write failure has no console code; it should stay explicit rather than be undone. Writing the param first and re-running setup when it's missing is good.

@popcoder565

Copy link
Copy Markdown
Contributor

Native Windows run, since no Windows results were posted. Setup: Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release. Head a8c2100f, merged onto main d70b899 in one build with 38 other PRs that had no Windows run.

No title was run.

🤖 Addressed by Claude Code

@adriadam10 adriadam10 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the rework. Dean's request from 2026-10-09 is still pending on the current head (a8c2100):

  • core/libs/prx/libSceSaveData.native/Export.cpp:653-660: drop the .param rollback (the remove/rewrite of paramPath after the blob write fails).
  • Export.cpp:647-649 (and the blob write failure at 652-662): a failed write_file_replace is a host write failure with no console code, so throw std::runtime_error instead of returning 0x809F000B. Keep writing the param first and re-running setup when it is missing, that part is fine.
  • core/libs/tests/SaveDataMemoryMetadata.cpp:134-190: these cases pin the rollback and the error code; rewrite them for the new behaviour (exception on param write failure, retry with the same size re-initialises because the param is missing).

Please also drop the now unused originalParam read (Export.cpp:636-639) once the rollback is gone.

@Sanjaysrinivas

Copy link
Copy Markdown
Contributor

Posting the relevant part of my reproduction of #1667 here, because this PR is the one carrying the review that asks for it.

adriadam10's review asks that a failed write_file_replace throw std::runtime_error instead of returning 0x809F000B. I implemented exactly that on Linux and it corrupts the heap of the calling process. Deterministic, every run:

retry rc=0
DUMP after-retry-bin:   _sd_mem/u42/slot0.bin   size=128
DUMP after-retry-param: _sd_mem/u42/slot0.param size=1328
free(): double free detected in tcache 2      (exit 134)

The parameter-first ordering itself works: the retry really does persist a 128-byte zero-filled blob and the requested metadata, which is the behaviour #1667 asks for. The crash comes only from the exception leaving the library.

Controls I ran on the same build:

Case Result
sceSaveDataSetupSaveDataMemory2 with no failing write rc=0, exit 0, no corruption
metadata write failure, exception caught by the caller files written correctly, then double free
pre-change main never throws, so it never occurs

The likely cause is an allocator mismatch across the boundary. libSceSaveData.native.prx links libc.prx (readelf -d shows NEEDED libc.prx), while the test executable links libc.so.6. The exception object is therefore allocated through one allocator and released by the other's unwinder. The .prx has .eh_frame and .gcc_except_table and imports _Unwind_Resume/__cxa_throw, so the tables are present; it is the allocator pairing that differs.

Two things I would add for whatever lands here:

  1. [Data integrity] Fix save-memory metadata failures and setup recovery #1667 explicitly asks the opposite of the review: "Use the API's established error representation; do not substitute a host exception for an expected filesystem failure." Returning SAVE_DATA_ERROR_INTERNAL — the code the set path already returns for the same host failure — satisfies the review's intent (do not report success) without the crash.
  2. If throwing is genuinely wanted, it needs to be caught inside the .prx and converted to a code before crossing the boundary, or the boundary needs one allocator. I did not find a way to do it from the single call site.

I could not reproduce this on Windows; I only had Linux. #2677 says it was tested on Windows, and configure_windows_unwind is applied to the library but not to savedata_memory_metadata_tests, so the two platforms may differ. My own evidence is Linux-only and I am not claiming the review is wrong everywhere.

I opened #2840 for this, based on current main, with the parameter written first, no .param rollback, and the error returned as a code. If it is better folded into this PR or #2677, say so and I will do that instead.

@emirplus

Copy link
Copy Markdown
Contributor Author

Pushed commit 6a7cce4 addressing the review feedback and test matrix requirements:

  1. Error Code Contract vs Host Exception:

    • Returns SAVE_DATA_ERROR_INTERNAL (0x809F000B) on write_file_replace failure rather than throwing std::runtime_error.
    • Adheres to [Data integrity] Fix save-memory metadata failures and setup recovery #1667's specification ("Use the API's established error representation; do not substitute a host exception for an expected filesystem failure") and mirrors the existing convention in setSaveDataMemory2.
    • Throwing std::runtime_error across the PRX/host boundary was reported to trigger a Linux double-free crash (exit 134). The exact allocator interaction has not been conclusively established, so this implementation uses the established error-code contract instead.
  2. Dropped Rollback and Unused Reads:

    • Removed .param rollback (removal/rewrite of paramPath upon blob write failure) in setupSaveDataMemory2.
    • Removed the preceding originalParam read (read_file_all(paramPath, originalParam)).
  3. Ordering and Result Integrity:

    • Parameters are written prior to blob replacement.
    • On write failure (either .param or .bin), the call immediately exits with SAVE_DATA_ERROR_INTERNAL without modifying result->existed_memory_size.
    • If blob writing fails, fresh slots retain no blob (have == false) and growing slots retain their pre-existing blob (existed < memory_size), allowing a same-size retry to re-run setup, provided the underlying write failure has been resolved.
  4. Expanded Regression Coverage:

    • SaveDataMemoryMetadata.cpp: Verified fresh-slot retry after metadata failure, seeded non-zero blob preservation on growth failure, fresh blob write failure recovery, retry with same size, slot/user isolation, null/zero-option parameter handling, and on-disk readback across library terminate/re-initialize cycles.
    • SaveDataMemoryGrowth.cpp: Updated to assert .param presence since metadata write precedes the blob write.
  5. Verification:

    • CTest Release: 6/6 test targets pass (savedata_memory_metadata, savedata_memory_growth, savedata_memory_growth_read_failure, savedata_core_write_replacement, savedata_native_write_replacement, savedata_replace_file_failure) in 1.48s.
    • Conventions: tools/check_conventions.py passed with 0 violations.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

Please throw std::runtime_error when write_file_replace fails in setupSaveDataMemory2 (Export.cpp, the param write and the blob write), as asked above; a host write failure has no console code. The double free comes from the test using the host libc: add libc to target_link_libraries(savedata_memory_metadata_tests ...) in core/libs/CMakeLists.txt, as guest_ssl_tests does since #2830, and the exception crosses cleanly. Conventions also fails because the PR body is missing the template's What, Tested and Checklist sections.

@adriadam10

Copy link
Copy Markdown
Collaborator

@oneandonlydean we implemented your request on top of current main (throw std::runtime_error on both write_file_replace failures in setupSaveDataMemory2, libc added to savedata_memory_metadata_tests) and it does not work on Linux here:

  • savedata_memory_metadata aborts with SIGABRT in _Unwind_Resume. gdb shows __cxa_throw from setupSaveDataMemory2.cold and no catch is ever entered; catch (std::runtime_error&), catch (std::exception&) and catch (...) behave the same.
  • libc is linked (ldd lists libc.prx), so it is not the missing link you described. A difference with guest_ssl: that one throws from functions with no cleanups, while setupSaveDataMemory2 holds a lock_guard, a std::string and a std::vector in the PRX frame, so the unwinder has landing pads to resume through.
  • This matches @Sanjaysrinivas's double-free reproduction.

Could you confirm how it crosses cleanly on your setup (branch/commit), or should this keep returning 0x809F000B as setSaveDataMemory2 does? @emirplus, the PR body also still needs the template's What, Tested and Checklist sections (Conventions fails).

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@adriadam10 you're right, I took the guest_ssl case as general and it isn't: with cleanups in the PRX frame the throw doesn't cross. Keep returning 0x809F000B, as the head already does and as setSaveDataMemory2 does for the same failure.

@emirplus that leaves the template's What, Tested and Checklist sections in the PR body (Conventions fails without them).

@adriadam10

Copy link
Copy Markdown
Collaborator

Ready to merge from my side, but the PR description fails the conventions check:

  • [pr-template] Fill in the pull request template: unchecked: AI-assisted:
  • [pr-template] Fill in the pull request template: answer AI-assisted with yes or no

Please fill those template lines in (only you can answer AI-assisted); it merges once they pass.

@emirplus

Copy link
Copy Markdown
Contributor Author

@adriadam10 The PR description checklist has been updated with - [x] AI-assisted: yes. Ready for merge.

@oneandonlydean
oneandonlydean dismissed adriadam10’s stale review October 12, 2026 02:44

The throw this review asks for was withdrawn on 10-11; the PR was marked ready by the reviewer on 10-11 09:23Z and its full build is green on the current head.

@oneandonlydean
oneandonlydean merged commit 4dfa850 into boykopovar:main Oct 12, 2026
14 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data integrity] Fix save-memory metadata failures and setup recovery

5 participants