fix(roms): serve the char index only for lexically ordered sorts

The alpha strip's offsets only mean anything when the rows are ordered
by the letters being counted. Sorts that fell back to the name column
(dates, ratings) and native enum sorts (the database orders those by
declaration order) produced name-based offsets into a differently
ordered result, so strip jumps landed on the wrong rows. Skip the
sidecar for those sorts before touching the cache; the strip renders
its letters disabled. This also retires the letter walk's NULL bucket
and enum cast, which no such sort can reach any more.

Version the char_index and rom_id_index cache keys with the release
schema marker, like filter_values already does, so sidecars cached
before an ordering-semantics change stop being served after a deploy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ND1wfNV3vKwu8Mfinn4WkA
This commit is contained in:
zurdi
2026-09-10 18:39:29 +02:00
parent e566f41c9d
commit 33c73a3fbe
3 changed files with 45 additions and 37 deletions

View File

@@ -184,12 +184,6 @@ ROM_METADATA_ORDER_COLUMNS: dict[str, QueryableAttribute] = {
}
def _sorts_nulls_last(order_column: Any) -> bool:
"""RomUser sort keys are NULL for roms the user never touched; the query
ordering and the char-index walk must both pin that bucket last."""
return getattr(order_column, "class_", None) is RomUser
# Filter dropdowns read the narrow `roms_facets` mirror instead of `roms`,
# whose rows carry the raw metadata blobs. Column order matches the unpacking
# in `_collect_filter_values`.
@@ -309,6 +303,14 @@ def _filter_values_redis_key(cache_key: str, version: str) -> str:
return f"filter_values:{ROM_FILTERS_CACHE_SCHEMA_VERSION}:{cache_key}:v{version}"
def _char_index_redis_key(cache_key: str, version: str) -> str:
return f"char_index:{ROM_FILTERS_CACHE_SCHEMA_VERSION}:{cache_key}:v{version}"
def _rom_id_index_redis_key(cache_key: str, version: str) -> str:
return f"rom_id_index:{ROM_FILTERS_CACHE_SCHEMA_VERSION}:{cache_key}:v{version}"
def _store_versioned_cache(redis_key: str, version: str, result: Any) -> None:
version_keys_set = _filter_values_cache_keys_key(version)
with sync_cache.pipeline() as pipe:
@@ -1681,7 +1683,7 @@ class DBRomsHandler(DBBaseHandler):
# keys (no rom_user row, or an unset field) last in both directions.
nulls_last_clause = (
order_attr_column.is_(None)
if _sorts_nulls_last(order_attr_column)
if getattr(order_attr_column, "class_", None) is RomUser
else None
)
@@ -1821,11 +1823,19 @@ class DBRomsHandler(DBBaseHandler):
order_dir: str = "asc",
session: Session = None, # type: ignore
) -> list[tuple[str, int]]:
# Letter offsets only index a lexically ordered result: skip sorts
# that fall back to another column, and native enums (the database
# orders those by declaration order, not by their letters).
if not isinstance(order_by_attr.type, (String, Text)) or isinstance(
order_by_attr.type, Enum
):
return []
redis_key: str | None = None
version: str | None = None
if cache_key:
version = _filter_values_cache_version()
redis_key = f"char_index:{cache_key}:v{version}"
redis_key = _char_index_redis_key(cache_key, version)
cached = sync_cache.get(redis_key)
if cached is not None:
return json.loads(cached)
@@ -1834,31 +1844,18 @@ class DBRomsHandler(DBBaseHandler):
# This builds its own positional ordering below.
query = query.order_by(None)
if not isinstance(order_by_attr.type, (String, Text)):
order_by_attr = Rom.name_sort_key
# The alpha-strip only needs each first letter's starting offset, not a
# positional number for every row. Counting rows per letter and
# accumulating those counts avoids row_number() over the whole library,
# which forced a full materialization + filesort on large libraries.
descending = order_dir.lower() == "desc"
letter_source = order_by_attr
if isinstance(order_by_attr.type, Enum):
# PostgreSQL has no substring() overload for native enums.
letter_source = cast(order_by_attr, String)
letter = func.substring(letter_source, 1, 1)
letter_order: list[ColumnElement[Any]] = []
# A NULLS-pinned sort needs the letter walk to visit that bucket last
# too, or every offset shifts by its size.
if _sorts_nulls_last(order_by_attr):
letter_order.append(letter.is_(None))
letter_order.append(letter.desc() if descending else letter.asc())
letter = func.substring(order_by_attr, 1, 1)
counts = (
query.with_only_columns( # type: ignore
letter.label("letter"), func.count().label("count")
)
.group_by(letter)
.order_by(*letter_order)
.order_by(letter.desc() if descending else letter.asc())
)
# Walk the letters in the same direction the client paginates over, so
@@ -1894,7 +1891,7 @@ class DBRomsHandler(DBBaseHandler):
version: str | None = None
if cache_key:
version = _filter_values_cache_version()
redis_key = f"rom_id_index:{cache_key}:v{version}"
redis_key = _rom_id_index_redis_key(cache_key, version)
cached = sync_cache.get(redis_key)
if cached is not None:
return json.loads(cached)

