Skip to content

Tools: preserve existing saves when an offline import fails - #4872

Open
gabrielsteglich wants to merge 4 commits into
ItsNotRexed:mainfrom
gabrielsteglich:fix/offline-save-import-rollback
Open

gabrielsteglich wants to merge 4 commits into
ItsNotRexed:mainfrom
gabrielsteglich:fix/offline-save-import-rollback

Conversation

@gabrielsteglich

@gabrielsteglich gabrielsteglich commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue #4816.

What and why

tools/saves.py import published blobs one at a time and wrote the manifest in place. A later failure could leave an overwritten save paired with the old manifest. The hash also came from an earlier read of the source.

Stage each blob and the manifest before publication and hash the staged bytes. Replace the manifest last, restore earlier destinations if a replacement fails, and retain a recovery backup if restoration fails. Rollback assumes one writer in the destination save directory. The merge from main preserves its invalid-container-name warning.

Addressed the I/O review by reading only the metadata headers needed for ASAV and SLAYER1 and using the open file's size for the dry-run summary. The real import reads the full content in 1 MiB chunks and checks the manifest size and hash against the bytes written. As a dry run, it checks file access and the relevant headers; full body reads happen during import.

Tested

Head b33a09db on base d974c88a. Windows 11 Pro 26300, Python 3.13.7.

  • 46/46 passed across import and format/pack-index tests, including 18/18 import tests. Covers staged writes, first/later/manifest replacement failures, an interruption after replacement, recovery backups, source changes before staging, and bounded header reads. Docs links passed 6/6 and line endings passed 3/3.
  • With 16 MiB synthetic payloads, peak Python allocations tracked by tracemalloc fell from 16.0 MiB (plain ASAV) or 32.0 MiB (with a SLAYER1 companion) to about 2.0 MiB during import and about 15 KiB during dry-run, compared with 4e8bd8f0. Manifest sizes and SHA-256 hashes matched the source and output bytes.
  • The full saves suite ran 71 tests. Its two absolute-symlink subcase failures in pack and its one skip also occur on main d974c88a on this Windows host.

AI-assisted (Codex). Synthetic saves only.

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

The staging loop copies each blob in 1 MiB chunks, but import still reads the entire input in save_slot to get its header. The dry run also calls len(read(src)) to print the size.

I imported a single synthetic ASAV with a 16 MiB payload at 451fc265 on Windows 11 with CPython 3.14.7. The real import peaked at 16,912,584 traced bytes, down from 33,823,533 on merge base de671352. The dry run peaked at 16,914,153 bytes.

For this plain ASAV path, I changed the payload read in save_slot to read(os.path.join(folder, payload), ASAV_HDR) and used os.path.getsize(src) for the dry-run size. With those two local changes, the same import peaked at 2,367,806 bytes. The dry run peaked at 135,687 bytes. The output manifest hash still matched the input. This check uses no packed companion.

The PR save suite ran 67 tests with three skips and zero failures. The PR import tests on the merge base reported 11 failed assertions. To reproduce the allocation measurements on the published head, run this script from the checkout root with py -3.14 -I -B probe.py.

import gc, sys, tempfile, tracemalloc, hashlib, json
from pathlib import Path
sys.path.insert(0,str(Path("tests").resolve()))
from test_saves import make_asav, saves, quiet
for mib in (1,4,16):
    with tempfile.TemporaryDirectory() as d:
        src=Path(d)/"input"
        src.mkdir()
        p=src/"Player"
        p.write_bytes(make_asav(slot="Player",payload=bytes(mib<<20)))
        for dry in (True,False):
            out=Path(d)/"out"
            args=[str(src),"--out",str(out)]+(["--dry-run"] if dry else [])
            gc.collect()
            tracemalloc.start()
            quiet(saves.import_saves,args)
            peak=tracemalloc.get_traced_memory()[1]
            tracemalloc.stop()
            if dry:
                assert not out.exists()
            else:
                e=json.loads((out/"import-manifest.json").read_bytes())["entries"][0]
                assert e["sha256"]==hashlib.sha256(p.read_bytes()).hexdigest()
            print(mib,dry,peak)

AI-assisted.

Keep the XGameSave container-name warning in the shared import report while preserving staged publication and rollback.

@kacper-serewis kacper-serewis left a comment

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.

Windows Python 3.13 CPU review at 451fc26: all 15 import tests passed. With two synthetic saves, injecting an OSError before each of three os.replace calls restored the previous tree, blob and manifest hashes and left no staging files. Retry published both updated blobs with matching source and manifest hashes. This covers handled publication errors, not power loss. AI-assisted.

Read the fixed ASAV header and seek to a packed companion header after validating the wrapper extent. Report dry-run sizes from open file metadata. Keep full-file size checks for ASAV offsets and the existing streaming publication and rollback.
@DenRakEiw

Copy link
Copy Markdown
Contributor

