fix(sync): make deleted-save tracking exact, complete, and effective on filled slots (#4789)

This commit is contained in:
Sam Dornan
2026-09-26 12:33:54 -04:00
committed by GitHub
parent 6002b8fdaa
commit d1ce4e3db2
29 changed files with 1841 additions and 155 deletions

View File

@@ -9,7 +9,7 @@ Create Date: 2026-09-21 00:00:00.000000
import sqlalchemy as sa
from alembic import op
from utils.database import CustomJSON
from utils.database import CustomJSON, exact_collation
# revision identifiers, used by Alembic.
revision = "0136_deleted_assets"
@@ -27,7 +27,11 @@ def upgrade() -> None:
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("rom_id", sa.Integer(), nullable=False),
sa.Column("slot", sa.String(length=255), nullable=False),
sa.Column(
"slot",
sa.String(length=255, collation=exact_collation(op.get_bind())),
nullable=False,
),
sa.Column("content_hashes", CustomJSON(), nullable=False),
sa.Column(
"created_at",

View File

@@ -0,0 +1,78 @@
"""Compare save slots exactly, index a slot's versions, and time their removal
Revision ID: 0138_exact_save_slots
Revises: 0137_rename_system_groups
Create Date: 2026-09-26 00:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
from models.assets import SAVE_SLOT_MAX_LENGTH, SAVE_SLOT_VERSIONS_INDEX
from utils.database import CustomJSON, exact_collation
# revision identifiers, used by Alembic.
revision = "0138_exact_save_slots"
down_revision = "0137_rename_system_groups"
branch_labels = None
depends_on = None
# Each slot column and its nullability. deleted_assets is included for
# databases that ran 0136 before it created the column exact.
SLOT_COLUMNS = (("saves", True), ("deleted_assets", False))
def upgrade() -> None:
op.create_index(
SAVE_SLOT_VERSIONS_INDEX,
"saves",
# Led by rom_id, which another index already serves as a foreign key:
# a user_id lead would replace MariaDB's own index for that key.
["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:
op.drop_column("deleted_assets", "removed_at", if_exists=True)
op.drop_index(SAVE_SLOT_VERSIONS_INDEX, table_name="saves", if_exists=True)
collation = exact_collation(op.get_bind())
# 0136 creates deleted_assets.slot exact, so only saves.slot reverts.
if collation is None or _slot_collation("saves") != collation:
return
# Without a collation the column takes the table's default back.
op.alter_column(
"saves",
"slot",
existing_type=sa.String(length=SAVE_SLOT_MAX_LENGTH),
type_=sa.String(length=SAVE_SLOT_MAX_LENGTH),
existing_nullable=True,
)
def _slot_collation(table: str) -> str | None:
[column] = [
column
for column in sa.inspect(op.get_bind()).get_columns(table)
if column["name"] == "slot"
]
return column["type"].collation

View File

@@ -12,7 +12,8 @@ class SyncOperationSchema(BaseModel):
"Operation the client should perform. 'upload' when the client has a "
"save the server lacks (including any null-slot save, which is never "
"paired with server saves), 'download' when the server has a newer or "
"unknown save, 'conflict' when both sides changed independently, "
"unknown save or the client holds a version removed here, 'conflict' "
"when both sides changed independently, "
"'delete' when the slot the client still holds was emptied here, and "
"'no_op' when no action is needed."
)

View File

@@ -13,11 +13,15 @@ from endpoints.responses.assets import SaveSchema, SaveSummarySchema, SlotSummar
from endpoints.responses.device import DeviceSyncSchema
from endpoints.roms import refresh_affected_smart_collections
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from handler.asset_store import release_thumbnail, remove_asset_file, rename_asset
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
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
db_device_save_sync_handler,
db_rom_handler,
@@ -107,42 +111,6 @@ def _syncs_for_save(
DATETIME_TAG_PATTERN = re.compile(r" \[\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\]")
async def _delete_save(save: Save) -> None:
"""Drop a save row with its file and screenshot."""
# Recorded first: a record for a save still present is never read, while
# a deletion with no record lets every device holding it offer it back.
if save.slot:
content_hash = save.content_hash or (
await fs_asset_handler.compute_content_hash(save.full_path)
)
if content_hash:
db_deleted_asset_handler.record_deletion(
user_id=save.user_id,
rom_id=save.rom_id,
slot=save.slot,
content_hash=content_hash,
)
db_save_handler.delete_save(save.id)
await remove_asset_file(save.full_path, "Save file")
await release_thumbnail(save.screenshot)
async def _prune_slot(user_id: int, rom_id: int, slot: str, keep: int) -> None:
"""Drop every version of ``slot`` past the ``keep`` newest, files included."""
for file_path, file_name, file_name_no_ext in db_save_handler.prune_slot(
user_id=user_id, rom_id=rom_id, slot=slot, keep=keep
):
await remove_asset_file(f"{file_path}/{file_name}", "Save file")
await release_thumbnail(
db_screenshot_handler.get_screenshot(
rom_id=rom_id,
user_id=user_id,
file_name=file_name,
file_name_no_ext=file_name_no_ext,
)
)
def _slot_retention(autocleanup: bool, autocleanup_limit: int) -> int | None:
"""Versions to keep in a slot: the tighter of the client's ask and the server cap."""
limits = [MAX_SAVES_PER_SLOT] if MAX_SAVES_PER_SLOT else []
@@ -308,6 +276,19 @@ async def add_save(
f"Uploading save {hl(actual_filename)} for {hl(str(rom.name), color=BLUE)}"
)
# Looked up before the write, which replaces a colliding save's bytes.
colliding_save = (
None
if db_save
else db_save_handler.get_save_by_path(
user_id=request.user.id,
rom_id=rom.id,
file_path=saves_path,
file_name=actual_filename,
)
)
replaced = db_save or colliding_save
replaced_hash = await unrecorded_hash(replaced) if replaced else None
await fs_asset_handler.write_file(
file=saveFile, path=saves_path, filename=actual_filename
)
@@ -334,21 +315,14 @@ async def add_save(
pass
# A retry still counts as an upload to the slot, so the cap applies.
if keep is not None:
await _prune_slot(request.user.id, rom.id, slot, keep)
await prune_save_slot(request.user.id, rom.id, slot, keep)
return _build_save_schema(
existing_by_hash, _syncs_for_save(existing_by_hash.id, device), device
)
if db_save is None:
# 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,
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
# Refresh hash if the file already exists to avoid mismatched metadata.
if colliding_save and colliding_save.content_hash != scanned_save.content_hash:
db_save = colliding_save
if db_save:
# Track file path and emulator to prevent hash-content drift.
@@ -361,7 +335,9 @@ async def add_save(
}
if slot is not None:
update_data["slot"] = slot
db_save = db_save_handler.update_save(db_save.id, update_data)
db_save = db_save_handler.update_save(
db_save.id, update_data, replaced_hash=replaced_hash
)
# Delete orphaned bytes only if no other row references the old path.
if stale_full_path != db_save.full_path:
@@ -394,7 +370,7 @@ async def add_save(
_increment_session_counter(session_id, request.user.id)
if slot and keep is not None:
await _prune_slot(request.user.id, rom.id, slot, keep)
await prune_save_slot(request.user.id, rom.id, slot, keep)
if screenshotFile and screenshotFile.filename:
try:
@@ -852,7 +828,7 @@ async def delete_saves(
log.info(
f"Deleting save {hl(save.file_name)} [{save.rom.platform_slug}] from filesystem"
)
await _delete_save(save)
await remove_save(save)
refresh_affected_smart_collections(list(affected_rom_ids), membership_only=True)

View File

@@ -30,7 +30,11 @@ from handler.database import (
)
from handler.play_session_handler import ingest_play_sessions
from handler.redis_handler import high_prio_queue
from handler.sync.comparison import compare_missing_server_save, compare_save_state
from handler.sync.comparison import (
compare_missing_server_save,
compare_save_state,
roms_to_check_for_removals,
)
from logger.logger import log
from models.assets import Save
from models.deleted_asset import DeletedAsset
@@ -231,17 +235,11 @@ def negotiate_sync(
if current is None or to_utc(save.updated_at) > to_utc(current.updated_at):
server_save_map[key] = save
# Read only when a slot has no row left, so a slot refilled since keeps
# its record harmlessly.
emptied_rom_ids = {
s.rom_id
for s in payload.saves
if s.slot and (s.rom_id, s.slot) not in server_save_map
}
deleted_map: dict[tuple[int, str | None], DeletedAsset] = {
(record.rom_id, record.slot): record
for record in db_deleted_asset_handler.get_deletions(
user_id=request.user.id, rom_ids=emptied_rom_ids
user_id=request.user.id,
rom_ids=roms_to_check_for_removals(payload.saves, server_save_map),
)
}
@@ -259,13 +257,14 @@ def negotiate_sync(
for client_save in payload.saves:
key = (client_save.rom_id, client_save.slot)
server_save = server_save_map.get(key)
# Without this the client offers a removed version back and the
# deletion or rollback undoes itself.
deletion = deleted_map.get(key)
removed_at = deletion.removal_times() if deletion else {}
if server_save is None:
# Without this the client offers the save back and the deletion
# undoes itself.
deletion = deleted_map.get(key)
result = compare_missing_server_save(
client_save.content_hash, deletion.content_hashes if deletion else ()
client_save.content_hash, client_save.updated_at, removed_at
)
operations.append(
SyncOperationSchema(
@@ -304,6 +303,7 @@ def negotiate_sync(
server_hash=server_save.content_hash,
server_updated_at=server_save.updated_at,
device_last_synced_at=device_sync.last_synced_at if device_sync else None,
removed_at=removed_at,
)
operations.append(

View File

@@ -10,6 +10,7 @@ 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
@@ -482,7 +483,7 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
await psp.put_psp_file(
request.user, psp_path, content, _rom_visibility(request)
)
except (psp.PspFolderUnresolved, psp.PspBundleInvalid, ValueError):
except psp.PspFolderUnresolved, psp.PspBundleInvalid, ValueError:
return _empty(status.HTTP_409_CONFLICT)
return _empty(status.HTTP_201_CREATED)
@@ -568,6 +569,9 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
# the row pointing at the fresh bytes instead of orphaning them.
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
)
async with _request_body(request) as body:
await fs_asset_handler.write_file(
@@ -592,7 +596,9 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
}
if isinstance(scanned, Save):
db_save_handler.update_save(
existing.id, {**fields, "content_hash": scanned.content_hash}
existing.id,
{**fields, "content_hash": scanned.content_hash},
replaced_hash=replaced_hash,
)
else:
db_state_handler.update_state(existing.id, fields)
@@ -658,7 +664,7 @@ 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)
db_save_handler.delete_save(asset.id, content_hash=await unrecorded_hash(asset))
else:
db_state_handler.delete_state(asset.id)

View File

@@ -19,6 +19,7 @@ from handler.database import (
db_state_handler,
)
from handler.database.base_handler import sync_session
from handler.database.saves_handler import UnhashedVersions
from handler.filesystem import fs_asset_handler
from handler.scan_handler import scan_screenshot, scan_state
from logger.formatter import highlight as hl
@@ -153,6 +154,52 @@ 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))
await remove_asset_file(save.full_path, "Save file")
await release_thumbnail(save.screenshot)
async def prune_save_slot(user_id: int, rom_id: int, slot: str, keep: int) -> None:
"""Drop every version of ``slot`` past the ``keep`` newest, files included."""
# Hashed outside the slot's lock, recorded by the prune that deletes them.
# Each pass hashes only what the last one lacked.
file_hashes: dict[int, str | None] = {}
while True:
try:
pruned = db_save_handler.prune_slot(
user_id=user_id,
rom_id=rom_id,
slot=slot,
keep=keep,
fallback_hashes=file_hashes,
)
break
except UnhashedVersions as unhashed:
for version in unhashed.versions:
file_hashes[version.id] = await fs_asset_handler.compute_content_hash(
f"{version.file_path}/{version.file_name}"
)
for version in pruned:
await remove_asset_file(f"{version.file_path}/{version.file_name}", "Save file")
await release_thumbnail(
db_screenshot_handler.get_screenshot(
rom_id=rom_id,
user_id=user_id,
file_name=version.file_name,
file_name_no_ext=version.file_name_no_ext,
)
)
def _name_taken(file_name: str) -> HTTPException:
return HTTPException(
status_code=status.HTTP_409_CONFLICT,

View File

@@ -1,4 +1,5 @@
from collections.abc import Collection, Sequence
from datetime import datetime, timezone
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
@@ -11,37 +12,107 @@ from .base_handler import DBBaseHandler
class DBDeletedAssetsHandler(DBBaseHandler):
def ensure_record(self, user_id: int, rom_id: int, slot: str) -> None:
"""Create the slot's empty record if it has none, in its own transaction."""
# Recording then only locks a row that exists: on MariaDB, locking a
# missing key and then inserting deadlocks a concurrent deletion.
if self._exists(user_id, rom_id, slot):
return
try:
self._insert(user_id, rom_id, slot)
except IntegrityError:
pass # A concurrent deletion of the same slot inserted first.
@begin_session
def _exists(
self,
user_id: int,
rom_id: int,
slot: str,
session: Session = None, # type: ignore[assignment]
) -> bool:
return (
session.scalar(
select(DeletedAsset.id).filter_by(
user_id=user_id, rom_id=rom_id, slot=slot
)
)
is not None
)
def record_deletion(
self,
user_id: int,
rom_id: int,
slot: str,
content_hash: str,
session: Session | None = None,
) -> DeletedAsset:
"""Remember a version this slot lost, keeping one row per slot.
"""Remember one version this slot lost, as `record_deletions` does."""
return self.record_deletions(
user_id, rom_id, slot, [content_hash], session=session
)
def record_deletions(
self,
user_id: int,
rom_id: int,
slot: str,
content_hashes: Sequence[str],
session: Session | None = None,
) -> DeletedAsset:
"""Remember versions this slot lost, oldest first, keeping one row per slot.
Args:
user_id: Whose library the slot belongs to.
rom_id: The ROM whose slot lost a version.
rom_id: The ROM whose slot lost the versions.
slot: The slot itself.
content_hash: What that version held.
content_hashes: What those versions held, oldest first.
session: The transaction losing the versions, so both commit
together. Its caller runs `ensure_record` before taking locks.
Returns:
The record a negotiation will read.
"""
# Separate transactions: on MariaDB, locking a missing key and then
# inserting deadlocks a concurrent deletion, even of another slot.
record = self._merge(user_id, rom_id, slot, content_hash)
if record:
return record
try:
return self._insert(user_id, rom_id, slot, content_hash)
except IntegrityError:
# A concurrent deletion of the same slot inserted first.
record = self._merge(user_id, rom_id, slot, content_hash)
if not record:
raise
return record
if session is None:
self.ensure_record(user_id, rom_id, slot)
return self._append(user_id, rom_id, slot, content_hashes)
return self._append(user_id, rom_id, slot, content_hashes, session=session)
@begin_session
def _append(
self,
user_id: int,
rom_id: int,
slot: str,
content_hashes: Sequence[str],
session: Session = None, # type: ignore[assignment]
) -> DeletedAsset:
record = self.lock_record(user_id, rom_id, slot, session)
if record is None:
# The slot changed since its record was ensured, or it was never ensured.
try:
with session.begin_nested():
record = self._insert(user_id, rom_id, slot, session=session)
except IntegrityError:
# A concurrent deletion of the same slot inserted first.
record = self.lock_record(user_id, rom_id, slot, session)
if record is None:
raise
# 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
}
session.flush()
return record
@begin_session
def _insert(
@@ -49,42 +120,39 @@ class DBDeletedAssetsHandler(DBBaseHandler):
user_id: int,
rom_id: int,
slot: str,
content_hash: str,
session: Session = None, # type: ignore[assignment]
) -> DeletedAsset:
record = DeletedAsset(
user_id=user_id,
rom_id=rom_id,
slot=slot,
content_hashes=[content_hash],
user_id=user_id, rom_id=rom_id, slot=slot, content_hashes=[], removed_at={}
)
session.add(record)
session.flush()
return record
@begin_session
def _merge(
self,
user_id: int,
rom_id: int,
slot: str,
content_hash: str,
session: Session = None, # type: ignore[assignment]
@staticmethod
def lock_record(
user_id: int, rom_id: int, slot: str, session: Session
) -> DeletedAsset | None:
"""Add this version to the slot's record, or None when it has none yet."""
record = session.scalar(
"""Lock the slot's record, which serializes every change to the slot's versions."""
return session.scalar(
select(DeletedAsset)
.filter_by(user_id=user_id, rom_id=rom_id, slot=slot)
.with_for_update()
)
if not record:
return None
# A version lost again moves to the end, so trimming keeps it.
hashes = [h for h in record.content_hashes if h != content_hash]
hashes.append(content_hash)
record.content_hashes = hashes[-MAX_REMEMBERED_HASHES:]
session.flush()
return record
@begin_session
def removal_times(
self,
user_id: int,
rom_id: int,
slot: str | None,
session: Session = None, # type: ignore[assignment]
) -> dict[str, datetime]:
"""When each version this slot lost was lost, empty for a slot that lost none."""
record = session.scalar(
select(DeletedAsset).filter_by(user_id=user_id, rom_id=rom_id, slot=slot)
)
return record.removal_times() if record else {}
@begin_session
def get_deletions(
@@ -93,7 +161,7 @@ class DBDeletedAssetsHandler(DBBaseHandler):
rom_ids: Collection[int],
session: Session = None, # type: ignore[assignment]
) -> Sequence[DeletedAsset]:
"""Every slot of these ROMs this user emptied."""
"""What each slot of these ROMs lost, for this user."""
if not rom_ids:
return []
return session.scalars(

View File

@@ -1,15 +1,52 @@
from collections.abc import Collection, Sequence
import functools
from collections.abc import Callable, Collection, Mapping, Sequence
from typing import Literal
from sqlalchemy import Select, and_, asc, delete, desc, func, or_, select, update
from sqlalchemy.engine import Row
from sqlalchemy.orm import Session
from decorators.database import begin_session
from models.assets import Save
from models.assets import SAVE_SLOT_VERSIONS_INDEX, Save
from models.base import with_file_name_parts
from models.rom import Rom
from .base_handler import DBBaseHandler
from .base_handler import DBBaseHandler, affected_rows
from .deleted_assets_handler import DBDeletedAssetsHandler
_deleted_assets = DBDeletedAssetsHandler()
# What identifies a version in its slot, for recording it when it leaves.
_VERSION_COLUMNS = (Save.user_id, Save.rom_id, Save.slot, Save.content_hash)
_SLOT_MOVE_ATTEMPTS = 3
class _SlotMoved(Exception):
"""The save changed slot between the unlocked read and its lock."""
class UnhashedVersions(Exception):
"""Versions a prune would drop without a hash to record them by."""
def __init__(self, versions: Sequence[Row]):
super().__init__(f"{len(versions)} versions to prune were never hashed")
self.versions = versions
def _retry_if_slot_moved[**P, R](func: Callable[P, R]) -> Callable[P, R]:
"""Rerun a removal in a fresh transaction, releasing the stale slot's lock."""
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
if kwargs.get("session") is not None:
return func(*args, **kwargs)
for _ in range(_SLOT_MOVE_ATTEMPTS - 1):
try:
return func(*args, **kwargs)
except _SlotMoved:
continue
return func(*args, **kwargs)
return wrapper
class DBSavesHandler(DBBaseHandler):
@@ -236,12 +273,36 @@ class DBSavesHandler(DBBaseHandler):
latest.setdefault(save.rom_id, save)
return latest
@begin_session
def _slot_version(
self,
id: int,
session: Session = None, # type: ignore[assignment]
) -> Row | None:
return session.execute(_version_query(id)).one_or_none()
def _lock_for_removal(self, id: int, session: Session) -> Row | None:
"""Lock the save's slot record, then the save, returning its current version."""
# Before this session holds a connection, since ensuring takes its own.
before = self._slot_version(id)
if not before:
return None
if before.slot:
_lock_slot(before.user_id, before.rom_id, before.slot, session)
current = session.execute(_version_query(id).with_for_update()).one_or_none()
# Locking the slot it moved to now would take a slot after a row.
if current and current.slot and current.slot != before.slot:
raise _SlotMoved
return current
@_retry_if_slot_moved
@begin_session
def update_save(
self,
id: int,
data: dict,
touch: bool = True,
replaced_hash: str | None = None,
session: Session = None, # type: ignore[assignment]
) -> Save:
"""Write `data` onto a save.
@@ -249,8 +310,43 @@ class DBSavesHandler(DBBaseHandler):
Args:
touch: False keeps `updated_at`, since annotating is not a write
to the bytes and device sync reads it to detect staleness.
replaced_hash: What the version held, for a row that never hashed it.
"""
data = with_file_name_parts(data)
if "content_hash" in data or "slot" in data:
current = self._lock_for_removal(id, session)
if current and _loses_version(current, data):
_record_loss(current, session, replaced_hash)
return self._write(id, data, touch, session)
@begin_session
def rehash_save(
self,
id: int,
content_hash: str,
replacing: str | None,
session: Session = None, # type: ignore[assignment]
) -> bool:
"""Store a recomputed hash of the same bytes, so no version leaves the slot.
Args:
content_hash: The recomputed hash.
replacing: The hash it was computed against; a row holding another
was rewritten meanwhile and keeps its own.
Returns:
Whether the row still held ``replacing`` and took the new hash.
"""
result = session.execute(
update(Save)
.where(Save.id == id, Save.content_hash.is_not_distinct_from(replacing))
.values(content_hash=content_hash)
.execution_options(synchronize_session=False)
)
return affected_rows(result) == 1
@staticmethod
def _write(id: int, data: dict, touch: bool, session: Session) -> Save:
values = data if touch else {**data, "updated_at": Save.updated_at}
session.execute(
update(Save)
@@ -267,37 +363,100 @@ class DBSavesHandler(DBBaseHandler):
rom_id: int,
slot: str,
keep: int,
fallback_hashes: Mapping[int, str | None] | None = None,
session: Session = None, # type: ignore[assignment]
) -> list[tuple[str, str, str]]:
) -> Sequence[Row]:
"""Delete every version of a slot past the ``keep`` newest.
The rows are locked while they are listed and deleted, so two uploads
pruning the same slot cannot both keep a version the other dropped.
The slot's record is locked while its versions are listed and deleted,
so two uploads pruning it cannot both keep a version the other dropped.
Args:
fallback_hashes: What versions never hashed held, by save id, or
None for a file that couldn't be read.
Returns:
``(file_path, file_name, file_name_no_ext)`` of each deleted version.
Each deleted version's hash and ``file_path``, ``file_name`` and
``file_name_no_ext``, newest first.
Raises:
UnhashedVersions: Deleting nothing, for versions never hashed that
``fallback_hashes`` lacks.
"""
rows = session.execute(
select(Save.id, Save.file_path, Save.file_name, Save.file_name_no_ext)
past_keep = (
select(
Save.id,
*_VERSION_COLUMNS,
Save.file_path,
Save.file_name,
Save.file_name_no_ext,
)
.filter_by(user_id=user_id, rom_id=rom_id, slot=slot)
.order_by(desc(Save.updated_at), desc(Save.id))
.offset(keep)
)
# Before this session holds a connection, since ensuring takes its own.
if not self._any(past_keep):
return []
_lock_slot(user_id, rom_id, slot, session)
# Locks only this slot's rows and takes no snapshot, which MariaDB's
# snapshot isolation would fail the delete against.
hint = f"FORCE INDEX ({SAVE_SLOT_VERSIONS_INDEX})"
rows = session.execute(
past_keep.with_hint(Save, hint, "mariadb")
.with_hint(Save, hint, "mysql")
.with_for_update()
).all()
if rows:
fallback_hashes = fallback_hashes or {}
unhashed = [
row
for row in rows
if not row.content_hash and row.id not in fallback_hashes
]
if unhashed:
raise UnhashedVersions(unhashed)
# Oldest first, so trimming the record drops the oldest version first.
lost = [
content_hash
for row in reversed(rows)
if (content_hash := row.content_hash or fallback_hashes.get(row.id))
]
if lost:
_deleted_assets.record_deletions(
user_id, rom_id, slot, lost, session=session
)
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 [(row.file_path, row.file_name, row.file_name_no_ext) for row in rows]
return rows
@begin_session
def _any(
self,
query: Select,
session: Session = None, # type: ignore[assignment]
) -> bool:
return session.execute(query.limit(1)).first() is not None
@_retry_if_slot_moved
@begin_session
def delete_save(
self,
id: int,
content_hash: str | None = None,
session: Session = None, # type: ignore[assignment]
) -> None:
"""Delete a save, recording the version its slot loses.
Args:
content_hash: What the version held, for a row that never hashed it.
"""
current = self._lock_for_removal(id, session)
if current:
_record_loss(current, session, content_hash)
session.execute(
delete(Save)
.where(Save.id == id)
@@ -392,3 +551,37 @@ class DBSavesHandler(DBBaseHandler):
return session.scalars(
select(Save).where(Save.id > after_id).order_by(asc(Save.id)).limit(limit)
).all()
def _version_query(id: int) -> Select:
return select(*_VERSION_COLUMNS).where(Save.id == id)
def _loses_version(version: Row, data: dict) -> bool:
"""Whether writing `data` takes this version out of its slot."""
return (
data.get("slot", version.slot) != version.slot
or data.get("content_hash", version.content_hash) != version.content_hash
)
def _lock_slot(user_id: int, rom_id: int, slot: str, session: Session) -> None:
"""Ensure the slot has a record, then lock it before any of its rows."""
# One order everywhere, the record before the rows, so removals never deadlock.
_deleted_assets.ensure_record(user_id, rom_id, slot)
_deleted_assets.lock_record(user_id, rom_id, slot, session)
def _record_loss(
version: Row, session: Session, content_hash: str | None = None
) -> None:
"""Remember a version leaving its slot, in the transaction that removes it."""
content_hash = version.content_hash or content_hash
if version.slot and content_hash:
_deleted_assets.record_deletion(
version.user_id,
version.rom_id,
version.slot,
content_hash,
session=session,
)

View File

@@ -1,8 +1,8 @@
from __future__ import annotations
from collections.abc import Collection
from collections.abc import Iterable, Mapping
from datetime import datetime
from typing import Literal, NamedTuple
from typing import Literal, NamedTuple, Protocol
from utils.datetime import to_utc
@@ -21,9 +21,13 @@ def compare_save_state(
server_hash: str | None,
server_updated_at: datetime,
device_last_synced_at: datetime | None,
removed_at: Mapping[str, datetime] | None = None,
) -> SyncComparisonResult:
"""Compare client and server save state to determine the sync action.
`removed_at` maps versions the server's slot lost to when they were lost, so
a client still holding one from before then is behind the server.
Returns a (action, reason) tuple where action is one of:
- upload: client save should be uploaded to server
- download: server save should be downloaded to client
@@ -37,6 +41,11 @@ def compare_save_state(
if client_hash and server_hash and client_hash == server_hash:
return SyncComparisonResult("no_op", "Content is identical")
if _held_since_removal(client_hash, client_ts, removed_at):
return SyncComparisonResult(
"download", "Client holds a version removed on the server"
)
# If we have a last sync timestamp, use it to determine which side changed
if device_last_synced_at:
synced_ts = to_utc(device_last_synced_at)
@@ -75,17 +84,59 @@ def compare_save_state(
def compare_missing_server_save(
client_hash: str | None, deleted_hashes: Collection[str]
client_hash: str | None,
client_updated_at: datetime,
removed_at: Mapping[str, datetime],
) -> SyncComparisonResult:
"""Decide a client save whose slot has no server save, matched by identity.
Args:
client_hash: The digest the client reported, when it reported one.
deleted_hashes: What the slot is known to have lost.
client_updated_at: When the client last wrote its copy.
removed_at: What the slot is known to have lost, and when.
Returns:
`delete` when the client holds a version the slot lost, else `upload`.
`delete` when the client holds a version the slot lost since the client
wrote it, else `upload`.
"""
if client_hash in deleted_hashes:
if _held_since_removal(client_hash, to_utc(client_updated_at), removed_at):
return SyncComparisonResult("delete", "Save was deleted on the server")
return SyncComparisonResult("upload", "Save exists on client but not on server")
def _held_since_removal(
client_hash: str | None,
client_ts: datetime,
removed_at: Mapping[str, datetime] | None,
) -> bool:
"""Whether the client's copy is a removed version it wrote before the removal."""
# Written after the removal, the same bytes are progress made on the device.
removed = (removed_at or {}).get(client_hash) if client_hash else None
return removed is not None and client_ts <= to_utc(removed)
class _SlotVersion(Protocol):
@property
def rom_id(self) -> int: ...
@property
def slot(self) -> str | None: ...
@property
def content_hash(self) -> str | None: ...
def roms_to_check_for_removals(
client_saves: Iterable[_SlotVersion],
current: Mapping[tuple[int, str | None], _SlotVersion],
) -> set[int]:
"""ROMs whose slotted client saves differ from the current version, so may hold a lost one."""
return {
save.rom_id
for save in client_saves
if save.slot
and (
(version := current.get((save.rom_id, save.slot))) is None
or version.content_hash != save.content_hash
)
}

View File

@@ -23,6 +23,7 @@ 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
@@ -446,6 +447,7 @@ 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
)
@@ -456,6 +458,7 @@ 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)

View File

@@ -14,7 +14,7 @@ from models.base import (
BaseModel,
compute_file_name_parts,
)
from utils.database import CustomJSON
from utils.database import CustomJSON, ExactString
if TYPE_CHECKING:
from models.device_save_sync import DeviceSaveSync
@@ -24,6 +24,8 @@ if TYPE_CHECKING:
SAVE_SLOT_MAX_LENGTH = 255
# A slot's versions, newest last: pruning locks exactly these rows through it.
SAVE_SLOT_VERSIONS_INDEX = "ix_saves_rom_user_slot_updated"
EMULATOR_MAX_LENGTH = 50
ASSET_LABEL_MAX_LENGTH = 255
ASSET_LABELS_MAX = 20
@@ -104,12 +106,14 @@ class Save(RomAsset):
__table_args__ = (
Index("ix_saves_rom_user_hash", "rom_id", "user_id", "content_hash"),
Index("idx_saves_public", "is_public"),
Index(SAVE_SLOT_VERSIONS_INDEX, "rom_id", "user_id", "slot", "updated_at"),
{"extend_existing": True},
)
emulator: Mapped[str | None] = mapped_column(String(length=EMULATOR_MAX_LENGTH))
# Exact, so the database pairs slots as sync negotiation does in Python.
slot: Mapped[str | None] = mapped_column(
String(length=SAVE_SLOT_MAX_LENGTH), index=True
ExactString(SAVE_SLOT_MAX_LENGTH), index=True
)
content_hash: Mapped[str | None] = mapped_column(String(length=32))
origin_device_id: Mapped[str | None] = mapped_column(

View File

@@ -1,23 +1,26 @@
from __future__ import annotations
from sqlalchemy import ForeignKey, Index, String
from datetime import datetime
from sqlalchemy import ForeignKey, Index
from sqlalchemy.orm import Mapped, mapped_column
from models.assets import SAVE_SLOT_MAX_LENGTH
from models.base import BaseModel
from utils.database import CustomJSON
from utils.database import CustomJSON, ExactString
from utils.datetime import to_utc
# Trimming drops the oldest, which a long-offline device is likeliest to hold;
# past the bound that device is answered `upload` rather than `delete`.
# past the bound that device's version is negotiated as if it were new.
MAX_REMEMBERED_HASHES = 100
class DeletedAsset(BaseModel):
"""A slot emptied by its owner, so a device still holding it can be told."""
"""The versions a slot lost, so a device still holding one can be told."""
__tablename__ = "deleted_assets"
__table_args__ = (
# One row per slot, however often it is emptied and refilled.
# One row per slot, however many versions it loses.
Index(
"ix_deleted_assets_user_rom_slot", "user_id", "rom_id", "slot", unique=True
),
@@ -29,7 +32,23 @@ class DeletedAsset(BaseModel):
rom_id: Mapped[int] = mapped_column(
ForeignKey("roms.id", ondelete="CASCADE"), index=True
)
slot: Mapped[str] = mapped_column(String(length=SAVE_SLOT_MAX_LENGTH))
# Every version the slot lost, matched by identity rather than by time:
# a device's clock is not the server's.
# Exact, like `Save.slot`, so the unique index keys what negotiation looks up.
slot: Mapped[str] = mapped_column(ExactString(SAVE_SLOT_MAX_LENGTH))
# Every version the slot lost, oldest first, matched by what a device reports holding.
content_hashes: Mapped[list[str]] = mapped_column(CustomJSON(), default=list)
# When each was lost, by the server's clock: a device copy written later is new progress.
removed_at: Mapped[dict[str, str] | None] = mapped_column(
CustomJSON(), nullable=True, default=dict
)
def removal_times(self) -> dict[str, datetime]:
"""When each remembered version was lost, the record's own time where unstamped."""
stamped = self.removed_at or {}
return {
content_hash: (
to_utc(datetime.fromisoformat(stamped[content_hash]))
if content_hash in stamped
else to_utc(self.updated_at)
)
for content_hash in self.content_hashes
}

View File

@@ -20,7 +20,9 @@ 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,
db_device_save_sync_handler,
db_platform_handler,
@@ -249,6 +251,9 @@ 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
),
)
if result.action == "no_op":
@@ -263,6 +268,7 @@ def _process_incoming_file(
)
with open(full_path, "rb") as f:
file_data = f.read()
replaced_hash = asyncio.run(unrecorded_hash(matched_save))
asyncio.run(
fs_asset_handler.write_file(
file=file_data,
@@ -276,6 +282,7 @@ def _process_incoming_file(
"file_size_bytes": file_size,
"content_hash": file_hash,
},
replaced_hash=replaced_hash,
)
db_device_save_sync_handler.upsert_sync(
device_id=device.id,

View File

@@ -111,7 +111,13 @@ class RecomputeSaveContentHashesTask(Task):
continue
try:
db_save_handler.update_save(save.id, {"content_hash": new_hash})
if not db_save_handler.rehash_save(
save.id, new_hash, replacing=save.content_hash
):
# Rewritten while hashed, so the row's own hash stands.
stats.saves_unchanged += 1
self._maybe_flush(stats)
continue
stats.saves_updated += 1
log.debug(
f"Rewrote content_hash for save {save.id} "

View File

@@ -12,7 +12,9 @@ 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,
db_device_save_sync_handler,
db_platform_handler,
@@ -266,6 +268,9 @@ 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
),
)
if result.action == "no_op":
@@ -284,6 +289,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)
await fs_asset_handler.write_file(
file=file_data,
path=matched_save.file_path,
@@ -295,6 +301,7 @@ async def _process_remote_save(
"file_size_bytes": remote_save.file_size,
"content_hash": remote_hash,
},
replaced_hash=replaced_hash,
)
db_device_save_sync_handler.upsert_sync(
device_id=device.id,

View File

@@ -27,11 +27,11 @@ def test_delete_saves(client, access_token, save):
assert len(body) == 1
# No hash and no file to take one from, so nothing a device could match.
assert (
db_deleted_asset_handler.get_deletions(
assert not any(
record.content_hashes
for record in db_deleted_asset_handler.get_deletions(
user_id=save.user_id, rom_ids=[save.rom_id]
)
== []
)

View File

@@ -7,11 +7,13 @@ from unittest import mock
import pytest
from fastapi import status
from sqlalchemy import update
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_deleted_asset_handler,
db_device_handler,
db_device_save_sync_handler,
db_save_handler,
@@ -1869,6 +1871,115 @@ class TestAutocleanup:
assert response.status_code == status.HTTP_200_OK
assert mock_remove.call_count == 6
@mock.patch(
"endpoints.saves.fs_asset_handler.compute_content_hash",
new_callable=mock.AsyncMock,
)
@mock.patch(
"endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock
)
@mock.patch(
"endpoints.saves.fs_asset_handler.remove_file", new_callable=mock.AsyncMock
)
@mock.patch("endpoints.saves.scan_save", new_callable=mock.AsyncMock)
def test_autocleanup_records_versions_never_hashed(
self,
mock_scan,
mock_remove,
mock_write,
mock_hash,
client,
access_token: str,
rom: Rom,
platform: Platform,
admin_user: User,
slot_saves: list[Save],
):
mock_hash.side_effect = lambda path: f"hash of {path.rsplit('/', 1)[-1]}"
mock_scan.return_value = _slot_save(
admin_user, rom, platform, "new_autosave", "autosave"
)
response = client.post(
f"/api/saves?rom_id={rom.id}&slot=autosave&autocleanup=true&autocleanup_limit=10",
files={
"saveFile": (
"new_autosave.sav",
BytesIO(b"new"),
"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]
)
# The six oldest of the fifteen seeded versions, oldest first.
assert record.content_hashes == [
f"hash of autosave_{index}.sav" for index in range(6)
]
@mock.patch(
"endpoints.saves.fs_asset_handler.compute_content_hash",
new_callable=mock.AsyncMock,
)
@mock.patch(
"endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock
)
@mock.patch(
"endpoints.saves.fs_asset_handler.remove_file", new_callable=mock.AsyncMock
)
@mock.patch("endpoints.saves.scan_save", new_callable=mock.AsyncMock)
def test_autocleanup_records_versions_pushed_past_the_limit_while_hashing(
self,
mock_scan,
mock_remove,
mock_write,
mock_hash,
client,
access_token: str,
rom: Rom,
platform: Platform,
admin_user: User,
slot_saves: list[Save],
):
raced: list[Save] = []
def hash_while_another_upload_lands(path: str) -> str:
if not raced:
upload = _slot_save(admin_user, rom, platform, "raced", "autosave")
upload.content_hash = "raced"
raced.append(db_save_handler.add_save(upload))
return f"hash of {path.rsplit('/', 1)[-1]}"
mock_hash.side_effect = hash_while_another_upload_lands
mock_scan.return_value = _slot_save(
admin_user, rom, platform, "new_autosave", "autosave"
)
response = client.post(
f"/api/saves?rom_id={rom.id}&slot=autosave&autocleanup=true&autocleanup_limit=10",
files={
"saveFile": (
"new_autosave.sav",
BytesIO(b"new"),
"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]
)
# The race pushed a seventh version past the limit.
assert record.content_hashes == [
f"hash of autosave_{index}.sav" for index in range(7)
]
@mock.patch(
"endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock
)
@@ -3502,6 +3613,45 @@ class TestSlotScopedDedupeMatrix:
assert len(rows) == 1
assert rows[0]["content_hash"] == FIXTURE_B_HASH
def test_overwriting_a_colliding_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.post(
f"/api/saves?rom_id={rom.id}&emulator=test_emulator",
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,

View File

@@ -107,6 +107,39 @@ class TestSyncNegotiate:
assert data[f"total_{expected_action}"] == 1
assert data["operations"][0]["action"] == expected_action
def test_negotiate_a_deleted_slot_matches_its_exact_name(
self, client, access_token: str, admin_user: User, rom: Rom
):
"""Slots differing only in case keep their own deletion records."""
device = db_device_handler.add_device(
Device(id="neg-dev-deleted-case", user_id=admin_user.id, sync_enabled=True)
)
for slot, content_hash in (("Autosave", "upper"), ("autosave", "lower")):
db_deleted_asset_handler.record_deletion(
user_id=admin_user.id,
rom_id=rom.id,
slot=slot,
content_hash=content_hash,
)
data = _negotiate(
client,
access_token,
device.id,
[
{
"rom_id": rom.id,
"file_name": "test_save.sav",
"slot": "autosave",
"content_hash": "lower",
"updated_at": "2026-01-09T00:00:00Z",
"file_size_bytes": 1024,
}
],
)
assert data["operations"][0]["action"] == "delete"
def test_negotiate_server_has_save_client_doesnt(
self, client, access_token: str, admin_user: User, save: Save
):
@@ -710,6 +743,161 @@ def _negotiate(client, access_token, device_id, saves):
return resp.json()
def _slot_version(
user: User, rom: Rom, stem: str, content_hash: str, updated_at: datetime
) -> Save:
save = db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=user.id,
file_name=f"{stem}.sav",
file_name_no_tags=stem,
file_name_no_ext=stem,
file_extension="sav",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="autosave",
content_hash=content_hash,
)
)
return db_save_handler.update_save(save.id, {"updated_at": updated_at})
class TestNegotiateRemovedVersions:
"""A version that left its slot on the server is never offered back."""
BASE = datetime(2026, 1, 1, tzinfo=timezone.utc)
@staticmethod
def _held(
rom: Rom, content_hash: str, updated_at: str = "2026-02-01T00:00:00Z"
) -> dict:
return {
"rom_id": rom.id,
"file_name": "autosave.sav",
"slot": "autosave",
"content_hash": content_hash,
"updated_at": updated_at,
"file_size_bytes": 100,
}
def _delete(self, client, access_token: str, save: Save) -> None:
response = client.post(
"/api/saves/delete",
json={"saves": [save.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
def test_a_rolled_back_version_is_replaced_by_the_current_one(
self, client, access_token: str, admin_user: User, rom: Rom
):
device = db_device_handler.add_device(
Device(id="removed-rollback", user_id=admin_user.id, sync_enabled=True)
)
older = _slot_version(admin_user, rom, "older", "HASH_A", self.BASE)
newest = _slot_version(
admin_user, rom, "newest", "HASH_B", self.BASE + timedelta(hours=1)
)
db_device_save_sync_handler.upsert_sync(
device_id=device.id, save_id=newest.id, synced_at=newest.updated_at
)
self._delete(client, access_token, newest)
data = _negotiate(client, access_token, device.id, [self._held(rom, "HASH_B")])
[op] = data["operations"]
assert op["action"] == "download"
assert op["save_id"] == older.id
def test_a_pruned_version_is_deleted_once_the_slot_is(
self, client, access_token: str, admin_user: User, rom: Rom
):
device = db_device_handler.add_device(
Device(id="removed-pruned", user_id=admin_user.id, sync_enabled=True)
)
_slot_version(admin_user, rom, "v1", "HASH_V1", self.BASE)
current = _slot_version(
admin_user, rom, "v2", "HASH_V2", self.BASE + timedelta(hours=1)
)
db_save_handler.prune_slot(
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=1
)
self._delete(client, access_token, current)
data = _negotiate(client, access_token, device.id, [self._held(rom, "HASH_V1")])
assert data["operations"][0]["action"] == "delete"
def test_an_overwritten_version_is_deleted_once_the_slot_is(
self, client, access_token: str, admin_user: User, rom: Rom
):
device = db_device_handler.add_device(
Device(id="removed-overwritten", user_id=admin_user.id, sync_enabled=True)
)
save = _slot_version(admin_user, rom, "v1", "HASH_V1", self.BASE)
save = db_save_handler.update_save(save.id, {"content_hash": "HASH_V2"})
self._delete(client, access_token, save)
data = _negotiate(client, access_token, device.id, [self._held(rom, "HASH_V1")])
assert data["operations"][0]["action"] == "delete"
def test_a_copy_written_after_the_removal_is_offered_as_new(
self, client, access_token: str, admin_user: User, rom: Rom
):
device = db_device_handler.add_device(
Device(id="removed-rewritten", user_id=admin_user.id, sync_enabled=True)
)
db_deleted_asset_handler.record_deletion(
user_id=admin_user.id, rom_id=rom.id, slot="autosave", content_hash="SAME"
)
later = (datetime.now(timezone.utc) + timedelta(days=1)).isoformat()
data = _negotiate(
client, access_token, device.id, [self._held(rom, "SAME", later)]
)
assert data["operations"][0]["action"] == "upload"
def test_a_copy_written_after_a_rollback_is_not_replaced(
self, client, access_token: str, admin_user: User, rom: Rom
):
device = db_device_handler.add_device(
Device(id="removed-progress", user_id=admin_user.id, sync_enabled=True)
)
_slot_version(admin_user, rom, "older", "HASH_A", self.BASE)
newest = _slot_version(
admin_user, rom, "newest", "HASH_B", self.BASE + timedelta(hours=1)
)
self._delete(client, access_token, newest)
later = (datetime.now(timezone.utc) + timedelta(days=1)).isoformat()
data = _negotiate(
client, access_token, device.id, [self._held(rom, "HASH_B", later)]
)
assert data["operations"][0]["action"] == "upload"
def test_the_current_version_matches_even_after_it_was_once_removed(
self, client, access_token: str, admin_user: User, rom: Rom
):
device = db_device_handler.add_device(
Device(id="removed-refilled", user_id=admin_user.id, sync_enabled=True)
)
db_deleted_asset_handler.record_deletion(
user_id=admin_user.id,
rom_id=rom.id,
slot="autosave",
content_hash="HASH_A",
)
_slot_version(admin_user, rom, "again", "HASH_A", self.BASE)
data = _negotiate(client, access_token, device.id, [self._held(rom, "HASH_A")])
assert data["operations"][0]["action"] == "no_op"
class TestNegotiateAdvanced:
def test_negotiate_untracked_save_returns_noop(
self, client, access_token: str, admin_user: User, save: Save

View File

@@ -8,6 +8,7 @@ from fastapi.testclient import TestClient
from redis.exceptions import RedisError
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
db_rom_handler,
db_save_handler,
@@ -725,6 +726,50 @@ class TestRetroArchSyncUpload:
assert len(saves) == 1
assert saves[0].file_size_bytes == 7
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.compute_content_hash",
new_callable=mock.AsyncMock,
return_value="hash_of_old_file",
)
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.write_file",
new_callable=mock.AsyncMock,
)
@mock.patch("endpoints.sync.retroarch.scan_save", new_callable=mock.AsyncMock)
def test_overwriting_a_slotted_save_never_hashed_records_its_file_hash(
self,
mock_scan_save: mock.AsyncMock,
_mock_write_file: mock.AsyncMock,
_mock_hash: mock.AsyncMock,
client,
admin_user: User,
rom: Rom,
saves_path: str,
synced_save: Save,
):
db_save_handler.update_save(synced_save.id, {"slot": "autosave"})
mock_scan_save.return_value = Save(
file_name=synced_save.file_name,
file_path=synced_save.file_path,
file_size_bytes=7,
content_hash="9a0364b9e99bb480dd25e1f0284c8555",
)
response = client.put(
"/api/sync/retroarch/saves/Snes9x/test_rom.srm",
content=b"newdata",
auth=ADMIN_AUTH,
)
assert response.status_code == status.HTTP_204_NO_CONTENT
[record] = db_deleted_asset_handler.get_deletions(
user_id=admin_user.id, rom_ids=[rom.id]
)
assert (record.slot, record.content_hashes) == (
"autosave",
["hash_of_old_file"],
)
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.write_file",
new_callable=mock.AsyncMock,
@@ -936,6 +981,38 @@ class TestRetroArchSyncDelete:
mock_remove_file.assert_awaited_once()
assert db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[rom.id]) == []
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.compute_content_hash",
new_callable=mock.AsyncMock,
return_value="hash_of_file",
)
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.remove_file",
new_callable=mock.AsyncMock,
)
def test_deleting_a_slotted_save_never_hashed_records_its_file_hash(
self,
_mock_remove_file: mock.AsyncMock,
_mock_hash: mock.AsyncMock,
client,
admin_user: User,
rom: Rom,
synced_save: Save,
):
db_save_handler.update_save(synced_save.id, {"slot": "autosave"})
response = client.request(
"DELETE",
"/api/sync/retroarch/saves/Snes9x/test_rom.srm",
auth=ADMIN_AUTH,
)
assert response.status_code == status.HTTP_204_NO_CONTENT
[record] = db_deleted_asset_handler.get_deletions(
user_id=admin_user.id, rom_ids=[rom.id]
)
assert (record.slot, record.content_hashes) == ("autosave", ["hash_of_file"])
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.remove_file",
new_callable=mock.AsyncMock,

View File

@@ -1,7 +1,10 @@
from datetime import datetime, timezone
from handler.database import db_deleted_asset_handler
from models.deleted_asset import MAX_REMEMBERED_HASHES, DeletedAsset
from models.rom import Rom
from models.user import User
from utils.datetime import to_utc
def _record(user: User, rom: Rom, slot: str, content_hash: str) -> DeletedAsset:
@@ -40,6 +43,73 @@ class TestRecordDeletion:
}
assert slots == {"autosave", "main_quest"}
def test_a_slot_differing_only_in_case_is_its_own_record(
self, rom: Rom, admin_user: User
):
for slot in ("Autosave", "autosave"):
_record(admin_user, rom, slot, slot)
records = {
record.slot: record.content_hashes
for record in db_deleted_asset_handler.get_deletions(
user_id=admin_user.id, rom_ids=[rom.id]
)
}
assert records == {"Autosave": ["Autosave"], "autosave": ["autosave"]}
def test_ensuring_a_record_twice_keeps_one_empty_row(
self, rom: Rom, admin_user: User
):
for _ in range(2):
db_deleted_asset_handler.ensure_record(admin_user.id, rom.id, "autosave")
[record] = db_deleted_asset_handler.get_deletions(
user_id=admin_user.id, rom_ids=[rom.id]
)
assert record.content_hashes == []
class TestRemovalTimes:
def test_each_version_is_stamped_when_it_was_lost(self, rom: Rom, admin_user: User):
before = datetime.now(timezone.utc)
_record(admin_user, rom, "autosave", "lost")
times = db_deleted_asset_handler.removal_times(
admin_user.id, rom.id, "autosave"
)
assert list(times) == ["lost"]
assert before <= times["lost"] <= datetime.now(timezone.utc)
def test_a_version_lost_again_is_stamped_again(self, rom: Rom, admin_user: User):
first = _record(admin_user, rom, "autosave", "again").removal_times()["again"]
_record(admin_user, rom, "autosave", "other")
again = _record(admin_user, rom, "autosave", "again").removal_times()["again"]
assert again >= first
def test_an_unstamped_version_falls_back_to_the_records_time(
self, rom: Rom, admin_user: User
):
record = _record(admin_user, rom, "autosave", "stamped")
record.removed_at = {}
record.content_hashes = ["legacy", "stamped"]
assert record.removal_times() == {
"legacy": to_utc(record.updated_at),
"stamped": to_utc(record.updated_at),
}
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}")
assert set(record.removed_at or {}) == set(record.content_hashes)
assert "v0" not in (record.removed_at or {})
def test_a_slot_that_lost_nothing_has_no_times(self, rom: Rom, admin_user: User):
assert db_deleted_asset_handler.removal_times(admin_user.id, rom.id, "x") == {}
class TestGetDeletions:
def test_an_empty_scope_asks_about_nothing(self, rom: Rom, admin_user: User):

View File

@@ -5,7 +5,22 @@ This module tests the platform filtering fixes for DBSavesHandler to ensure
it properly filters by platform_id through the Rom relationship.
"""
from handler.database import db_save_handler
import ast
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest import mock
import pytest
from sqlalchemy import Delete, event
from sqlalchemy.exc import NoResultFound
import handler.database.saves_handler as saves_handler_module
from handler.database import db_deleted_asset_handler, db_save_handler
from handler.database.base_handler import sync_engine
from models.assets import Save
from models.platform import Platform
from models.rom import Rom
@@ -296,6 +311,42 @@ class TestDBSavesHandlerSlotFiltering:
assert len(slot_b_saves) == 1
assert slot_b_saves[0].slot == "Slot B"
@pytest.mark.parametrize(
"slot,sibling",
[("autosave", "Autosave"), ("Cafe", "Café"), ("autosave", "autosave ")],
ids=["case", "accent", "trailing-space"],
)
def test_a_slot_is_matched_exactly(
self, admin_user: User, rom: Rom, slot: str, sibling: str
):
"""Sync pairs slots in Python, so the database must not fold them."""
for index, name in enumerate((slot, sibling)):
db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name=f"exact_{index}.sav",
file_name_no_tags=f"exact_{index}",
file_name_no_ext=f"exact_{index}",
file_extension="sav",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot=name,
content_hash=f"exact_{index}",
)
)
[found] = db_save_handler.get_saves(
user_id=admin_user.id, rom_ids=[rom.id], slot=slot
)
assert found.slot == slot
db_save_handler.prune_slot(
user_id=admin_user.id, rom_id=rom.id, slot=slot, keep=0
)
[kept] = db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[rom.id])
assert kept.slot == sibling
def test_get_saves_with_null_slot_filter(self, admin_user: User, rom: Rom):
save_with_slot = Save(
rom_id=rom.id,
@@ -943,3 +994,360 @@ class TestGetSavesRomIdsScope:
)
assert [s.id for s in saves] == [save.id]
class TestDBSavesHandlerRecordsLostVersions:
"""Every way a version leaves its slot is remembered for sync."""
@staticmethod
def _add(
user: User, rom: Rom, stem: str, slot: str | None, content_hash: str | None
) -> Save:
return db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=user.id,
file_name=f"{stem}.sav",
file_name_no_tags=stem,
file_name_no_ext=stem,
file_extension="sav",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot=slot,
content_hash=content_hash,
)
)
@staticmethod
def _lost(user: User, rom: Rom) -> dict[str, list[str]]:
return {
record.slot: record.content_hashes
for record in db_deleted_asset_handler.get_deletions(
user_id=user.id, rom_ids=[rom.id]
)
}
def test_a_deleted_version_is_recorded(self, admin_user: User, rom: Rom):
save = self._add(admin_user, rom, "deleted", "autosave", "gone")
db_save_handler.delete_save(save.id)
assert self._lost(admin_user, rom) == {"autosave": ["gone"]}
def test_a_deleted_version_never_hashed_takes_the_callers_hash(
self, admin_user: User, rom: Rom
):
save = self._add(admin_user, rom, "unhashed", "autosave", None)
db_save_handler.delete_save(save.id, content_hash="from_file")
assert self._lost(admin_user, rom) == {"autosave": ["from_file"]}
def test_a_save_outside_any_slot_is_not_recorded(self, admin_user: User, rom: Rom):
save = self._add(admin_user, rom, "archival", None, "archived")
db_save_handler.delete_save(save.id)
assert self._lost(admin_user, rom) == {}
def test_pruned_versions_are_recorded(self, admin_user: User, rom: Rom):
for index in range(3):
save = self._add(admin_user, rom, f"v{index}", "autosave", f"v{index}")
db_save_handler.update_save(
save.id, {"updated_at": datetime(2026, 1, 1 + index, tzinfo=UTC)}
)
db_save_handler.prune_slot(
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=1
)
assert self._lost(admin_user, rom) == {"autosave": ["v0", "v1"]}
def test_a_prune_hands_back_versions_it_has_no_hash_for(
self, admin_user: User, rom: Rom
):
for index, content_hash in enumerate([None, "hashed", None]):
save = self._add(admin_user, rom, f"v{index}", "autosave", content_hash)
db_save_handler.update_save(
save.id, {"updated_at": datetime(2026, 1, 1 + index, tzinfo=UTC)}
)
with pytest.raises(saves_handler_module.UnhashedVersions) as raised:
db_save_handler.prune_slot(
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=1
)
[unhashed] = raised.value.versions
assert unhashed.file_name == "v0.sav"
assert len(db_save_handler.get_saves(user_id=admin_user.id)) == 3
db_save_handler.prune_slot(
user_id=admin_user.id,
rom_id=rom.id,
slot="autosave",
keep=1,
fallback_hashes={unhashed.id: "from_file"},
)
assert self._lost(admin_user, rom) == {"autosave": ["from_file", "hashed"]}
def test_an_overwritten_version_never_hashed_takes_the_callers_hash(
self, admin_user: User, rom: Rom
):
save = self._add(admin_user, rom, "unhashed", "autosave", None)
db_save_handler.update_save(
save.id, {"content_hash": "new"}, replaced_hash="from_file"
)
assert self._lost(admin_user, rom) == {"autosave": ["from_file"]}
def test_a_version_overwritten_since_it_was_read_is_recorded(
self, admin_user: User, rom: Rom
):
"""Two overwrites racing: the second replaces what the first wrote."""
save = self._add(admin_user, rom, "raced", "autosave", "v0")
stale = db_save_handler._slot_version(save.id)
db_save_handler.update_save(save.id, {"content_hash": "v1"})
with mock.patch.object(db_save_handler, "_slot_version", return_value=stale):
db_save_handler.update_save(save.id, {"content_hash": "v2"})
assert self._lost(admin_user, rom) == {"autosave": ["v0", "v1"]}
def test_a_version_moved_since_it_was_read_is_retried_in_its_new_slot(
self, admin_user: User, rom: Rom
):
save = self._add(admin_user, rom, "moved", "autosave", "v0")
moved_from = SimpleNamespace(
user_id=admin_user.id, rom_id=rom.id, slot="manual", content_hash="v0"
)
pre_reads = iter([moved_from])
read_current = db_save_handler._slot_version
with mock.patch.object(
db_save_handler,
"_slot_version",
side_effect=lambda id: next(pre_reads, None) or read_current(id),
) as pre_read:
db_save_handler.update_save(save.id, {"content_hash": "v1"})
assert pre_read.call_count == 2
current = db_save_handler.get_save(admin_user.id, save.id)
assert current is not None
assert current.content_hash == "v1"
assert self._lost(admin_user, rom)["autosave"] == ["v0"]
def test_a_version_that_keeps_moving_gives_up(self, admin_user: User, rom: Rom):
save = self._add(admin_user, rom, "moving", "autosave", "v0")
moved_from = SimpleNamespace(
user_id=admin_user.id, rom_id=rom.id, slot="manual", content_hash="v0"
)
with (
mock.patch.object(
db_save_handler, "_slot_version", return_value=moved_from
),
pytest.raises(saves_handler_module._SlotMoved),
):
db_save_handler.delete_save(save.id)
current = db_save_handler.get_save(admin_user.id, save.id)
assert current is not None
assert current.content_hash == "v0"
def test_a_prune_that_fails_records_nothing(self, admin_user: User, rom: Rom):
"""The record commits with the removal, so no negotiation sees one alone."""
self._add(admin_user, rom, "kept", "autosave", "kept")
# Raised before a cursor exists: failing inside one leaves the MariaDB
# driver's pooled connection unusable, and the next checkout crashes.
def fail_the_delete(_conn: Any, statement: Any, *_: Any) -> None:
if isinstance(statement, Delete) and statement.table.description == "saves":
raise RuntimeError("delete failed")
event.listen(sync_engine, "before_execute", fail_the_delete)
try:
with pytest.raises(RuntimeError):
db_save_handler.prune_slot(
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=0
)
finally:
event.remove(sync_engine, "before_execute", fail_the_delete)
assert self._lost(admin_user, rom) == {"autosave": []}
assert db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[rom.id])
def test_a_loss_the_first_read_missed_is_still_recorded(
self, admin_user: User, rom: Rom
):
save = self._add(admin_user, rom, "missed", "autosave", "old")
looks_unchanged = SimpleNamespace(
user_id=admin_user.id, rom_id=rom.id, slot="autosave", content_hash="new"
)
with mock.patch.object(
db_save_handler, "_slot_version", return_value=looks_unchanged
):
db_save_handler.update_save(save.id, {"content_hash": "new"})
assert self._lost(admin_user, rom) == {"autosave": ["old"]}
def test_concurrent_removals_record_every_lost_version(
self, admin_user: User, rom: Rom
):
"""One lock order, the slot's record before its rows, so none deadlock."""
# Five slots against four kinds of write, so every pair races on a slot.
saves = [
self._add(admin_user, rom, f"c{index}", f"slot{index % 5}", f"c{index}")
for index in range(120)
]
def remove(index: int) -> None:
save = saves[index]
try:
if index % 4 == 0:
db_save_handler.delete_save(save.id)
elif index % 4 == 1:
db_save_handler.update_save(save.id, {"content_hash": f"n{index}"})
elif index % 4 == 2:
db_save_handler.prune_slot(
user_id=admin_user.id,
rom_id=rom.id,
slot=f"slot{index % 5}",
keep=3,
)
else:
# Writes a row a prune may be deleting, without the slot's lock.
db_save_handler.update_save(
save.id, {"is_favorite": True}, touch=False
)
except NoResultFound:
pass # A prune removed the row first.
with ThreadPoolExecutor(max_workers=12) as pool:
list(pool.map(remove, range(120)))
remaining = {
save.content_hash
for save in db_save_handler.get_saves(
user_id=admin_user.id, rom_ids=[rom.id]
)
}
lost = {h for hashes in self._lost(admin_user, rom).values() for h in hashes}
assert {save.content_hash for save in saves} - remaining <= lost
@pytest.mark.parametrize("path", ["delete", "prune", "overwrite"])
def test_recording_never_checks_out_a_second_connection(
self, admin_user: User, rom: Rom, path: str
):
"""A second checkout per removal would starve the pool under load."""
save = self._add(admin_user, rom, "pooled", "autosave", "pooled")
checked_out: dict[str, int] = {}
deleted_assets = saves_handler_module._deleted_assets
ensure, record = deleted_assets.ensure_record, deleted_assets.record_deletions
def spy(name: str, wrapped: Callable[..., Any]) -> Callable[..., Any]:
def call(*args: Any, **kwargs: Any) -> Any:
checked_out[name] = sync_engine.pool.checkedout() # type: ignore[attr-defined]
return wrapped(*args, **kwargs)
return call
with (
mock.patch.object(deleted_assets, "ensure_record", spy("ensure", ensure)),
mock.patch.object(
deleted_assets, "record_deletions", spy("record", record)
),
):
if path == "delete":
db_save_handler.delete_save(save.id)
elif path == "prune":
db_save_handler.prune_slot(
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=0
)
else:
db_save_handler.update_save(save.id, {"content_hash": "new"})
# Ensuring runs before the removal holds one; recording joins it.
assert checked_out == {"ensure": 0, "record": 1}
def test_an_overwritten_version_is_recorded(self, admin_user: User, rom: Rom):
save = self._add(admin_user, rom, "overwritten", "autosave", "before")
db_save_handler.update_save(save.id, {"content_hash": "after"})
assert self._lost(admin_user, rom) == {"autosave": ["before"]}
def test_a_version_moved_to_another_slot_is_recorded_in_the_first(
self, admin_user: User, rom: Rom
):
save = self._add(admin_user, rom, "moved", "autosave", "moved")
db_save_handler.update_save(save.id, {"slot": "main_quest"})
assert self._lost(admin_user, rom) == {"autosave": ["moved"]}
def test_a_recomputed_hash_of_the_same_bytes_records_nothing(
self, admin_user: User, rom: Rom
):
save = self._add(admin_user, rom, "rehashed", "autosave", "raw_md5")
assert db_save_handler.rehash_save(save.id, "entries_md5", replacing="raw_md5")
assert self._lost(admin_user, rom) == {}
def test_a_recomputed_hash_never_replaces_a_newer_one(
self, admin_user: User, rom: Rom
):
save = self._add(admin_user, rom, "rewritten", "autosave", "newer")
assert not db_save_handler.rehash_save(
save.id, "entries_md5", replacing="read_before"
)
[kept] = db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[rom.id])
assert kept.content_hash == "newer"
@pytest.mark.parametrize(
"data",
[{"content_hash": "same"}, {"is_favorite": True}],
ids=["same-bytes", "annotation"],
)
def test_an_update_that_keeps_the_version_records_nothing(
self, admin_user: User, rom: Rom, data: dict
):
save = self._add(admin_user, rom, "kept", "autosave", "same")
db_save_handler.update_save(save.id, data)
assert not any(self._lost(admin_user, rom).values())
BACKEND_ROOT = Path(__file__).parents[3]
SAVES_HANDLER = BACKEND_ROOT / "handler" / "database" / "saves_handler.py"
def _writes_save_rows(node: ast.Call) -> bool:
"""Whether `node` is `delete(Save)`, `update(Save)` or `.query(Save)...delete()`."""
func = node.func
name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
if name not in {"delete", "update"}:
return False
if any(isinstance(arg, ast.Name) and arg.id == "Save" for arg in node.args):
return True
return isinstance(func, ast.Attribute) and "query(Save)" in ast.unparse(func.value)
def test_only_the_saves_handler_writes_save_rows():
"""The handler records every version leaving a slot, so nothing may go around it."""
offenders = []
for path in BACKEND_ROOT.rglob("*.py"):
relative = path.relative_to(BACKEND_ROOT)
if relative.parts[0] in {"tests", "alembic"} or path == SAVES_HANDLER:
continue
tree = ast.parse(path.read_text(), filename=str(path))
offenders += [
f"{relative}:{node.lineno}"
for node in ast.walk(tree)
if isinstance(node, ast.Call) and _writes_save_rows(node)
]
assert offenders == []

View File

@@ -1,11 +1,13 @@
"""Tests for sync comparison algorithm."""
from dataclasses import dataclass
from datetime import datetime, timezone
from handler.sync.comparison import (
SyncComparisonResult,
compare_missing_server_save,
compare_save_state,
roms_to_check_for_removals,
)
@@ -147,18 +149,92 @@ class TestCompareReturnType:
assert isinstance(result.reason, str)
class TestCompareRemovedVersions:
REMOVED = datetime(2026, 1, 2, tzinfo=timezone.utc)
BEFORE = datetime(2026, 1, 1, tzinfo=timezone.utc)
AFTER = datetime(2026, 1, 3, tzinfo=timezone.utc)
def _compare(self, client_hash, client_updated_at, **overrides):
kwargs = {
"client_hash": client_hash,
"client_updated_at": client_updated_at,
"server_hash": "current",
"server_updated_at": self.BEFORE,
"device_last_synced_at": self.BEFORE,
"removed_at": {"removed": self.REMOVED, "current": self.REMOVED},
}
return compare_save_state(**{**kwargs, **overrides})
def test_a_version_written_before_its_removal_downloads(self):
# Its timestamp is newer than the server's current save, which alone
# would answer upload.
assert self._compare("removed", self.REMOVED).action == "download"
def test_the_same_bytes_written_after_the_removal_are_progress(self):
assert self._compare("removed", self.AFTER).action == "upload"
def test_the_current_version_stays_in_sync_even_if_once_removed(self):
assert self._compare("current", self.BEFORE).action == "no_op"
def test_a_client_that_reports_no_digest_compares_by_time(self):
result = self._compare(None, self.AFTER, device_last_synced_at=None)
assert result.action == "upload"
class TestCompareMissingServerSave:
def test_a_version_the_slot_lost_is_deleted(self):
result = compare_missing_server_save("abc123", ["def456", "abc123"])
REMOVED = datetime(2026, 1, 2, tzinfo=timezone.utc)
LOST = {"def456": REMOVED, "abc123": REMOVED}
def test_a_version_written_before_the_slot_lost_it_is_deleted(self):
result = compare_missing_server_save(
"abc123", datetime(2026, 1, 1, tzinfo=timezone.utc), self.LOST
)
assert result.action == "delete"
def test_the_same_bytes_written_after_the_loss_are_uploaded(self):
result = compare_missing_server_save(
"abc123", datetime(2026, 1, 3, tzinfo=timezone.utc), self.LOST
)
assert result.action == "upload"
def test_bytes_nobody_deleted_are_uploaded(self):
# Offering it back costs a deletion that misses that device; deleting
# it would cost the save.
assert compare_missing_server_save("fresh", ["abc123"]).action == "upload"
assert (
compare_missing_server_save("fresh", self.REMOVED, self.LOST).action
== "upload"
)
def test_a_client_that_reports_no_digest_is_uploaded(self):
assert compare_missing_server_save(None, ["abc123"]).action == "upload"
assert (
compare_missing_server_save(None, self.REMOVED, self.LOST).action
== "upload"
)
def test_a_slot_that_lost_nothing_is_uploaded(self):
assert compare_missing_server_save("abc123", ()).action == "upload"
assert (
compare_missing_server_save("abc123", self.REMOVED, {}).action == "upload"
)
@dataclass(frozen=True)
class _Save:
rom_id: int
slot: str | None
content_hash: str | None
class TestRomsToCheckForRemovals:
def test_only_saves_that_differ_from_their_slot_are_checked(self):
current: dict[tuple[int, str | None], _Save] = {
(1, "autosave"): _Save(1, "autosave", "same"),
(2, "autosave"): _Save(2, "autosave", "current"),
}
client_saves = [
_Save(1, "autosave", "same"),
_Save(2, "autosave", "older"),
_Save(3, "autosave", "unknown"),
_Save(4, None, "archival"),
]
assert roms_to_check_for_removals(client_saves, current) == {2, 3}

View File

@@ -360,6 +360,50 @@ class TestRecomputeSaveContentHashesTask:
assert refreshed is not None
assert refreshed.content_hash == original_hash
async def test_a_row_rewritten_while_hashed_keeps_its_own_hash(
self,
task: RecomputeSaveContentHashesTask,
isolated_assets_dir: Path,
admin_user: User,
rom: Rom,
platform: Platform,
mocker,
):
rel_dir = f"{platform.fs_slug}/saves/test_emulator"
file_name = "fixture_a.zip"
_write_fixture_a_zip(isolated_assets_dir / rel_dir / file_name)
save = db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name=file_name,
file_name_no_tags="fixture_a",
file_name_no_ext="fixture_a",
file_extension="zip",
emulator="test_emulator",
slot="autosave",
file_path=rel_dir,
file_size_bytes=1,
content_hash="00000000000000000000000000000000",
)
)
async def upload_lands_mid_hash(_path: str) -> str:
db_save_handler.update_save(save.id, {"content_hash": "uploaded_meanwhile"})
return FIXTURE_A_PINNED_HASH
mocker.patch.object(
fs_asset_handler, "compute_content_hash", side_effect=upload_lands_mid_hash
)
stats = await task.run()
assert stats["saves_updated"] == 0
assert stats["saves_unchanged"] == 1
refreshed = db_save_handler.get_save(user_id=admin_user.id, id=save.id)
assert refreshed is not None
assert refreshed.content_hash == "uploaded_meanwhile"
async def test_update_save_failure_increments_errors(
self,
task: RecomputeSaveContentHashesTask,
@@ -393,7 +437,7 @@ class TestRecomputeSaveContentHashesTask:
mocker.patch.object(
db_save_handler,
"update_save",
"rehash_save",
side_effect=RuntimeError("simulated DB failure"),
)

View File

@@ -5,7 +5,11 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from handler.database import db_device_handler, db_save_handler
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
db_save_handler,
)
from handler.sync.ssh_handler import RemoteSaveInfo
from models.assets import Save
from models.device import Device, SyncMode
@@ -211,6 +215,41 @@ class TestNullSlotLeakInProcessRemoteSave:
assert refreshed is not None
assert refreshed.content_hash == "archival_hash_unique"
async def test_a_version_removed_since_the_device_wrote_it_is_replaced(
self, device: Device, admin_user: User, platform: Platform, save: Save
):
"""Newer than the server's save by its timestamp, yet lost since it was written."""
assert save.slot
db_save_handler.update_save(
save.id, {"updated_at": datetime(2020, 1, 1, tzinfo=timezone.utc)}
)
db_deleted_asset_handler.record_deletion(
admin_user.id, save.rom_id, save.slot, "removed_here"
)
remote_save = RemoteSaveInfo(
path=f"/remote/{platform.fs_slug}/{save.file_name}",
file_name=save.file_name,
platform_slug=platform.fs_slug,
file_size=1,
mtime=datetime(2021, 1, 1, tzinfo=timezone.utc),
)
ssh = MagicMock()
ssh.download_save = AsyncMock(return_value=("/tmp/unused", "removed_here"))
ssh.upload_save = AsyncMock()
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler", return_value=ssh),
patch("tasks.sync_push_pull_task.fs_asset_handler"),
patch("tasks.sync_push_pull_task.AnyioPath") as mock_anyio_path,
):
mock_anyio_path.return_value.exists = AsyncMock(return_value=False)
action = await _process_remote_save(
device, conn=MagicMock(), remote_save=remote_save, session_id=1
)
assert action == "pushed"
ssh.upload_save.assert_awaited_once()
class TestProcessRemoteSaveConflict:
async def test_conflict_names_the_matched_rom(

View File

@@ -27,6 +27,7 @@ from utils.database import (
AUTOGENERATE_EXEMPT_INDEX_NAMES,
POSTGRESQL_FK_INDEXES,
SORTABLE_NULLABLE_ROM_COLUMNS,
exact_collation,
full_path_digest_sql,
has_column,
is_mariadb,
@@ -235,6 +236,7 @@ def _replay(connection: sa.Connection, filename: str) -> None:
("0132_audit_events.py", "audit_events"),
("0135_drop_play_session_sync_link.py", "play_sessions"),
("0136_deleted_assets.py", "deleted_assets"),
("0138_exact_save_slots.py", "saves"),
],
)
def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op(
@@ -270,6 +272,88 @@ def test_the_play_session_sync_link_revision_reverses_and_replays():
assert _schema_of(connection, "play_sessions") == before
def _slot_collations(connection: sa.Connection) -> dict[str, str | None]:
inspector = sa.inspect(connection)
collations = {}
for table in ("saves", "deleted_assets"):
[slot_type] = [
column["type"]
for column in inspector.get_columns(table)
if column["name"] == "slot"
]
assert isinstance(slot_type, sa.String)
collations[table] = slot_type.collation
return collations
def test_save_slots_are_compared_exactly():
"""Both slot columns match as sync negotiation pairs them in Python."""
with sync_engine.connect() as connection:
expected = exact_collation(connection)
assert _slot_collations(connection) == {
"saves": expected,
"deleted_assets": expected,
}
def test_the_exact_save_slots_revision_reverses_and_replays():
migration = _load_migration("0138_exact_save_slots.py")
with sync_engine.begin() as connection:
exact = exact_collation(connection)
with Operations.context(MigrationContext.configure(connection)):
migration.downgrade()
if exact is not None:
assert _slot_collations(connection)["saves"] != exact
migration.downgrade()
migration.upgrade()
migration.upgrade()
assert _slot_collations(connection)["saves"] == exact
def test_the_exact_save_slots_revision_fixes_an_early_deleted_assets_table():
"""A deleted_assets slot left with the table's folding collation is made exact."""
migration = _load_migration("0138_exact_save_slots.py")
with sync_engine.begin() as connection:
exact = exact_collation(connection)
if exact is None:
pytest.skip("PostgreSQL compares slots exactly already")
with Operations.context(MigrationContext.configure(connection)) as op:
op.alter_column(
"deleted_assets",
"slot",
existing_type=sa.String(length=255),
type_=sa.String(length=255),
existing_nullable=False,
)
assert _slot_collations(connection)["deleted_assets"] != exact
migration.upgrade()
assert _slot_collations(connection)["deleted_assets"] == exact
def test_the_exact_save_slots_revision_rebuilds_no_table_already_exact():
"""A replay after a run that died partway skips the collations it finished."""
migration = _load_migration("0138_exact_save_slots.py")
statements: list[str] = []
with sync_engine.begin() as connection:
@sa.event.listens_for(connection, "before_cursor_execute")
def _record(_conn: Any, _cursor: Any, statement: str, *_args: Any) -> None:
if re.match(r"ALTER TABLE \S+ MODIFY", statement.lstrip(), re.I):
statements.append(statement)
with Operations.context(MigrationContext.configure(connection)):
migration.upgrade()
assert statements == []
def test_the_rom_similarity_revision_fills_in_a_missing_index():
"""0122 meets its own table on a replay, with only some of its indexes.

View File

@@ -6,7 +6,11 @@ from unittest.mock import MagicMock, patch
import pytest
from handler.database import db_device_handler, db_save_handler
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
db_save_handler,
)
from handler.filesystem.sync_handler import FSSyncHandler
from models.assets import Save
from models.device import Device, SyncMode
@@ -194,7 +198,9 @@ class TestProcessIncomingFileFilenameOnlyMatching:
patch("sync_watcher.asyncio") as mock_asyncio,
):
mock_cmp.return_value = MagicMock(action="upload", reason=None)
mock_asyncio.run = MagicMock()
mock_asyncio.run = MagicMock(
side_effect=lambda awaitable: awaitable.close()
)
_process_incoming_file(
device=device,
session_id=1,
@@ -261,7 +267,9 @@ class TestProcessIncomingFileFilenameOnlyMatching:
patch("sync_watcher.asyncio") as mock_asyncio,
):
mock_cmp.return_value = MagicMock(action="upload", reason=None)
mock_asyncio.run = MagicMock()
mock_asyncio.run = MagicMock(
side_effect=lambda awaitable: awaitable.close()
)
_process_incoming_file(
device=device,
session_id=1,
@@ -281,3 +289,44 @@ class TestProcessIncomingFileFilenameOnlyMatching:
assert (
slotted_after.content_hash != "slotted_old_hash"
), "slotted save should have been updated, but the bug picked archival"
def test_the_matched_slots_removals_reach_the_comparison(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
incoming_file: str,
):
from sync_watcher import _process_incoming_file
db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="collision.sav",
file_name_no_tags="collision",
file_name_no_ext="collision",
file_extension="sav",
emulator="test_emulator",
slot="autosave",
file_path=f"{platform.slug}/saves/test_emulator",
file_size_bytes=99,
content_hash="current",
)
)
db_deleted_asset_handler.record_deletion(
admin_user.id, rom.id, "autosave", "removed_here"
)
with patch("sync_watcher.compare_save_state") as mock_cmp:
mock_cmp.return_value = MagicMock(action="no_op", reason=None)
_process_incoming_file(
device=device,
session_id=1,
platform_slug=platform.fs_slug,
filename="collision.sav",
full_path=incoming_file,
)
assert set(mock_cmp.call_args.kwargs["removed_at"]) == {"removed_here"}

View File

@@ -87,6 +87,37 @@ def CustomJSON(**kwargs: Any) -> sa.JSON:
return sa.JSON(**kwargs).with_variant(sa_pg.JSONB(**kwargs), "postgresql")
# Byte for byte and NO PAD, so case, accents and trailing spaces all count.
MARIADB_EXACT_COLLATION = "utf8mb4_nopad_bin"
MYSQL_EXACT_COLLATION = "utf8mb4_0900_bin"
class ExactString(sa.types.TypeDecorator[str]):
"""A VARCHAR that MariaDB and MySQL compare exactly, as PostgreSQL and Python do."""
impl = sa.String
cache_ok = True
def load_dialect_impl(self, dialect: sa.Dialect) -> sa.types.TypeEngine[Any]:
return dialect.type_descriptor(
sa.String(self.length, collation=_exact_collation(dialect))
)
def exact_collation(conn: DatabaseBind) -> str | None:
"""The collation `ExactString` needs on this server, None on PostgreSQL."""
return _exact_collation(conn.engine.dialect)
def _exact_collation(dialect: sa.Dialect) -> str | None:
if dialect.name == "postgresql":
return None
# The dialect is named `mysql` when the MySQL driver reaches a MariaDB server.
if getattr(dialect, "is_mariadb", False):
return MARIADB_EXACT_COLLATION
return MYSQL_EXACT_COLLATION
def is_db_version_compatible(
conn: DatabaseBind,
min_version: tuple[int, ...] | None = None,

View File

@@ -4,7 +4,7 @@
/* eslint-disable */
export type SyncOperationSchema = {
/**
* Operation the client should perform. 'upload' when the client has a save the server lacks (including any null-slot save, which is never paired with server saves), 'download' when the server has a newer or unknown save, 'conflict' when both sides changed independently, 'delete' when the slot the client still holds was emptied here, and 'no_op' when no action is needed.
* Operation the client should perform. 'upload' when the client has a save the server lacks (including any null-slot save, which is never paired with server saves), 'download' when the server has a newer or unknown save or the client holds a version removed here, 'conflict' when both sides changed independently, 'delete' when the slot the client still holds was emptied here, and 'no_op' when no action is needed.
*/
action: 'upload' | 'download' | 'conflict' | 'no_op' | 'delete';
/**