fix(collections): refresh smart collections on per-user state changes

Removing the read-time recompute left the cached membership blind to
everything that is not a ROM edit. A save, a state, a status, or moving
a ROM in or out of a regular collection all change what `has_saves`,
`has_states`, `statuses`, `collection_id` and `favorite` match, so the
stored counts, covers and ROM-detail chips went stale until an unrelated
edit or the next scan.

Refresh from those paths too: save and state upload, delete and
visibility toggle, `update_rom_user` when a status is set, and adding or
removing collection members. Sharing an asset is included because
`has_saves` matches other users' public saves, so it moves collections
that are not the uploader's.

These changes leave the ROM row alone, so they pass `membership_only`
and only recount a collection when the ROM actually joined or left.
Autosaves land constantly, and without it every one of them would force
a full recount of any collection the ROM already belonged to.

Reported by Greptile on #4039.

Implemented with Claude Code (Opus 5), tests first, then reviewed and
verified by me.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Spinnich
2026-07-31 22:18:53 +00:00
parent b5d276e2ed
commit 7399c19479
7 changed files with 157 additions and 11 deletions

View File

@@ -14,6 +14,7 @@ from endpoints.responses.collection import (
SmartCollectionSchema,
VirtualCollectionSchema,
)
from endpoints.roms import refresh_affected_smart_collections
from exceptions.endpoint_exceptions import (
CollectionAlreadyExistsException,
CollectionNotFoundInDatabaseException,
@@ -559,6 +560,7 @@ async def add_roms_to_collection(
updated_collection = db_collection_handler.add_roms_to_collection(
id, payload.rom_ids
)
refresh_affected_smart_collections(payload.rom_ids, membership_only=True)
return CollectionSchema.model_validate(updated_collection)
@@ -588,6 +590,7 @@ async def remove_roms_from_collection(
updated_collection = db_collection_handler.remove_roms_from_collection(
id, payload.rom_ids
)
refresh_affected_smart_collections(payload.rom_ids, membership_only=True)
return CollectionSchema.model_validate(updated_collection)

View File

@@ -119,14 +119,18 @@ def safe_int_or_none(value: Any) -> int | None:
return safe_int(value)
def refresh_affected_smart_collections(rom_ids: Sequence[int]) -> None:
"""Follow a library change into the cached smart collection membership.
def refresh_affected_smart_collections(
rom_ids: Sequence[int], membership_only: bool = False
) -> None:
"""Follow a change into the cached smart collection membership.
The ROM write has already been committed, so a stale count is the worst
this can cost, and reporting it back as a failed write would be a lie.
The write has already been committed, so a stale count is the worst this
can cost, and reporting it back as a failed write would be a lie.
"""
try:
db_collection_handler.refresh_smart_collections_for_roms(rom_ids)
db_collection_handler.refresh_smart_collections_for_roms(
rom_ids, membership_only=membership_only
)
except Exception as e:
log.error(f"Couldn't refresh smart collections for {rom_ids}: {e}")
@@ -2115,4 +2119,7 @@ async def update_rom_user(
if "hidden" in cleaned_data:
db_rom_handler.invalidate_filter_values_cache()
if "status" in cleaned_data:
refresh_affected_smart_collections([id], membership_only=True)
return RomUserSchema.model_validate(rom_user)

View File

@@ -11,6 +11,7 @@ from config import MAX_AUTOCLEANUP_LIMIT
from decorators.auth import protected_route
from endpoints.responses.assets import SaveSchema, SaveSummarySchema, SlotSummarySchema
from endpoints.responses.device import DeviceSyncSchema
from endpoints.roms import refresh_affected_smart_collections
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_rom_visible
@@ -391,6 +392,8 @@ async def add_save(
rom_user.id, {"last_played": datetime.now(timezone.utc)}
)
refresh_affected_smart_collections([rom.id], membership_only=True)
return _build_save_schema(db_save, _syncs_for_save(db_save.id, device), device)
@@ -684,6 +687,9 @@ def update_save_visibility(
save.screenshot.id, {"is_public": is_public}
)
# Sharing a save exposes it to every other user's `has_saves` filter.
refresh_affected_smart_collections([save.rom_id], membership_only=True)
return _build_save_schema(updated)
@@ -712,6 +718,8 @@ async def delete_saves(
log.error(error)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error)
affected_rom_ids: set[int] = set()
for save_id in saves:
save = db_save_handler.get_save(user_id=request.user.id, id=save_id)
if not save:
@@ -719,6 +727,7 @@ async def delete_saves(
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
affected_rom_ids.add(save.rom_id)
db_save_handler.delete_save(save_id)
log.info(
@@ -741,6 +750,8 @@ async def delete_saves(
error = f"Screenshot file {hl(save.screenshot.file_name)} not found for save {hl(save.file_name)}[{hl(save.rom.platform_slug)}]"
log.error(error)
refresh_affected_smart_collections(sorted(affected_rom_ids), membership_only=True)
return saves

View File

@@ -6,6 +6,7 @@ from fastapi.responses import FileResponse
from decorators.auth import protected_route
from endpoints.responses.assets import StateSchema
from endpoints.roms import refresh_affected_smart_collections
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_rom_visible
@@ -169,6 +170,8 @@ async def add_state(
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
refresh_affected_smart_collections([rom.id], membership_only=True)
return StateSchema.model_validate(db_state)
@@ -357,6 +360,9 @@ def update_state_visibility(
state.screenshot.id, {"is_public": is_public}
)
# Sharing a state exposes it to every other user's `has_states` filter.
refresh_affected_smart_collections([state.rom_id], membership_only=True)
return StateSchema.model_validate(updated)
@@ -385,6 +391,8 @@ async def delete_states(
log.error(error)
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error)
affected_rom_ids: set[int] = set()
for state_id in states:
state = db_state_handler.get_state(user_id=request.user.id, id=state_id)
if not state:
@@ -392,6 +400,7 @@ async def delete_states(
log.error(error)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
affected_rom_ids.add(state.rom_id)
db_state_handler.delete_state(state_id)
log.info(
f"Deleting state {hl(state.file_name)} [{state.rom.platform_slug}] from filesystem"
@@ -414,4 +423,6 @@ async def delete_states(
error = f"Screenshot file {hl(state.screenshot.file_name)} not found for state {hl(state.file_name)}[{hl(state.rom.platform_slug)}]"
log.error(error)
refresh_affected_smart_collections(sorted(affected_rom_ids), membership_only=True)
return states

View File

@@ -637,15 +637,21 @@ class DBCollectionsHandler(DBBaseHandler):
def refresh_smart_collections_for_roms(
self,
rom_ids: Sequence[int],
membership_only: bool = False,
session: Session = None, # type: ignore
) -> int:
"""Refresh the collections a handful of edited or deleted ROMs touch.
"""Refresh the collections a handful of changed ROMs touch.
Editing one ROM rarely moves any collection, and asking whether given
ids match is an indexed lookup, so only the collections that actually
hold one of them pay for a recount. Membership is then recomputed whole,
since a ROM that stayed a member can still have changed the stored order
or the cover mosaic.
hold one of them pay for a recount.
`membership_only` is for changes that leave the ROM row alone, like a
save, a state, a status or collection membership: nothing about the ROM
can have moved except whether it matches, so a member that stayed one
needs no recount. That matters because autosaves land constantly. The
default suits a library change, where a ROM that stayed a member can
still have a new name, sort position or cover to reflect.
"""
from handler.database import db_rom_handler
@@ -661,7 +667,9 @@ class DBCollectionsHandler(DBBaseHandler):
user_id=smart_collection.user_id,
session=session,
)
if matching or candidates & set(smart_collection.rom_ids):
cached = candidates & set(smart_collection.rom_ids)
moved = matching != cached if membership_only else bool(matching or cached)
if moved:
self.refresh_smart_collection(smart_collection.id, session=session)
refreshed += 1

View File

@@ -729,3 +729,54 @@ class TestSmartCollectionEndpoints:
assert after.updated_at == before.updated_at
assert list(after.rom_ids) == list(before.rom_ids)
assert after.path_covers_small == before.path_covers_small
def test_adding_a_rom_to_a_collection_refreshes_scoped_membership(
self, client, access_token: str, admin_user: User, rom: Rom
):
shelf = db_collection_handler.add_collection(
Collection(name="Shelf", description="", user_id=admin_user.id)
)
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="On the shelf",
description="",
user_id=admin_user.id,
filter_criteria={"collection_id": shelf.id},
)
)
db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.post(
f"/api/collections/{shelf.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
refreshed = db_collection_handler.get_smart_collection(smart_collection.id)
assert refreshed is not None
assert refreshed.rom_ids == [rom.id]
def test_setting_a_rom_status_refreshes_membership(
self, client, access_token: str, admin_user: User, rom: Rom
):
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="Finished games",
description="",
user_id=admin_user.id,
filter_criteria={"statuses": ["finished"]},
)
)
db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.put(
f"/api/roms/{rom.id}/props",
json={"status": "finished"},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
refreshed = db_collection_handler.get_smart_collection(smart_collection.id)
assert refreshed is not None
assert refreshed.rom_ids == [rom.id]

View File

@@ -7,7 +7,8 @@ memory and writing it back on every read (see #4029).
from collections.abc import Sequence
from handler.database import db_collection_handler, db_rom_handler
from handler.database import db_collection_handler, db_rom_handler, db_save_handler
from models.assets import Save
from models.collection import Collection, SmartCollection
from models.platform import Platform
from models.rom import Rom
@@ -310,6 +311,60 @@ def test_refresh_for_roms_leaves_untouched_collections_alone(
assert refresh.call_count == 0
def _add_save(rom: Rom, user: User, name: str = "save.sav") -> Save:
return db_save_handler.add_save(
Save(
rom_id=rom.id,
user_id=user.id,
file_name=name,
file_name_no_tags=name,
file_name_no_ext=name,
file_extension="sav",
emulator="test_emulator",
file_path="test/saves",
file_size_bytes=1.0,
)
)
def test_refresh_for_roms_follows_per_user_state(platform: Platform, admin_user: User):
# A save is not a ROM edit, but it moves anything filtering on `has_saves`.
collection = _add_smart_collection(admin_user, {"has_saves": True})
rom = _add_rom(platform, "Rally One")
db_collection_handler.refresh_smart_collections()
seeded = db_collection_handler.get_smart_collection(collection.id)
assert seeded is not None and seeded.rom_count == 0
_add_save(rom, admin_user)
db_collection_handler.refresh_smart_collections_for_roms(
[rom.id], membership_only=True
)
after = db_collection_handler.get_smart_collection(collection.id)
assert after is not None
assert after.rom_ids == [rom.id]
def test_refresh_for_roms_membership_only_skips_a_member_that_stayed(
platform: Platform, admin_user: User, mocker
):
# Autosaves land constantly. Once the ROM is already a member, another save
# changes nothing about the collection, so it must not force a recount.
_add_smart_collection(admin_user, {"has_saves": True})
rom = _add_rom(platform, "Rally One")
_add_save(rom, admin_user, "first.sav")
db_collection_handler.refresh_smart_collections()
_add_save(rom, admin_user, "second.sav")
refresh = mocker.spy(db_collection_handler, "refresh_smart_collection")
moved = db_collection_handler.refresh_smart_collections_for_roms(
[rom.id], membership_only=True
)
assert moved == 0
assert refresh.call_count == 0
def test_cached_membership_belongs_to_the_owner(
platform: Platform, admin_user: User, editor_user: User
):