View File

@@ -23,9 +23,11 @@ from tests.conftest import session as session_factory
from handler.database import db_rom_handler
from handler.database.roms_handler import (
ROM_FILTERS_CACHE_VERSION_KEY,
_char_index_redis_key,
_filter_values_cache_keys_key,
_filter_values_cache_version,
_filter_values_redis_key,
_rom_id_index_redis_key,
_store_versioned_cache,
)
from handler.redis_handler import sync_cache
@@ -152,7 +154,7 @@ class TestCacheHitMatchesMiss:
)
version = _filter_values_cache_version()
redis_key = f"char_index:{cache_key}:v{version}"
redis_key = _char_index_redis_key(cache_key, version)
assert sync_cache.get(redis_key) is not None
# "test_rom" -> first letter "t" at position 0.
assert dict(miss) == {"t": 0}
@@ -186,7 +188,7 @@ class TestCacheHitMatchesMiss:
miss = db_rom_handler.get_rom_id_index(query=query, cache_key=cache_key)
version = _filter_values_cache_version()
redis_key = f"rom_id_index:{cache_key}:v{version}"
redis_key = _rom_id_index_redis_key(cache_key, version)
assert sync_cache.get(redis_key) is not None
assert miss == [rom.id]

View File

@@ -123,20 +123,29 @@ class TestRomUserSortResults:
assert db_rom_handler.get_rom_count(query=query) == 3
def test_char_index_visits_the_null_bucket_last(
self, admin_user: User, platform: Platform
@pytest.mark.parametrize("order_by", ["last_played", "status"])
def test_char_index_skips_non_lexical_sorts(
self, admin_user: User, platform: Platform, order_by: str
):
for name in ("first_done", "second_done"):
_set_user_props(
_make_rom(platform, name),
admin_user,
{"status": RomUserStatus.FINISHED},
)
_set_user_props(
_make_rom(platform, "finished"),
admin_user,
{"status": RomUserStatus.FINISHED},
)
_set_user_props(
_make_rom(platform, "incomplete"),
admin_user,
{
"status": RomUserStatus.INCOMPLETE,
"last_played": datetime(2024, 6, 1, tzinfo=timezone.utc),
},
)
_make_rom(platform, "untouched")
query, order_column = db_rom_handler.get_roms_query(
order_by="status", user_id=admin_user.id
order_by=order_by, user_id=admin_user.id
)
# The status-less rom sorts last, so it must not shift the offsets.
assert db_rom_handler.with_char_index(query, order_column) == [("F", 0)]
# Offsets into a non-lexical order (a date, or an enum the database
# orders by declaration) would hand the alpha strip wrong targets.
assert db_rom_handler.with_char_index(query, order_column) == []