From aab49aefc8c43ad524f5e18caf6aee3636d870bd Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sun, 19 Jul 2026 22:05:39 -0400 Subject: [PATCH 1/3] Fix slot-less save upload DB/file desync (#3833) A slot-less POST /api/saves behaves as a filename upsert, and two details combined into silent save corruption. 1. get_save_by_filename only filtered by slot when one was passed, so a slot-less lookup could match (and overwrite) a save row living in a named slot. Scope slot=None to the null-slot save (Save.slot IS NULL) so a slot-less upload can never adopt a row from another slot. get_save_by_content_hash keeps its documented cross-slot slot=None behavior (dedup-only, non-destructive). 2. The upsert branch only wrote file_size_bytes and content_hash while the bytes landed under a path derived from the request's emulator, so the row's hash could disagree with the file it still pointed at. Also persist file_path/emulator, and remove the now-orphaned file when the row's location changes. Co-Authored-By: Claude Opus 4.8 (1M context) --- backend/endpoints/saves.py | 15 +++ backend/handler/database/saves_handler.py | 5 + backend/tests/endpoints/test_saves.py | 121 ++++++++++++++++-- .../handler/database/test_saves_handler.py | 75 ++++++++++- 4 files changed, 201 insertions(+), 15 deletions(-) diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index 7b287abaa..ed963e905 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -267,13 +267,28 @@ async def add_save( ) if db_save: + # Track where the bytes actually landed: the file is written under a + # path derived from this request's emulator, which may differ from the + # existing row's location. Persisting file_path/emulator keeps the row's + # hash and its on-disk content from drifting apart. + stale_full_path = db_save.full_path update_data: dict = { "file_size_bytes": scanned_save.file_size_bytes, "content_hash": scanned_save.content_hash, + "file_path": scanned_save.file_path, + "emulator": emulator, } if slot is not None: update_data["slot"] = slot db_save = db_save_handler.update_save(db_save.id, update_data) + + # The row moved to a new path, so the previously stored bytes are now + # orphaned. Remove them to avoid leaving stale save files on disk. + if stale_full_path != db_save.full_path: + try: + await fs_asset_handler.remove_file(stale_full_path) + except FileNotFoundError: + pass else: scanned_save.rom_id = rom.id scanned_save.user_id = request.user.id diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index 9242c7e9e..779daa4ed 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -41,8 +41,13 @@ class DBSavesHandler(DBBaseHandler): query = select(Save).filter_by( rom_id=rom_id, user_id=user_id, file_name=file_name ) + # `slot=None` scopes to the null-slot save, not "any slot", so a + # slot-less upload can never match (and overwrite) a save living in a + # named slot. if slot is not None: query = query.filter(Save.slot == slot) + else: + query = query.filter(Save.slot.is_(None)) return session.scalars(query.limit(1)).first() @begin_session diff --git a/backend/tests/endpoints/test_saves.py b/backend/tests/endpoints/test_saves.py index 7546b2f29..e36f42e76 100644 --- a/backend/tests/endpoints/test_saves.py +++ b/backend/tests/endpoints/test_saves.py @@ -8,7 +8,11 @@ from fastapi import status from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS from handler.auth import oauth_handler from handler.auth.constants import Scope -from handler.database import db_device_handler, db_device_save_sync_handler +from handler.database import ( + db_device_handler, + db_device_save_sync_handler, + db_save_handler, +) from models.assets import Save from models.device import Device from models.platform import Platform @@ -381,6 +385,80 @@ class TestSaveUploadWithSync: assert data["device_syncs"] == [] assert data["origin_device_id"] is None + @mock.patch( + "endpoints.saves.fs_asset_handler.remove_file", new_callable=mock.AsyncMock + ) + @mock.patch( + "endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock + ) + @mock.patch("endpoints.saves.scan_save", new_callable=mock.AsyncMock) + def test_reupload_updates_file_path_and_emulator( + self, + mock_scan, + _mock_write, + mock_remove, + client, + access_token: str, + rom: Rom, + platform: Platform, + admin_user: User, + ): + """Re-uploading the same filename under a different emulator must move + the row's file_path/emulator to where the new bytes landed, so the + stored hash never disagrees with the served content.""" + existing = db_save_handler.add_save( + Save( + file_name="test.sav", + file_name_no_tags="test", + file_name_no_ext="test", + file_extension="sav", + file_path=f"{platform.slug}/saves/old_emu", + file_size_bytes=100, + content_hash="0" * 32, + emulator="old_emu", + rom_id=rom.id, + user_id=admin_user.id, + ) + ) + + new_path = f"{platform.slug}/saves/new_emu" + mock_scan.return_value = Save( + file_name="test.sav", + file_name_no_tags="test", + file_name_no_ext="test", + file_extension="sav", + file_path=new_path, + file_size_bytes=200, + content_hash="f" * 32, + rom_id=rom.id, + user_id=admin_user.id, + ) + + response = client.post( + f"/api/saves?rom_id={rom.id}&emulator=new_emu", + files={ + "saveFile": ( + "test.sav", + BytesIO(b"new save data"), + "application/octet-stream", + ) + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + + updated = db_save_handler.get_save(user_id=admin_user.id, id=existing.id) + assert updated is not None + assert updated.file_path == new_path + assert updated.emulator == "new_emu" + assert updated.content_hash == "f" * 32 + assert updated.file_size_bytes == 200 + # full_path now points at the freshly written bytes, not the stale ones. + assert updated.full_path == f"{new_path}/test.sav" + # The orphaned bytes at the old location are cleaned up. + mock_remove.assert_awaited_once_with(f"{platform.slug}/saves/old_emu/test.sav") + @mock.patch( "endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock ) @@ -812,32 +890,39 @@ class TestSaveConflictDetection: rom: Rom, platform: Platform, admin_user: User, - save: Save, + archival_save: Save, device: Device, device_b: Device, ): """Scenario 6: Device A uploads, Device B uploads without downloading first. Device B has an old sync from before Device A's upload, so conflict. + Slot-less uploads negotiate against the null-slot (archival) row. """ from datetime import datetime, timedelta, timezone old_sync_time = datetime.now(timezone.utc) - timedelta(hours=2) db_device_save_sync_handler.upsert_sync( - device_id=device_b.id, save_id=save.id, synced_at=old_sync_time + device_id=device_b.id, save_id=archival_save.id, synced_at=old_sync_time ) db_device_save_sync_handler.upsert_sync( - device_id=device.id, save_id=save.id, synced_at=save.updated_at + device_id=device.id, + save_id=archival_save.id, + synced_at=archival_save.updated_at, ) - mock_scan.return_value = save + mock_scan.return_value = archival_save file_content = BytesIO(b"stale save from device b") response = client.post( f"/api/saves?rom_id={rom.id}&device_id={device_b.id}", files={ - "saveFile": (save.file_name, file_content, "application/octet-stream") + "saveFile": ( + archival_save.file_name, + file_content, + "application/octet-stream", + ) }, headers={"Authorization": f"Bearer {access_token}"}, ) @@ -859,7 +944,7 @@ class TestSaveConflictDetection: rom: Rom, platform: Platform, admin_user: User, - save: Save, + archival_save: Save, device: Device, ): """Scenario 7: Web UI uploads (no device_id), device with old sync uploads. @@ -871,16 +956,20 @@ class TestSaveConflictDetection: old_sync_time = datetime.now(timezone.utc) - timedelta(hours=1) db_device_save_sync_handler.upsert_sync( - device_id=device.id, save_id=save.id, synced_at=old_sync_time + device_id=device.id, save_id=archival_save.id, synced_at=old_sync_time ) - mock_scan.return_value = save + mock_scan.return_value = archival_save file_content = BytesIO(b"stale save from device after web update") response = client.post( f"/api/saves?rom_id={rom.id}&device_id={device.id}", files={ - "saveFile": (save.file_name, file_content, "application/octet-stream") + "saveFile": ( + archival_save.file_name, + file_content, + "application/octet-stream", + ) }, headers={"Authorization": f"Bearer {access_token}"}, ) @@ -939,7 +1028,7 @@ class TestSaveConflictDetection: rom: Rom, platform: Platform, admin_user: User, - save: Save, + archival_save: Save, device: Device, ): """Verify conflict response contains all necessary details for client handling.""" @@ -947,16 +1036,20 @@ class TestSaveConflictDetection: old_sync_time = datetime.now(timezone.utc) - timedelta(hours=1) db_device_save_sync_handler.upsert_sync( - device_id=device.id, save_id=save.id, synced_at=old_sync_time + device_id=device.id, save_id=archival_save.id, synced_at=old_sync_time ) - mock_scan.return_value = save + mock_scan.return_value = archival_save file_content = BytesIO(b"conflicting save") response = client.post( f"/api/saves?rom_id={rom.id}&device_id={device.id}", files={ - "saveFile": (save.file_name, file_content, "application/octet-stream") + "saveFile": ( + archival_save.file_name, + file_content, + "application/octet-stream", + ) }, headers={"Authorization": f"Bearer {access_token}"}, ) diff --git a/backend/tests/handler/database/test_saves_handler.py b/backend/tests/handler/database/test_saves_handler.py index cce626cc6..cd1bc2a8f 100644 --- a/backend/tests/handler/database/test_saves_handler.py +++ b/backend/tests/handler/database/test_saves_handler.py @@ -107,13 +107,86 @@ class TestDBSavesHandlerPlatformFiltering: ): """Test that get_save_by_filename works correctly with platform filtering.""" retrieved_save = db_save_handler.get_save_by_filename( - user_id=admin_user.id, rom_id=rom.id, file_name=save.file_name + user_id=admin_user.id, + rom_id=rom.id, + file_name=save.file_name, + slot=save.slot, ) assert retrieved_save is not None assert retrieved_save.id == save.id assert retrieved_save.file_name == save.file_name + def test_get_save_by_filename_slotless_ignores_slotted_save( + self, admin_user: User, rom: Rom + ): + """A slot-less lookup must not match a same-named save in a named slot.""" + slotted = Save( + rom_id=rom.id, + user_id=admin_user.id, + file_name="shared.sav", + file_name_no_tags="shared", + file_name_no_ext="shared", + file_extension="sav", + emulator="test_emu", + file_path=f"{rom.platform_slug}/saves", + file_size_bytes=100, + slot="Slot A", + ) + slotted = db_save_handler.add_save(slotted) + + # No null-slot save exists, so a slot-less lookup should find nothing. + assert ( + db_save_handler.get_save_by_filename( + user_id=admin_user.id, rom_id=rom.id, file_name="shared.sav", slot=None + ) + is None + ) + + # The named-slot lookup still resolves the slotted save. + found = db_save_handler.get_save_by_filename( + user_id=admin_user.id, + rom_id=rom.id, + file_name="shared.sav", + slot="Slot A", + ) + assert found is not None + assert found.id == slotted.id + + def test_get_save_by_filename_slotted_ignores_slotless_save( + self, admin_user: User, rom: Rom + ): + """A named-slot lookup must not match a same-named null-slot save.""" + slotless = Save( + rom_id=rom.id, + user_id=admin_user.id, + file_name="shared.sav", + file_name_no_tags="shared", + file_name_no_ext="shared", + file_extension="sav", + emulator="test_emu", + file_path=f"{rom.platform_slug}/saves", + file_size_bytes=100, + slot=None, + ) + slotless = db_save_handler.add_save(slotless) + + assert ( + db_save_handler.get_save_by_filename( + user_id=admin_user.id, + rom_id=rom.id, + file_name="shared.sav", + slot="Slot A", + ) + is None + ) + + found = db_save_handler.get_save_by_filename( + user_id=admin_user.id, rom_id=rom.id, file_name="shared.sav", slot=None + ) + assert found is not None + assert found.id == slotless.id + def test_platform_filtering_with_different_emulators( self, admin_user: User, platform: Platform, rom: Rom ): From d6679066bad5d10231e72e1d615bdcea2dafef8d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sun, 19 Jul 2026 22:56:15 -0400 Subject: [PATCH 2/3] fixes --- backend/endpoints/saves.py | 49 +++++++++++++++++------ backend/handler/database/saves_handler.py | 20 +++++++++ backend/tests/endpoints/test_saves.py | 47 ++++++++++++++++++++++ 3 files changed, 103 insertions(+), 13 deletions(-) diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index ed963e905..ce532f981 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -194,6 +194,13 @@ async def add_save( if slot: actual_filename = _apply_datetime_tag(sanitized_save_filename) + saves_path = fs_asset_handler.build_saves_file_path( + user=request.user, + platform_fs_slug=rom.platform.fs_slug, + rom_id=rom.id, + emulator=emulator, + ) + db_save = db_save_handler.get_save_by_filename( user_id=request.user.id, rom_id=rom.id, file_name=actual_filename, slot=slot ) @@ -231,13 +238,6 @@ async def add_save( f"Uploading save {hl(actual_filename)} for {hl(str(rom.name), color=BLUE)}" ) - saves_path = fs_asset_handler.build_saves_file_path( - user=request.user, - platform_fs_slug=rom.platform.fs_slug, - rom_id=rom.id, - emulator=emulator, - ) - await fs_asset_handler.write_file( file=saveFile, path=saves_path, filename=actual_filename ) @@ -266,6 +266,21 @@ async def add_save( existing_by_hash, _syncs_for_save(existing_by_hash.id, device), device ) + if db_save is None: + # The write above landed on saves_path/actual_filename, whose bytes can + # already belong to a save in another slot (file identity is path+name, + # independent of slot). If that row's recorded hash no longer matches + # what we just wrote, refresh it instead of inserting a duplicate, so it + # does not keep reporting metadata that mismatches the bytes on disk. + colliding_save = db_save_handler.get_save_by_path( + user_id=request.user.id, + rom_id=rom.id, + file_path=scanned_save.file_path, + file_name=actual_filename, + ) + if colliding_save and colliding_save.content_hash != scanned_save.content_hash: + db_save = colliding_save + if db_save: # Track where the bytes actually landed: the file is written under a # path derived from this request's emulator, which may differ from the @@ -282,13 +297,21 @@ async def add_save( update_data["slot"] = slot db_save = db_save_handler.update_save(db_save.id, update_data) - # The row moved to a new path, so the previously stored bytes are now - # orphaned. Remove them to avoid leaving stale save files on disk. + # The row moved to a new path, so the previously stored bytes may now + # be orphaned. Slot is not part of the on-disk location, so another + # row can still point at the old path; only unlink it if none do. if stale_full_path != db_save.full_path: - try: - await fs_asset_handler.remove_file(stale_full_path) - except FileNotFoundError: - pass + still_referenced = any( + other.id != db_save.id and other.full_path == stale_full_path + for other in db_save_handler.get_saves( + user_id=request.user.id, rom_id=rom.id + ) + ) + if not still_referenced: + try: + await fs_asset_handler.remove_file(stale_full_path) + except FileNotFoundError: + pass else: scanned_save.rom_id = rom.id scanned_save.user_id = request.user.id diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index 779daa4ed..d3da5ccad 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -50,6 +50,26 @@ class DBSavesHandler(DBBaseHandler): query = query.filter(Save.slot.is_(None)) return session.scalars(query.limit(1)).first() + @begin_session + def get_save_by_path( + self, + user_id: int, + rom_id: int, + file_path: str, + file_name: str, + session: Session = None, # type: ignore + ) -> Save | None: + # A save's on-disk identity is (file_path, file_name), independent of + # slot. Used to find whichever row owns the bytes an upload is about to + # overwrite. + return session.scalars( + select(Save) + .filter_by( + rom_id=rom_id, user_id=user_id, file_path=file_path, file_name=file_name + ) + .limit(1) + ).first() + @begin_session def get_save_by_content_hash( self, diff --git a/backend/tests/endpoints/test_saves.py b/backend/tests/endpoints/test_saves.py index e36f42e76..d46270a1b 100644 --- a/backend/tests/endpoints/test_saves.py +++ b/backend/tests/endpoints/test_saves.py @@ -2682,6 +2682,53 @@ class TestSlotScopedDedupeMatrix: assert second.json()["slot"] == "slot2" assert second.json()["content_hash"] == first.json()["content_hash"] + def test_slotless_upload_over_named_slot_file_refreshes_that_row( + self, + client, + access_token: str, + rom: Rom, + _isolated_assets_dir, + ): + """A slot-less upload that lands on a named slot's file (same emulator + and filename) must not leave that row reporting a stale hash. + + File identity is path+name, independent of slot, so writing new bytes + there overwrites the named slot's file. The colliding row is refreshed + in place rather than shadowed by a divergent null-slot duplicate. + """ + slotted = self._upload( + client, access_token, rom, _build_fixture_a_zip(), slot="slot1" + ) + assert slotted.status_code == status.HTTP_200_OK + shared_name = slotted.json()["file_name"] + + # Slot-less upload (slot param omitted) reusing the slot's on-disk + # filename, but with new bytes. + slotless = client.post( + f"/api/saves?rom_id={rom.id}&emulator=test_emulator", + files={ + "saveFile": ( + shared_name, + BytesIO(_build_fixture_b_zip()), + "application/octet-stream", + ) + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert slotless.status_code == status.HTTP_200_OK + assert slotless.json()["id"] == slotted.json()["id"] + assert slotless.json()["content_hash"] == FIXTURE_B_HASH + + # No divergent second row was created for the same file. + listing = client.get( + f"/api/saves?rom_id={rom.id}", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert listing.status_code == status.HTTP_200_OK + rows = [s for s in listing.json() if s["file_name"] == shared_name] + assert len(rows) == 1 + assert rows[0]["content_hash"] == FIXTURE_B_HASH + def test_different_bytes_same_slot_creates_distinct_records( self, client, From bd55da40069decd455ddbdf42bb2cf3e1e5ec61c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sun, 19 Jul 2026 22:59:37 -0400 Subject: [PATCH 3/3] cleanup --- backend/endpoints/saves.py | 15 +++------------ backend/handler/database/saves_handler.py | 6 ------ 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index ce532f981..989c91f0f 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -267,11 +267,7 @@ async def add_save( ) if db_save is None: - # The write above landed on saves_path/actual_filename, whose bytes can - # already belong to a save in another slot (file identity is path+name, - # independent of slot). If that row's recorded hash no longer matches - # what we just wrote, refresh it instead of inserting a duplicate, so it - # does not keep reporting metadata that mismatches the bytes on disk. + # Refresh hash if the file already exists to avoid mismatched metadata. colliding_save = db_save_handler.get_save_by_path( user_id=request.user.id, rom_id=rom.id, @@ -282,10 +278,7 @@ async def add_save( db_save = colliding_save if db_save: - # Track where the bytes actually landed: the file is written under a - # path derived from this request's emulator, which may differ from the - # existing row's location. Persisting file_path/emulator keeps the row's - # hash and its on-disk content from drifting apart. + # Track file path and emulator to prevent hash-content drift. stale_full_path = db_save.full_path update_data: dict = { "file_size_bytes": scanned_save.file_size_bytes, @@ -297,9 +290,7 @@ async def add_save( update_data["slot"] = slot db_save = db_save_handler.update_save(db_save.id, update_data) - # The row moved to a new path, so the previously stored bytes may now - # be orphaned. Slot is not part of the on-disk location, so another - # row can still point at the old path; only unlink it if none do. + # Delete orphaned bytes only if no other row references the old path. if stale_full_path != db_save.full_path: still_referenced = any( other.id != db_save.id and other.full_path == stale_full_path diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index d3da5ccad..739ae7030 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -41,9 +41,6 @@ class DBSavesHandler(DBBaseHandler): query = select(Save).filter_by( rom_id=rom_id, user_id=user_id, file_name=file_name ) - # `slot=None` scopes to the null-slot save, not "any slot", so a - # slot-less upload can never match (and overwrite) a save living in a - # named slot. if slot is not None: query = query.filter(Save.slot == slot) else: @@ -59,9 +56,6 @@ class DBSavesHandler(DBBaseHandler): file_name: str, session: Session = None, # type: ignore ) -> Save | None: - # A save's on-disk identity is (file_path, file_name), independent of - # slot. Used to find whichever row owns the bytes an upload is about to - # overwrite. return session.scalars( select(Save) .filter_by(