Tested on Windows 11 / Python 3.12.10 at head SHA b33a09db569b7c968204d8214c18761b7214eaeb.

  • Trial-merge: Clean onto origin/main (d974c88a); git diff --cached --check passed with no issues.
  • Tests:
    • python -I tests/test_saves.py — Ran 70 tests in 2.695s (FAILED (failures=2, skipped=1)): test_replacement_preserves_existing_permission_bits skipped (POSIX permission bits), and the 2 failures are the relative=False (dangling=False/True) subtests of the pre-existing AtomicPackTest.test_destination_symlinks_update_the_target_and_remain_links (os.readlink returning a \\?\ prefix on Windows).
    • python -I tests/test_saves.py ImportTest — Ran 18 tests in 0.304s (OK), including all 9 new offline-import tests.
    • python -I tests/test_docs_links.py — Ran 6 tests in 0.110s (OK).
  • Code read: _publish_save_import streams and hashes all staged payloads plus import-manifest.json into sibling .saves-import-* temp directories, backs up existing destinations before replacing, and rolls back earlier replacements (or surfaces any remaining backup path) on failure while keeping save_slot header-only for --dry-run.

AI-assisted review (Gemini 4 Neon).

@kapitche

Copy link
Copy Markdown
Contributor

Tested b33a09d merged with main 3faac55 on Linux (WSL) Python 3.12.16 and native Windows Python 3.13.1: pass on Linux, concern on Windows (pre-existing)

Linux: tests/test_saves.py 70 tests OK (1 skipped); all tests/test_docs_*.py pass.
Negative control: tools/saves.py checked out from main with the PR's tests/test_saves.py: 12 failures (discovery reads at most 8 bytes, dry run reads only headers, flush before replace, prepare before publish, new output tree removed after failed manifest, backup path reported if restore fails, interrupted-after-replace x3, rollback of each failed publication x3), so the tests demonstrate the fix. Restored, all pass.
Windows: tests/test_saves.py 70 tests, 2 failures, both test_destination_symlinks_update_the_target_and_remain_links (AtomicPackTest, relative=False, dangling False/True). That test is not touched by this PR and fails the same way on main 3faac55 on this Windows machine (61 tests, the same 2 failures), so it is not caused by this change (absolute-path symlink case, tools.saves.pack). All import tests added here pass on Windows.
Read the diff (staging in a private sibling directory, manifest hashes the staged bytes, restore on failed os.replace, backup path reported); no verified issues.

@memorypressure

Copy link
Copy Markdown

Verified merge with main 3faac55 (clean, sitting on top of d974c88/de6713524): test_saves.py passes 70/70 under python -I (1 skipped, re-run), including nine new import-rollback and header-probe tests; the docs guards pass too. The only text write pins newline with utf-8, and the probe path now reads header bytes instead of whole payloads — backward compatible. If a restore fails, the backup location is reported, matching the docs. CI was pending. AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only run).

@Atomic258

Copy link
Copy Markdown
Contributor

Tested b33a09d on Windows Server 2022, CPython 3.13.12: pass

  • python -I tests/test_saves.py -> FAILED (failures=2) - the 2 are the known test_destination_symlinks_update_the_target_and_remain_links Windows symlink-spelling quirk, identical on upstream/main
  • Negative control (tools/saves.py swapped to upstream/main): FAILED (failures=14) - differentiates
  • Verdict: pass aside from pre-existing platform failures.

git diff --check clean; python -m compileall -q exit 0. No game files, no GPU. AI-assisted (Devin).

@JRamos1993

Copy link
Copy Markdown
Contributor

Tested abf53633 merged onto main 8575d36e on Windows 11, CPython 3.14.3, CPU only: pass.

  • python -I tests/test_saves.py: 79 tests OK (skipped=3).
  • Negative control (tools/saves.py from main, the PR's tests kept): tests/test_saves.py 79 tests FAILED (failures=12, skipped=3).
  • py_compile on the 2 changed Python files: OK; git diff --check: clean.

No game files. AI-assisted (Claude Code).

@kapitche

Copy link
Copy Markdown
Contributor

Tested abf5363 merged with main 8575d36 on Linux (WSL2) Python 3.12.16 (-I): pass
Clean merge. tests/test_saves.py: 79 tests OK, 1 skipped (Windows-only junction test).
Negative control: tools/saves.py reverted to main gives 12 failures across the new import tests (prepare-before-publish, rollback on failed publication, restore after interrupted replace, header-only dry run, 8-byte discovery reads), so they discriminate.
No overlapping open PR found by title search (#5240 touches saves JSON nesting limit, a different area).

@KotikVanil KotikVanil 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.

Tested abf53633 on Windows x64 with a synthetic save tree. I hard-linked a current destination to a second file, then injected an os.replace failure when publishing the manifest after the blobs had been replaced. Rollback restored the same bytes to both names but left them pointing to different files (os.path.samefile became false). The backup is a copy, so publishing it cannot restore that link relationship.

Candidate guard and regression apply the existing saves.py pack policy: refuse already hard-linked destinations before any replacement, even with --force. This preserves the alias and the original contents. With that candidate, all 20 ImportTest tests pass. This edge case matters only where the destination is hard-linked.

AI-assisted (Codex). CPU only, no actual save data.

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.

9 participants