From f0d42102d03f6647f043223631274ab6a2d21933 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 26 Sep 2026 12:59:17 -0400 Subject: [PATCH 1/2] fix(sync): code-review fixes for deleted-save tracking Follow-up to #4789 from the code-review pass: - PUT /api/saves/{id} records the replaced bytes of a never-hashed save - rehash_save keeps updated_at, so a recompute is not read as a write - unstamped legacy versions keep their removal time when another is lost - prune_slot deletes its locked rows in one statement - 0138 creates the slot index after the collation change Co-Authored-By: Claude Opus 5.5 (1M context) --- .../alembic/versions/0138_exact_save_slots.py | 36 ++++++++--------- backend/endpoints/saves.py | 2 + .../database/deleted_assets_handler.py | 7 ++-- backend/handler/database/saves_handler.py | 7 ++-- backend/tests/endpoints/test_saves.py | 39 +++++++++++++++++++ .../database/test_deleted_assets_handler.py | 21 ++++++++++ .../handler/database/test_saves_handler.py | 15 +++++++ 7 files changed, 102 insertions(+), 25 deletions(-) diff --git a/backend/alembic/versions/0138_exact_save_slots.py b/backend/alembic/versions/0138_exact_save_slots.py index 3f2afb142..531f2e5fd 100644 --- a/backend/alembic/versions/0138_exact_save_slots.py +++ b/backend/alembic/versions/0138_exact_save_slots.py @@ -24,6 +24,24 @@ SLOT_COLUMNS = (("saves", True), ("deleted_assets", False)) def upgrade() -> None: + op.add_column( + "deleted_assets", + sa.Column("removed_at", CustomJSON(), nullable=True), + if_not_exists=True, + ) + collation = exact_collation(op.get_bind()) + if collation is not None: + for table, nullable in SLOT_COLUMNS: + # Skipped once done, so a run that died partway resumes without a rebuild. + if _slot_collation(table) != collation: + op.alter_column( + table, + "slot", + existing_type=sa.String(length=SAVE_SLOT_MAX_LENGTH), + type_=sa.String(length=SAVE_SLOT_MAX_LENGTH, collation=collation), + existing_nullable=nullable, + ) + # After the collation change, which would otherwise rebuild it. op.create_index( SAVE_SLOT_VERSIONS_INDEX, "saves", @@ -32,24 +50,6 @@ def upgrade() -> None: ["rom_id", "user_id", "slot", "updated_at"], if_not_exists=True, ) - op.add_column( - "deleted_assets", - sa.Column("removed_at", CustomJSON(), nullable=True), - if_not_exists=True, - ) - collation = exact_collation(op.get_bind()) - if collation is None: - return - for table, nullable in SLOT_COLUMNS: - # Skipped once done, so a run that died partway resumes without a rebuild. - if _slot_collation(table) != collation: - op.alter_column( - table, - "slot", - existing_type=sa.String(length=SAVE_SLOT_MAX_LENGTH), - type_=sa.String(length=SAVE_SLOT_MAX_LENGTH, collation=collation), - existing_nullable=nullable, - ) def downgrade() -> None: diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index da0904d82..48ed226bc 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -622,6 +622,7 @@ async def update_save( raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) if saveFile: + replaced_hash = await unrecorded_hash(db_save) await fs_asset_handler.write_file( file=saveFile, path=db_save.file_path, filename=db_save.file_name ) @@ -638,6 +639,7 @@ async def update_save( "file_size_bytes": scanned_save.file_size_bytes, "content_hash": scanned_save.content_hash, }, + replaced_hash=replaced_hash, ) if screenshotFile and screenshotFile.filename: diff --git a/backend/handler/database/deleted_assets_handler.py b/backend/handler/database/deleted_assets_handler.py index 7d1116cc7..442c21854 100644 --- a/backend/handler/database/deleted_assets_handler.py +++ b/backend/handler/database/deleted_assets_handler.py @@ -99,17 +99,16 @@ class DBDeletedAssetsHandler(DBBaseHandler): record = self.lock_record(user_id, rom_id, slot, session) if record is None: raise + # Read before the flush bumps `updated_at`, which unstamped versions fall back to. + previous = record.removal_times() # A version lost again moves to the end, so trimming keeps it. lost = dict.fromkeys(content_hashes) hashes = [h for h in record.content_hashes if h not in lost] + list(lost) hashes = hashes[-MAX_REMEMBERED_HASHES:] now = datetime.now(timezone.utc).isoformat() - stamped = record.removed_at or {} record.content_hashes = hashes record.removed_at = { - h: now if h in lost else stamped[h] - for h in hashes - if h in lost or h in stamped + h: now if h in lost else previous[h].isoformat() for h in hashes } session.flush() return record diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index 72f744a52..538c811ce 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -337,10 +337,11 @@ class DBSavesHandler(DBBaseHandler): Returns: Whether the row still held ``replacing`` and took the new hash. """ + # Keeps `updated_at`, as `touch=False` does: device sync reads it as a write. result = session.execute( update(Save) .where(Save.id == id, Save.content_hash.is_not_distinct_from(replacing)) - .values(content_hash=content_hash) + .values(content_hash=content_hash, updated_at=Save.updated_at) .execution_options(synchronize_session=False) ) return affected_rows(result) == 1 @@ -425,10 +426,10 @@ class DBSavesHandler(DBBaseHandler): _deleted_assets.record_deletions( user_id, rom_id, slot, lost, session=session ) - for row in rows: + if rows: session.execute( delete(Save) - .where(Save.id == row.id) + .where(Save.id.in_([row.id for row in rows])) .execution_options(synchronize_session="evaluate") ) return rows diff --git a/backend/tests/endpoints/test_saves.py b/backend/tests/endpoints/test_saves.py index 41fea9b60..c3ebb42cc 100644 --- a/backend/tests/endpoints/test_saves.py +++ b/backend/tests/endpoints/test_saves.py @@ -3652,6 +3652,45 @@ class TestSlotScopedDedupeMatrix: [slotted.json()["content_hash"]], ) + def test_updating_a_save_never_hashed_records_its_bytes( + self, + client, + access_token: str, + rom: Rom, + admin_user: User, + _isolated_assets_dir, + ): + slotted = self._upload( + client, access_token, rom, _build_fixture_a_zip(), slot="slot1" + ) + with sync_session.begin() as session: + session.execute( + update(Save) + .where(Save.id == slotted.json()["id"]) + .values(content_hash=None) + ) + + response = client.put( + f"/api/saves/{slotted.json()['id']}", + files={ + "saveFile": ( + slotted.json()["file_name"], + BytesIO(_build_fixture_b_zip()), + "application/octet-stream", + ) + }, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + [record] = db_deleted_asset_handler.get_deletions( + user_id=admin_user.id, rom_ids=[rom.id] + ) + assert (record.slot, record.content_hashes) == ( + "slot1", + [slotted.json()["content_hash"]], + ) + def test_different_bytes_same_slot_creates_distinct_records( self, client, diff --git a/backend/tests/handler/database/test_deleted_assets_handler.py b/backend/tests/handler/database/test_deleted_assets_handler.py index 179b7244e..5eba44c26 100644 --- a/backend/tests/handler/database/test_deleted_assets_handler.py +++ b/backend/tests/handler/database/test_deleted_assets_handler.py @@ -1,6 +1,9 @@ from datetime import datetime, timezone +from sqlalchemy import update + from handler.database import db_deleted_asset_handler +from handler.database.base_handler import sync_session from models.deleted_asset import MAX_REMEMBERED_HASHES, DeletedAsset from models.rom import Rom from models.user import User @@ -100,6 +103,24 @@ class TestRemovalTimes: "stamped": to_utc(record.updated_at), } + def test_an_unstamped_version_keeps_its_time_when_another_is_lost( + self, rom: Rom, admin_user: User + ): + """Recording bumps the record's own time, which must not move older losses.""" + legacy = _record(admin_user, rom, "autosave", "legacy") + recorded = datetime(2026, 1, 1, tzinfo=timezone.utc) + with sync_session.begin() as session: + session.execute( + update(DeletedAsset) + .where(DeletedAsset.id == legacy.id) + .values(removed_at=None, updated_at=recorded) + ) + + times = _record(admin_user, rom, "autosave", "later").removal_times() + + assert times["legacy"] == recorded + assert times["later"] > recorded + def test_trimmed_versions_lose_their_stamps(self, rom: Rom, admin_user: User): for index in range(MAX_REMEMBERED_HASHES + 1): record = _record(admin_user, rom, "autosave", f"v{index}") diff --git a/backend/tests/handler/database/test_saves_handler.py b/backend/tests/handler/database/test_saves_handler.py index 02d273658..18d84679d 100644 --- a/backend/tests/handler/database/test_saves_handler.py +++ b/backend/tests/handler/database/test_saves_handler.py @@ -25,6 +25,7 @@ from models.assets import Save from models.platform import Platform from models.rom import Rom from models.user import User +from utils.datetime import to_utc class TestDBSavesHandlerPlatformFiltering: @@ -1295,6 +1296,20 @@ class TestDBSavesHandlerRecordsLostVersions: assert db_save_handler.rehash_save(save.id, "entries_md5", replacing="raw_md5") assert self._lost(admin_user, rom) == {} + def test_a_recomputed_hash_keeps_the_saves_timestamp( + self, admin_user: User, rom: Rom + ): + """Device sync reads `updated_at` as a write, and the bytes are unchanged.""" + save = self._add(admin_user, rom, "rehashed", "autosave", "raw_md5") + written = datetime(2026, 1, 1, tzinfo=UTC) + db_save_handler.update_save(save.id, {"updated_at": written}) + + db_save_handler.rehash_save(save.id, "entries_md5", replacing="raw_md5") + + [kept] = db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[rom.id]) + assert kept.content_hash == "entries_md5" + assert to_utc(kept.updated_at) == written + def test_a_recomputed_hash_never_replaces_a_newer_one( self, admin_user: User, rom: Rom ): From a06ec55060a9528edcaf75296ef97219eda8687f Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 26 Sep 2026 13:11:37 -0400 Subject: [PATCH 2/2] refactor(sync): simplify pass over deleted-save tracking - Move unrecorded_hash onto FSAssetsHandler, so sync_watcher and the push-pull task no longer import handler.asset_store (and with it scan_handler and every metadata provider, ~80 modules) - Drop the PSP bundle's unrecorded_hash call: bundles are never slotted - Skip the removal-times query when the device's copy already matches - Restore per-row deletes in prune_slot: the single `id IN (...)` delete from the review pass deadlocked the threaded removal test 3/10 runs on MariaDB (0/25 per row) Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/endpoints/saves.py | 7 ++++--- backend/endpoints/sync/retroarch.py | 9 ++++++--- backend/handler/asset_store.py | 11 +++-------- backend/handler/database/saves_handler.py | 5 +++-- backend/handler/filesystem/assets_handler.py | 10 ++++++++++ backend/handler/sync/retroarch/psp.py | 3 --- backend/sync_watcher.py | 12 ++++++++---- backend/tasks/sync_push_pull_task.py | 12 ++++++++---- 8 files changed, 42 insertions(+), 27 deletions(-) diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index 48ed226bc..846d91e48 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -17,7 +17,6 @@ from handler.asset_store import ( prune_save_slot, remove_save, rename_asset, - unrecorded_hash, ) from handler.auth.constants import Scope from handler.auth.dependencies import assert_rom_visible @@ -288,7 +287,9 @@ async def add_save( ) ) replaced = db_save or colliding_save - replaced_hash = await unrecorded_hash(replaced) if replaced else None + replaced_hash = ( + await fs_asset_handler.unrecorded_hash(replaced) if replaced else None + ) await fs_asset_handler.write_file( file=saveFile, path=saves_path, filename=actual_filename ) @@ -622,7 +623,7 @@ async def update_save( raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error) if saveFile: - replaced_hash = await unrecorded_hash(db_save) + replaced_hash = await fs_asset_handler.unrecorded_hash(db_save) await fs_asset_handler.write_file( file=saveFile, path=db_save.file_path, filename=db_save.file_name ) diff --git a/backend/endpoints/sync/retroarch.py b/backend/endpoints/sync/retroarch.py index 240781f89..296956ef3 100644 --- a/backend/endpoints/sync/retroarch.py +++ b/backend/endpoints/sync/retroarch.py @@ -10,7 +10,6 @@ from urllib.parse import quote from fastapi import APIRouter, Request, Response, UploadFile, status from fastapi.responses import JSONResponse, RedirectResponse -from handler.asset_store import unrecorded_hash from handler.auth.constants import Scope from handler.auth.dependencies import get_permissions from handler.auth.permissions import ResolvedPermissions @@ -570,7 +569,9 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response: existing = _get_asset(request.user, rom, parsed) write_file_name = existing.file_name if existing else file_name replaced_hash = ( - await unrecorded_hash(existing) if isinstance(existing, Save) else None + await fs_asset_handler.unrecorded_hash(existing) + if isinstance(existing, Save) + else None ) async with _request_body(request) as body: @@ -664,7 +665,9 @@ async def retroarch_sync_delete(request: Request, file_path: str) -> Response: if isinstance(asset, Screenshot): db_screenshot_handler.delete_screenshot(asset.id) elif isinstance(asset, Save): - db_save_handler.delete_save(asset.id, content_hash=await unrecorded_hash(asset)) + db_save_handler.delete_save( + asset.id, content_hash=await fs_asset_handler.unrecorded_hash(asset) + ) else: db_state_handler.delete_state(asset.id) diff --git a/backend/handler/asset_store.py b/backend/handler/asset_store.py index ad165a5c5..8ed935ed4 100644 --- a/backend/handler/asset_store.py +++ b/backend/handler/asset_store.py @@ -154,16 +154,11 @@ async def release_thumbnail(screenshot: Screenshot | None) -> None: await remove_asset_file(path, "Screenshot file") -async def unrecorded_hash(save: Save) -> str | None: - """The file's hash for a slotted save never hashed, so its removal is still recorded.""" - if save.slot and not save.content_hash: - return await fs_asset_handler.compute_content_hash(save.full_path) - return None - - async def remove_save(save: Save) -> None: """Drop a save row with its file and screenshot.""" - db_save_handler.delete_save(save.id, content_hash=await unrecorded_hash(save)) + db_save_handler.delete_save( + save.id, content_hash=await fs_asset_handler.unrecorded_hash(save) + ) await remove_asset_file(save.full_path, "Save file") await release_thumbnail(save.screenshot) diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index 538c811ce..da88c0217 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -426,10 +426,11 @@ class DBSavesHandler(DBBaseHandler): _deleted_assets.record_deletions( user_id, rom_id, slot, lost, session=session ) - if rows: + # One row at a time: MariaDB's `id IN (...)` plan deadlocks concurrent prunes. + for row in rows: session.execute( delete(Save) - .where(Save.id.in_([row.id for row in rows])) + .where(Save.id == row.id) .execution_options(synchronize_session="evaluate") ) return rows diff --git a/backend/handler/filesystem/assets_handler.py b/backend/handler/filesystem/assets_handler.py index 411d1d2a7..507637f5d 100644 --- a/backend/handler/filesystem/assets_handler.py +++ b/backend/handler/filesystem/assets_handler.py @@ -4,6 +4,7 @@ import threading import zipfile from mimetypes import guess_type from pathlib import Path +from typing import TYPE_CHECKING import magic from fastapi import HTTPException, UploadFile, status @@ -16,6 +17,9 @@ from utils.media_types import IMAGE_EXT_BY_MIME_TYPE from .base_handler import FSHandler +if TYPE_CHECKING: + from models.assets import Save + # libmagic loads its database on construction (~few MB read from disk), so we # share a single Magic instance across requests. The underlying magic_t handle # is not thread-safe, so guard from_buffer with a lock. Endpoints that call @@ -201,3 +205,9 @@ class FSAssetsHandler(FSHandler): except Exception as e: log.debug(f"Failed to compute content hash for {file_path}: {e}") return None + + async def unrecorded_hash(self, save: "Save") -> str | None: + """The file's hash for a slotted save never hashed, so its removal is still recorded.""" + if save.slot and not save.content_hash: + return await self.compute_content_hash(save.full_path) + return None diff --git a/backend/handler/sync/retroarch/psp.py b/backend/handler/sync/retroarch/psp.py index b821cae36..9d80fe3ab 100644 --- a/backend/handler/sync/retroarch/psp.py +++ b/backend/handler/sync/retroarch/psp.py @@ -23,7 +23,6 @@ from typing import Literal from redis.exceptions import RedisError from config import SYNC_RETROARCH_PSP_PENDING_PATH, SYNC_RETROARCH_PSP_SERIAL_MAP -from handler.asset_store import unrecorded_hash from handler.database import db_platform_handler, db_rom_handler, db_save_handler from handler.filesystem import fs_asset_handler from handler.filesystem.base_handler import FSHandler @@ -447,7 +446,6 @@ async def put_psp_file( async def _rewrite_bundle(bundle: Save, entries: dict[str, bytes]) -> None: """Write `entries` over the bundle's own file and refresh its row.""" zip_bytes = await asyncio.to_thread(_write_bundle, entries) - replaced_hash = await unrecorded_hash(bundle) await fs_asset_handler.write_file( file=zip_bytes, path=bundle.file_path, filename=bundle.file_name ) @@ -458,7 +456,6 @@ async def _rewrite_bundle(bundle: Save, entries: dict[str, bytes]) -> None: "content_hash": content_hash_of_bytes(zip_bytes), "missing_from_fs": False, }, - replaced_hash=replaced_hash, ) await _cache_member_md5s(updated, entries) diff --git a/backend/sync_watcher.py b/backend/sync_watcher.py index b7554465e..b85657ef9 100644 --- a/backend/sync_watcher.py +++ b/backend/sync_watcher.py @@ -20,7 +20,6 @@ from typing import cast import sentry_sdk from config import ENABLE_SYNC_FOLDER_WATCHER, SENTRY_DSN -from handler.asset_store import unrecorded_hash from handler.database import ( db_deleted_asset_handler, db_device_handler, @@ -251,8 +250,13 @@ def _process_incoming_file( server_hash=matched_save.content_hash, server_updated_at=matched_save.updated_at, device_last_synced_at=device_sync.last_synced_at if device_sync else None, - removed_at=db_deleted_asset_handler.removal_times( - device.user_id, matched_save.rom_id, matched_save.slot + # Identical content is a no_op, which never reads removals. + removed_at=( + db_deleted_asset_handler.removal_times( + device.user_id, matched_save.rom_id, matched_save.slot + ) + if file_hash != matched_save.content_hash + else None ), ) @@ -268,7 +272,7 @@ def _process_incoming_file( ) with open(full_path, "rb") as f: file_data = f.read() - replaced_hash = asyncio.run(unrecorded_hash(matched_save)) + replaced_hash = asyncio.run(fs_asset_handler.unrecorded_hash(matched_save)) asyncio.run( fs_asset_handler.write_file( file=file_data, diff --git a/backend/tasks/sync_push_pull_task.py b/backend/tasks/sync_push_pull_task.py index 2fb4faa01..f31a235d2 100644 --- a/backend/tasks/sync_push_pull_task.py +++ b/backend/tasks/sync_push_pull_task.py @@ -12,7 +12,6 @@ from anyio import Path as AnyioPath from anyio import open_file from config import ENABLE_SYNC_PUSH_PULL, SYNC_PUSH_PULL_CRON -from handler.asset_store import unrecorded_hash from handler.database import ( db_deleted_asset_handler, db_device_handler, @@ -268,8 +267,13 @@ async def _process_remote_save( server_hash=matched_save.content_hash, server_updated_at=matched_save.updated_at, device_last_synced_at=device_sync.last_synced_at if device_sync else None, - removed_at=db_deleted_asset_handler.removal_times( - device.user_id, matched_save.rom_id, matched_save.slot + # Identical content is a no_op, which never reads removals. + removed_at=( + db_deleted_asset_handler.removal_times( + device.user_id, matched_save.rom_id, matched_save.slot + ) + if remote_hash != matched_save.content_hash + else None ), ) @@ -289,7 +293,7 @@ async def _process_remote_save( ) async with await open_file(local_path, "rb") as f: file_data = await f.read() - replaced_hash = await unrecorded_hash(matched_save) + replaced_hash = await fs_asset_handler.unrecorded_hash(matched_save) await fs_asset_handler.write_file( file=file_data, path=matched_save.file_path,