feat(saves): scope save discovery to a set of ROM IDs

Sync clients that hold a subset of the library had no bounded way to ask
for the saves relevant to the ROMs on the device: `GET /api/saves` filters
one ROM at a time, and negotiation always evaluated the user's whole
slotted save set, offering downloads for ROMs the device cannot play.

Add a `rom_ids` scope to both. `GET /api/saves` takes a comma-separated
list (matching the `/roms/download` convention) and `POST /api/sync/negotiate`
takes a list in the request body, so a client with many ROMs is not bound by
URL length. Negotiation widens the scope with the ROMs the client sent saves
for, so a client save is never misread as an upload because its ROM was
omitted. The scope is read-only: an omitted ROM is outside the request, never
a deletion signal.

Both share one limit and one validation rule in the saves handler, and both
reject a scope that is non-positive or over the cap rather than truncating.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-08-29 15:44:44 -04:00
parent 55065ef893
commit e36d7646b2
7 changed files with 554 additions and 7 deletions

View File

@@ -4,7 +4,7 @@ from collections.abc import Sequence
from datetime import datetime, timezone
from typing import Annotated
from fastapi import Body, File, HTTPException, Request, UploadFile, status
from fastapi import Body, File, HTTPException, Query, Request, UploadFile, status
from fastapi.responses import FileResponse
from config import MAX_AUTOCLEANUP_LIMIT
@@ -23,6 +23,10 @@ from handler.database import (
db_screenshot_handler,
db_sync_session_handler,
)
from handler.database.saves_handler import (
MAX_ROM_IDS_PER_QUERY,
normalize_rom_id_scope,
)
from handler.filesystem import fs_asset_handler
from handler.scan_handler import scan_save, scan_screenshot
from logger.formatter import BLUE
@@ -397,10 +401,40 @@ async def add_save(
return _build_save_schema(db_save, _syncs_for_save(db_save.id, device), device)
def _parse_rom_ids(rom_ids: str) -> list[int]:
try:
parsed = [
int(part) for part in (raw.strip() for raw in rom_ids.split(",")) if part
]
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid ROM ID format. Must be comma-separated integers.",
) from exc
try:
return normalize_rom_id_scope(parsed)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
@protected_route(router.get, "", [Scope.ASSETS_READ])
def get_saves(
request: Request,
rom_id: int | None = None,
rom_ids: Annotated[
str | None,
Query(
description=(
"Comma-separated list of ROM IDs to scope the results to, for "
"clients syncing a known set of ROMs. At most "
f"{MAX_ROM_IDS_PER_QUERY} IDs per request; an empty value "
"returns no saves. Combined with `rom_id` when both are given."
),
),
] = None,
platform_id: int | None = None,
device_id: str | None = None,
slot: str | None = None,
@@ -411,7 +445,11 @@ def get_saves(
)
saves = db_save_handler.get_saves(
user_id=request.user.id, rom_id=rom_id, platform_id=platform_id, slot=slot
user_id=request.user.id,
rom_id=rom_id,
rom_ids=_parse_rom_ids(rom_ids) if rom_ids is not None else None,
platform_id=platform_id,
slot=slot,
)
if not device:

View File

@@ -1,7 +1,7 @@
from datetime import datetime
from fastapi import HTTPException, Request, status
from pydantic import Field, model_validator
from pydantic import Field, field_validator, model_validator
from config import TASK_TIMEOUT
from decorators.auth import protected_route
@@ -23,6 +23,10 @@ from handler.database import (
db_save_handler,
db_sync_session_handler,
)
from handler.database.saves_handler import (
MAX_ROM_IDS_PER_QUERY,
normalize_rom_id_scope,
)
from handler.play_session_handler import ingest_play_sessions
from handler.redis_handler import high_prio_queue
from handler.sync.comparison import compare_save_state
@@ -79,6 +83,21 @@ class SyncNegotiatePayload(BaseModel):
saves: list[ClientSaveState] = Field(
description="Current save state on the client."
)
rom_ids: list[int] | None = Field(
default=None,
description=(
"IDs of the ROMs installed on the device. When provided, downloads "
"are offered only for these ROMs (plus any ROM the client sent a "
"save for) instead of the user's whole save library. This is a "
"read-only scope: omitting a ROM never deletes or unlinks its "
f"saves. At most {MAX_ROM_IDS_PER_QUERY} IDs per request."
),
)
@field_validator("rom_ids")
@classmethod
def validate_rom_ids(cls, rom_ids: list[int] | None) -> list[int] | None:
return None if rom_ids is None else normalize_rom_id_scope(rom_ids)
class SyncPlaySessionEntry(BaseModel):
@@ -113,6 +132,11 @@ def negotiate_sync(
The client sends its current save state, and the server returns a list of
operations (upload, download, conflict, no_op) to bring both sides in sync.
A client that only holds part of the library can send `rom_ids` to scope the
negotiation to the ROMs installed on the device, which keeps the response
from listing downloads for ROMs it cannot play. The scope is read-only: a
ROM left out is simply outside this negotiation, never a deletion signal.
Saves are paired on (rom_id, slot). Clients that want a save to stay in sync
should send a stable, non-null slot name (e.g. "autosave"). Null-slot saves
are treated as archival, manual uploads: they are excluded from pairing, so a
@@ -160,9 +184,17 @@ def negotiate_sync(
operations: list[SyncOperationSchema] = []
# Widen an explicit ROM scope with the ROMs the client sent saves for, so a
# client save is never misread as an upload just because its ROM was omitted.
rom_id_scope: list[int] | None = None
if payload.rom_ids is not None:
rom_id_scope = list(
dict.fromkeys(payload.rom_ids + [s.rom_id for s in payload.saves])
)
# Pair on (rom_id, slot), keeping the newest row per slot: slot uploads are datetime-tagged (spec) so tagged filenames never equal the client's untagged name, and a slot accrues many rows over time. Null-slot rows stay archival-only.
server_saves = db_save_handler.get_saves(
user_id=request.user.id, slot_not_null=True
user_id=request.user.id, slot_not_null=True, rom_ids=rom_id_scope
)
server_save_map: dict[tuple[int, str | None], Save] = {}
for save in server_saves:

View File

@@ -1,5 +1,5 @@
from collections.abc import Sequence
from typing import Literal
from collections.abc import Collection, Iterable, Sequence
from typing import Final, Literal
from sqlalchemy import and_, asc, delete, desc, func, or_, select, update
from sqlalchemy.orm import QueryableAttribute, Session, load_only
@@ -10,6 +10,36 @@ from models.rom import Rom
from .base_handler import DBBaseHandler
# Upper bound on the `rom_ids` scope accepted by save queries, to keep the IN
# clause within driver parameter limits. Documented so sync clients can batch.
MAX_ROM_IDS_PER_QUERY: Final = 500
def normalize_rom_id_scope(rom_ids: Iterable[int]) -> list[int]:
"""Validate and deduplicate a `rom_ids` query scope, preserving order.
Args:
rom_ids: ROM IDs the caller wants to scope a save query to.
Returns:
The deduplicated IDs.
Raises:
ValueError: If any ID is not positive, or the scope exceeds
`MAX_ROM_IDS_PER_QUERY`.
"""
unique = list(dict.fromkeys(rom_ids))
if any(rom_id <= 0 for rom_id in unique):
raise ValueError("ROM IDs must be positive integers")
if len(unique) > MAX_ROM_IDS_PER_QUERY:
raise ValueError(
f"Too many ROM IDs: at most {MAX_ROM_IDS_PER_QUERY} per request"
)
return unique
class DBSavesHandler(DBBaseHandler):
@begin_session
@@ -85,6 +115,7 @@ class DBSavesHandler(DBBaseHandler):
self,
user_id: int,
rom_id: int | None = None,
rom_ids: Collection[int] | None = None,
platform_id: int | None = None,
slot: str | None = None,
slot_not_null: bool = False,
@@ -98,6 +129,10 @@ class DBSavesHandler(DBBaseHandler):
if rom_id:
query = query.filter_by(rom_id=rom_id)
# An empty collection is an explicit empty scope, not an absent filter.
if rom_ids is not None:
query = query.filter(Save.rom_id.in_(rom_ids))
if platform_id:
query = query.join(Rom, Save.rom_id == Rom.id).filter(
Rom.platform_id == platform_id

View File

@@ -11,9 +11,11 @@ from handler.auth.constants import Scope
from handler.database import (
db_device_handler,
db_device_save_sync_handler,
db_rom_handler,
db_save_handler,
)
from handler.database.base_handler import sync_session
from handler.database.saves_handler import MAX_ROM_IDS_PER_QUERY
from models.assets import Save
from models.device import Device
from models.permission import HiddenEntity, PermEntity
@@ -1444,6 +1446,153 @@ class TestSlotFiltering:
assert len(data) == 0
class TestRomIdsScope:
@pytest.fixture
def second_rom_save(self, admin_user: User, platform: Platform) -> tuple[Rom, Save]:
"""A save on a ROM other than the `rom` fixture's."""
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="second_rom",
slug="second_rom_slug",
fs_name="second_rom.zip",
fs_name_no_tags="second_rom",
fs_name_no_ext="second_rom",
fs_extension="zip",
fs_path=f"{platform.slug}/roms",
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
save = db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="second.sav",
file_name_no_tags="second",
file_name_no_ext="second",
file_extension="sav",
emulator="test_emulator",
slot="autosave",
file_path=f"{platform.slug}/saves/test_emulator",
file_size_bytes=100,
)
)
return rom, save
def test_scopes_results_to_listed_roms(
self,
client,
access_token: str,
rom: Rom,
save: Save,
second_rom_save: tuple[Rom, Save],
):
response = client.get(
f"/api/saves?rom_ids={rom.id}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert [item["id"] for item in response.json()] == [save.id]
def test_accepts_multiple_ids(
self,
client,
access_token: str,
rom: Rom,
save: Save,
second_rom_save: tuple[Rom, Save],
):
second_rom, second_save = second_rom_save
response = client.get(
f"/api/saves?rom_ids={rom.id},{second_rom.id}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert {item["id"] for item in response.json()} == {save.id, second_save.id}
def test_tolerates_whitespace_and_duplicates(
self, client, access_token: str, rom: Rom, save: Save
):
response = client.get(
f"/api/saves?rom_ids= {rom.id} , {rom.id} ",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert [item["id"] for item in response.json()] == [save.id]
def test_empty_value_returns_no_saves(self, client, access_token: str, save: Save):
response = client.get(
"/api/saves?rom_ids=",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json() == []
def test_omitted_returns_all_saves(
self,
client,
access_token: str,
save: Save,
second_rom_save: tuple[Rom, Save],
):
response = client.get(
"/api/saves",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert {item["id"] for item in response.json()} == {
save.id,
second_rom_save[1].id,
}
def test_combines_with_slot_filter(
self, client, access_token: str, rom: Rom, save: Save, archival_save: Save
):
response = client.get(
f"/api/saves?rom_ids={rom.id}&slot=autosave",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert [item["id"] for item in response.json()] == [save.id]
def test_rejects_non_integer_ids(self, client, access_token: str):
response = client.get(
"/api/saves?rom_ids=1,abc",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "comma-separated integers" in response.json()["detail"]
def test_rejects_non_positive_ids(self, client, access_token: str):
response = client.get(
"/api/saves?rom_ids=1,0",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "positive" in response.json()["detail"]
def test_rejects_scope_over_the_limit(self, client, access_token: str):
rom_ids = ",".join(str(i) for i in range(1, MAX_ROM_IDS_PER_QUERY + 2))
response = client.get(
f"/api/saves?rom_ids={rom_ids}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert str(MAX_ROM_IDS_PER_QUERY) in response.json()["detail"]
class TestDatetimeTagging:
@mock.patch(
"endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock

View File

@@ -5,17 +5,21 @@ from datetime import datetime, timedelta, timezone
from io import BytesIO
from unittest import mock
import pytest
from fastapi import status
from handler.database import (
db_device_handler,
db_device_save_sync_handler,
db_play_session_handler,
db_rom_handler,
db_save_handler,
db_sync_session_handler,
)
from handler.database.saves_handler import MAX_ROM_IDS_PER_QUERY
from models.assets import Save
from models.device import Device, SyncMode
from models.platform import Platform
from models.rom import Rom
from models.user import User
@@ -141,6 +145,188 @@ class TestSyncNegotiate:
assert data["session_id"] > 0
class TestNegotiateRomIdsScope:
"""`rom_ids` scopes negotiation to the ROMs installed on the device."""
@pytest.fixture
def uninstalled_rom_save(self, admin_user: User, platform: Platform) -> Save:
"""A server save for a ROM the device does not have installed."""
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="uninstalled_rom",
slug="uninstalled_rom_slug",
fs_name="uninstalled_rom.zip",
fs_name_no_tags="uninstalled_rom",
fs_name_no_ext="uninstalled_rom",
fs_extension="zip",
fs_path=f"{platform.slug}/roms",
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
return db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="uninstalled.sav",
file_name_no_tags="uninstalled",
file_name_no_ext="uninstalled",
file_extension="sav",
emulator="test_emulator",
slot="autosave",
file_path=f"{platform.slug}/saves/test_emulator",
file_size_bytes=100,
)
)
def test_scope_omits_downloads_for_uninstalled_roms(
self,
client,
access_token: str,
admin_user: User,
rom: Rom,
save: Save,
uninstalled_rom_save: Save,
):
device = db_device_handler.add_device(
Device(id="neg-scope-dev", user_id=admin_user.id, sync_enabled=True)
)
response = client.post(
"/api/sync/negotiate",
json={"device_id": device.id, "saves": [], "rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
save_ids = [op["save_id"] for op in response.json()["operations"]]
assert save.id in save_ids
assert uninstalled_rom_save.id not in save_ids
def test_without_scope_all_saves_are_offered(
self,
client,
access_token: str,
admin_user: User,
save: Save,
uninstalled_rom_save: Save,
):
device = db_device_handler.add_device(
Device(id="neg-noscope-dev", user_id=admin_user.id, sync_enabled=True)
)
response = client.post(
"/api/sync/negotiate",
json={"device_id": device.id, "saves": []},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
save_ids = [op["save_id"] for op in response.json()["operations"]]
assert {save.id, uninstalled_rom_save.id} <= set(save_ids)
def test_client_save_outside_scope_is_still_paired(
self, client, access_token: str, admin_user: User, rom: Rom, save: Save
):
"""A ROM missing from `rom_ids` but present in `saves` must not be
misread as an upload just because the scope omitted it."""
device = db_device_handler.add_device(
Device(id="neg-scope-pair-dev", user_id=admin_user.id, sync_enabled=True)
)
response = client.post(
"/api/sync/negotiate",
json={
"device_id": device.id,
"rom_ids": [rom.id + 10_000],
"saves": [
{
"rom_id": rom.id,
"file_name": save.file_name,
"slot": save.slot,
"updated_at": "2026-01-10T00:00:00Z",
"file_size_bytes": 1024,
}
],
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["total_upload"] == 0
assert [op["save_id"] for op in data["operations"]] == [save.id]
def test_empty_scope_offers_no_downloads(
self, client, access_token: str, admin_user: User, save: Save
):
device = db_device_handler.add_device(
Device(id="neg-empty-scope-dev", user_id=admin_user.id, sync_enabled=True)
)
response = client.post(
"/api/sync/negotiate",
json={"device_id": device.id, "saves": [], "rom_ids": []},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["operations"] == []
def test_scope_does_not_delete_saves_outside_it(
self, client, access_token: str, admin_user: User, save: Save
):
"""The scope is read-only: an omitted ROM keeps its saves."""
device = db_device_handler.add_device(
Device(
id="neg-scope-readonly-dev", user_id=admin_user.id, sync_enabled=True
)
)
client.post(
"/api/sync/negotiate",
json={"device_id": device.id, "saves": [], "rom_ids": []},
headers={"Authorization": f"Bearer {access_token}"},
)
assert db_save_handler.get_save(user_id=admin_user.id, id=save.id) is not None
def test_rejects_non_positive_ids(
self, client, access_token: str, admin_user: User
):
device = db_device_handler.add_device(
Device(id="neg-badid-dev", user_id=admin_user.id, sync_enabled=True)
)
response = client.post(
"/api/sync/negotiate",
json={"device_id": device.id, "saves": [], "rom_ids": [0]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
def test_rejects_scope_over_the_limit(
self, client, access_token: str, admin_user: User
):
device = db_device_handler.add_device(
Device(id="neg-toomany-dev", user_id=admin_user.id, sync_enabled=True)
)
response = client.post(
"/api/sync/negotiate",
json={
"device_id": device.id,
"saves": [],
"rom_ids": list(range(1, MAX_ROM_IDS_PER_QUERY + 2)),
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
class TestSyncSessions:
def test_complete_session(self, client, access_token: str, admin_user: User):
device = db_device_handler.add_device(

View File

@@ -5,7 +5,13 @@ 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 pytest
from handler.database import db_rom_handler, db_save_handler
from handler.database.saves_handler import (
MAX_ROM_IDS_PER_QUERY,
normalize_rom_id_scope,
)
from models.assets import Save
from models.platform import Platform
from models.rom import Rom
@@ -901,3 +907,100 @@ class TestDBSavesHandlerGetLatestSavesForRoms:
)
assert latest == {}
class TestGetSavesRomIdsScope:
"""Test suite for the `rom_ids` scope on DBSavesHandler.get_saves."""
def _add_save(self, user_id: int, rom: Rom, file_name: str) -> Save:
return db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=user_id,
file_name=file_name,
file_name_no_tags=file_name.removesuffix(".sav"),
file_name_no_ext=file_name.removesuffix(".sav"),
file_extension="sav",
emulator="test_emulator",
slot="autosave",
file_path=f"{rom.platform_slug}/saves/test_emulator",
file_size_bytes=100,
)
)
def _add_rom(self, admin_user: User, platform: Platform, slug: str) -> Rom:
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name=slug,
slug=slug,
fs_name=f"{slug}.zip",
fs_name_no_tags=slug,
fs_name_no_ext=slug,
fs_extension="zip",
fs_path=f"{platform.slug}/roms",
)
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
return rom
def test_scopes_to_listed_roms(
self, admin_user: User, platform: Platform, rom: Rom, save: Save
):
other_rom = self._add_rom(admin_user, platform, "other_rom")
other_save = self._add_save(admin_user.id, other_rom, "other.sav")
saves = db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[rom.id])
assert [s.id for s in saves] == [save.id]
assert other_save.id not in [s.id for s in saves]
def test_scopes_to_multiple_roms(
self, admin_user: User, platform: Platform, rom: Rom, save: Save
):
other_rom = self._add_rom(admin_user, platform, "other_rom")
other_save = self._add_save(admin_user.id, other_rom, "other.sav")
saves = db_save_handler.get_saves(
user_id=admin_user.id, rom_ids=[rom.id, other_rom.id]
)
assert {s.id for s in saves} == {save.id, other_save.id}
def test_empty_scope_returns_nothing(self, admin_user: User, save: Save):
assert db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[]) == []
def test_omitted_scope_returns_everything(self, admin_user: User, save: Save):
saves = db_save_handler.get_saves(user_id=admin_user.id, rom_ids=None)
assert save.id in [s.id for s in saves]
def test_combines_with_slot_filter(
self, admin_user: User, rom: Rom, save: Save, archival_save: Save
):
saves = db_save_handler.get_saves(
user_id=admin_user.id, rom_ids=[rom.id], slot_not_null=True
)
assert [s.id for s in saves] == [save.id]
class TestNormalizeRomIdScope:
def test_deduplicates_preserving_order(self):
assert normalize_rom_id_scope([3, 1, 3, 2, 1]) == [3, 1, 2]
def test_rejects_non_positive_ids(self):
with pytest.raises(ValueError, match="positive"):
normalize_rom_id_scope([1, 0])
with pytest.raises(ValueError, match="positive"):
normalize_rom_id_scope([-1])
def test_accepts_scope_at_the_limit(self):
rom_ids = list(range(1, MAX_ROM_IDS_PER_QUERY + 1))
assert normalize_rom_id_scope(rom_ids) == rom_ids
def test_rejects_scope_over_the_limit(self):
with pytest.raises(ValueError, match="Too many ROM IDs"):
normalize_rom_id_scope(range(1, MAX_ROM_IDS_PER_QUERY + 2))

View File

@@ -12,5 +12,9 @@ export type SyncNegotiatePayload = {
* Current save state on the client.
*/
saves: Array<ClientSaveState>;
/**
* IDs of the ROMs installed on the device. When provided, downloads are offered only for these ROMs (plus any ROM the client sent a save for) instead of the user's whole save library. This is a read-only scope: omitting a ROM never deletes or unlinks its saves. At most 500 IDs per request.
*/
rom_ids?: (Array<number> | null);
};