diff --git a/.claude/skills/backend-development/SKILL.md b/.claude/skills/backend-development/SKILL.md index f1a1a8c19..fdab401d7 100644 --- a/.claude/skills/backend-development/SKILL.md +++ b/.claude/skills/backend-development/SKILL.md @@ -99,6 +99,7 @@ npm run generate # writes src/__generated__/ via openapi-typescript-codegen cd backend uv run python3 main.py # run (migrations auto-apply on startup) uv run pytest # tests - affected files only, NEVER the whole suite +uv run pytest -n auto # same, in parallel; use for directories, not single files ``` - Tests: pytest + pytest-asyncio, isolated per `pytest-xdist` worker (per-worker DBs); `fakeredis`; `pytest-recording` VCR cassettes mock external APIs; Hypothesis for property tests. Mirror the `backend//` layout under `backend/tests/`. First-time test DB setup: `docker exec -i romm-db-dev mariadb -uroot -p < backend/romm_test/setup.sql`. diff --git a/.claude/skills/review-polish/SKILL.md b/.claude/skills/review-polish/SKILL.md index 45920a111..d14451fde 100644 --- a/.claude/skills/review-polish/SKILL.md +++ b/.claude/skills/review-polish/SKILL.md @@ -194,7 +194,7 @@ With `uiVersion = "v2"`: Run from `backend/`: -1. `uv run pytest `: zero failures on the tests affected by the diff. Never run the whole suite locally (20+ minutes); see [AGENTS.md](../../../AGENTS.md) for how to pick targets. CI runs it in full. +1. `uv run pytest `: zero failures on the tests affected by the diff. Add `-n auto` when the targets span a directory or more. Never run the whole suite locally (20+ minutes serially); see [AGENTS.md](../../../AGENTS.md) for how to pick targets. CI runs it in full. 2. `trunk fmt && trunk check`: ruff/black/isort/bandit clean (CI enforces Trunk). 3. `uv run mypy --config-file ../.trunk/configs/mypy.ini .`: zero errors across the backend (CI enforces it). 4. **If you added a migration:** `uv run alembic upgrade head` then `uv run alembic downgrade -1` to prove both directions; it must work on MariaDB **and** PostgreSQL (CI runs both). diff --git a/AGENTS.md b/AGENTS.md index 55d175fc8..66e0d3e77 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,19 +53,24 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha ## Never run the full backend test suite locally -A bare `uv run pytest` (or `pytest -vv`) over `backend/` takes 20+ minutes and burns a -huge number of tokens on output. Don't do it, even to "double check" at the end. +A bare `uv run pytest` (or `pytest -vv`) over `backend/` runs serially, takes 20+ minutes, and +burns a huge number of tokens on output. Don't do it, even to "double check" at the end. -Instead, select the tests affected by the change and run only those: +Instead, select the tests affected by the change and run only those. Add `-n auto` when the +selection spans a directory or more: the suite is set up for `pytest-xdist` (one database per +worker). ```bash cd backend uv run pytest tests/path/to/test_file.py # one file uv run pytest tests/path/to/test_file.py::test_name # one test -uv run pytest tests/handler/ tests/endpoints/ # affected areas +uv run pytest -n auto tests/handler/ tests/endpoints/ # affected areas, in parallel uv run pytest -k "scan or queue" # by name pattern ``` +It gains nothing on a single file or test, and `--pdb` and `-s` don't work under it, so drop it +when debugging. + Pick the targets from the diff: the test file mirroring each changed module (`backend//x.py` → `backend/tests//test_x.py`), plus the tests of the callers of anything whose signature or behavior you changed (`grep` for the symbol). diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index 2d97c28b9..fe44de670 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -236,7 +236,8 @@ _Migrations will be run automatically when running the tests._ cd backend # path or test file can be passed as argument to test only a subset uv run pytest [path/file] -# or run the following command to run all tests -# the -vv switch increases the verbosity of the output, providing more detailed information during test execution. -uv run pytest -vv +# or run the following command to run all tests, one worker per CPU core +uv run pytest -n auto ``` + +_Each `-n` worker gets its own database (`romm_test_gw0`, `romm_test_gw1`, ...), created and migrated on demand; `setup.sql` grants the test user the rights to create them. On a machine with many cores, cap the workers with `--maxprocesses 4` (CI's count) to keep the load on the database down. A serial run of the whole suite takes 20+ minutes. Drop `-n auto` when debugging with `--pdb` or `-s`, which don't work under parallel workers._ diff --git a/backend/AGENTS.md b/backend/AGENTS.md index 85919cb08..36ac7b2c0 100644 --- a/backend/AGENTS.md +++ b/backend/AGENTS.md @@ -6,6 +6,7 @@ uv sync --all-extras --dev # install uv run main.py # run (migrations auto-apply) uv run pytest # test - affected files only, NEVER the whole suite +uv run pytest -n auto # same, in parallel; use for directories, not single files uv run mypy --config-file ../.trunk/configs/mypy.ini . # type-check the whole backend uv run alembic revision --autogenerate -m "msg" # new migration (then HAND-REVIEW) uv run alembic upgrade head # apply migrations diff --git a/backend/exceptions/database_exceptions.py b/backend/exceptions/database_exceptions.py new file mode 100644 index 000000000..d68106d5e --- /dev/null +++ b/backend/exceptions/database_exceptions.py @@ -0,0 +1,9 @@ +class RomFileOwnerChangedError(Exception): + def __init__(self, rom_file_id: int) -> None: + self.message = ( + f"Rom file {rom_file_id} moved to another rom while it was being locked" + ) + super().__init__(self.message) + + def __repr__(self) -> str: + return self.message diff --git a/backend/handler/database/audit_events_handler.py b/backend/handler/database/audit_events_handler.py index d1924b81f..cc6c12bb4 100644 --- a/backend/handler/database/audit_events_handler.py +++ b/backend/handler/database/audit_events_handler.py @@ -11,7 +11,6 @@ from models.audit_event import AuditCategory, AuditEvent, actions_in from models.device import Device from models.rom import Rom from models.user import User -from utils.database import LIKE_ESCAPE_CHAR, escape_like from .base_handler import DBBaseHandler, affected_rows @@ -94,11 +93,10 @@ class DBAuditEventsHandler(DBBaseHandler): if filters.max_id is not None: clauses.append(AuditEvent.id <= filters.max_id) if filters.search: - like = f"%{escape_like(filters.search.lower())}%" clauses.append( or_( *( - func.lower(column).like(like, escape=LIKE_ESCAPE_CHAR) + column.icontains(filters.search, autoescape=True) for column in ( AuditEvent.actor_name, AuditEvent.target_name, diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 59a24d2cb..2a155f2d7 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -40,11 +40,12 @@ from sqlalchemy.orm import ( selectinload, undefer, ) -from sqlalchemy.sql.elements import ClauseList, ColumnElement, UnaryExpression +from sqlalchemy.sql.elements import ColumnElement, UnaryExpression from sqlalchemy.sql.selectable import Select from config.config_manager import config_manager as cm from decorators.database import INJECTED_SESSION, begin_session +from exceptions.database_exceptions import RomFileOwnerChangedError from handler.database.rom_filters import ( ROM_FILTER_SPECS, FilterKind, @@ -83,15 +84,18 @@ from models.rom import ( ) from utils import get_version from utils.database import ( - LIKE_ESCAPE_CHAR, ROMS_SEARCH_FULLTEXT_COLUMNS, SORTABLE_NULLABLE_ROM_COLUMNS, epoch_ms_in_ranges, - escape_like, is_non_blank, release_day_ranges, rom_unset_flag_column, ) +from utils.fulltext import ( + FULLTEXT_TOKEN_REGEX, + fulltext_settings, + split_fulltext_words, +) from utils.platform_slugs import UniversalPlatformSlug as UPS from utils.sql_dialect import ( Analyze, @@ -103,7 +107,7 @@ from utils.sql_dialect import ( nulls_last, ) -from .base_handler import DBBaseHandler, affected_rows +from .base_handler import DBBaseHandler, affected_rows, sync_engine type RomSelect = Select[tuple[Rom]] @@ -162,12 +166,6 @@ RUFFLE_SUPPORTED_PLATFORMS = [ UPS.BROWSER, ] -# Used to remove native full-text SQL operators -FULLTEXT_BOOLEAN_OPERATORS_REGEX = re.compile(r'[+\-~<>()"@*]') - -# 3 is the default minimum size in InnoDB -FULLTEXT_MIN_TOKEN_SIZE = 3 - # A term reaches the hash columns only when it is hex of exactly a digest # length, so an ordinary name search builds no hash SQL at all. Hashes are # stored lowercase, which keeps the lookup an indexed equality. @@ -237,6 +235,12 @@ ROM_SEARCH_COLUMNS: tuple[QueryableAttribute[Any], ...] = tuple( ) +def _name_like(word: str) -> ColumnElement[bool]: + return or_( + *(column.icontains(word, autoescape=True) for column in ROM_SEARCH_COLUMNS) + ) + + def _fulltext_match(boolean_query: str) -> ColumnElement[Any]: """A MariaDB/MySQL FULLTEXT match of the ROM's name, filename and aliases.""" return fulltext_match( @@ -245,6 +249,15 @@ def _fulltext_match(boolean_query: str) -> ColumnElement[Any]: ) +def _search_relevance(phrases: Sequence[str]) -> ColumnElement[Any]: + """How well the ROM's name, filename or aliases hold the phrases, words in order.""" + holds_a_phrase = or_(*(_name_like(phrase) for phrase in phrases)) + return DialectCase( + postgresql=case((holds_a_phrase, 1), else_=0), + mysql=_fulltext_match(" ".join(f'"{phrase}"' for phrase in phrases)), + ) + + # 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`. @@ -685,6 +698,39 @@ def _drop_filter_values_bump(session: Session) -> None: session.info.pop(FILTER_VALUES_BUMP_KEY, None) +# Per-user cache invalidations queued by `_queue_user_cache_bumps`, keyed by +# user id; they run once the transaction commits. +USER_CACHE_BUMPS_KEY = "user_cache_bumps" + + +@event.listens_for(Session, "after_commit") +def _bump_user_caches_after_commit(session: Session) -> None: + bumps: dict[int, set[str]] = session.info.pop(USER_CACHE_BUMPS_KEY, {}) + # No keys-set bookkeeping: entries under an old version become + # unreachable and are reaped by the TTL or the next global bump. + for uid, uid_flags in bumps.items(): + # The write is already durable, so a cache failure only logs; the + # stale entry falls to the TTL. + try: + if "sort" in uid_flags: + sync_cache.incr(_user_sort_version_key(uid)) + if "sib" in uid_flags: + sync_cache.incr(_user_sibling_version_key(uid)) + if "feed" in uid_flags: + # Imported here because the recommendation package reads + # this module. + from handler.recommendation import invalidate_cached_feed + + invalidate_cached_feed(uid) + except Exception: + log.exception("Failed to bump user %s cache versions", uid) + + +@event.listens_for(Session, "after_rollback") +def _drop_user_cache_bumps(session: Session) -> None: + session.info.pop(USER_CACHE_BUMPS_KEY, None) + + def _queue_user_cache_bumps( session: Session, user_id: int, @@ -696,47 +742,12 @@ def _queue_user_cache_bumps( """Queues per-user cache invalidations for after this transaction commits, so a rollback bumps nothing and a concurrent reader cannot cache pre-commit rows under the new version.""" - bumps: dict[int, set[str]] = session.info.setdefault("user_cache_bumps", {}) - flags = bumps.setdefault(user_id, set()) - flags.update( + bumps: dict[int, set[str]] = session.info.setdefault(USER_CACHE_BUMPS_KEY, {}) + bumps.setdefault(user_id, set()).update( flag for flag, queued in (("sort", sort_keys), ("sib", siblings), ("feed", feed)) if queued ) - if "user_cache_bumps_armed" in session.info: - return - session.info["user_cache_bumps_armed"] = True - - def _consume(ending_session: Session) -> dict[int, set[str]]: - # Popping the state re-arms the next transaction on a reused session. - ending_session.info.pop("user_cache_bumps_armed", None) - bumps: dict[int, set[str]] = ending_session.info.pop("user_cache_bumps", {}) - return bumps - - @event.listens_for(session, "after_commit", once=True) - def _flush(_session: Session) -> None: - # No keys-set bookkeeping: entries under an old version become - # unreachable and are reaped by the TTL or the next global bump. - for uid, uid_flags in _consume(_session).items(): - # The write is already durable, so a cache failure only logs; - # the stale entry falls to the TTL. - try: - if "sort" in uid_flags: - sync_cache.incr(_user_sort_version_key(uid)) - if "sib" in uid_flags: - sync_cache.incr(_user_sibling_version_key(uid)) - if "feed" in uid_flags: - # Imported here because the recommendation package reads - # this module. - from handler.recommendation import invalidate_cached_feed - - invalidate_cached_feed(uid) - except Exception: - log.exception("Failed to bump user %s cache versions", uid) - - @event.listens_for(session, "after_rollback", once=True) - def _discard(_session: Session) -> None: - _consume(_session) class DBRomsHandler(DBBaseHandler): @@ -1119,47 +1130,40 @@ class DBRomsHandler(DBBaseHandler): ) ) - def _build_fulltext_boolean_query(self, term: str) -> str | None: - words = FULLTEXT_BOOLEAN_OPERATORS_REGEX.sub(" ", term).split() - if not words or any(len(word) < FULLTEXT_MIN_TOKEN_SIZE for word in words): - return None - return " ".join(f"+{word}*" for word in words) - - def _build_fulltext_relevance(self, search_term: str) -> str | None: - parts: list[str] = [] + def _build_search_phrases(self, search_term: str) -> list[str]: + """The multi-word terms of a search, which relevance ranks by.""" + phrases: list[str] = [] for term in search_term.split("|"): - words = FULLTEXT_BOOLEAN_OPERATORS_REGEX.sub(" ", term).split() + words = FULLTEXT_TOKEN_REGEX.findall(term) if len(words) > 1: - parts.append('"' + " ".join(words) + '"') - return " ".join(parts) if parts else None + phrases.append(" ".join(words)) + return phrases def _build_name_conditions(self, terms: Sequence[str]) -> list[Any]: """One condition per term, matching it against the ROM's name, filename and aliases.""" - # PostgreSQL's pg_trgm indexes serve the ILIKE; MariaDB and MySQL use - # their FULLTEXT index unless a word is too short for it. - like_conditions = [ - and_( - *( - or_(*(column.ilike(f"%{word}%") for column in ROM_SEARCH_COLUMNS)) - for word in term.split() + settings = fulltext_settings(sync_engine) + conditions: list[Any] = [] + for term in terms: + words = term.split() + likes = {word: _name_like(word) for word in words} + like = and_(*likes.values()) + # Unreadable settings leave LIKE alone to decide. + indexed, unindexed = ( + split_fulltext_words(words, settings) if settings else ([], words) + ) + if not indexed: + conditions.append(like) + continue + # PostgreSQL's pg_trgm indexes serve the ILIKE. On MariaDB and MySQL + # FULLTEXT drives the query and LIKE checks the words it can't hold. + match = _fulltext_match(" ".join(f"+{word}*" for word in indexed)) + conditions.append( + DialectCase( + postgresql=like, + mysql=and_(match, *(likes[word] for word in unindexed)), ) ) - for term in terms - ] - boolean_queries = [ - query - for term in terms - if (query := self._build_fulltext_boolean_query(term)) is not None - ] - if len(boolean_queries) < len(terms): - return like_conditions - - return [ - DialectCase(postgresql=like, mysql=_fulltext_match(boolean_query)) - for boolean_query, like in zip( - boolean_queries, like_conditions, strict=True - ) - ] + return conditions def _build_hash_selects(self, terms: Iterable[str]) -> list[Select[tuple[int]]]: """Id-yielding selects for terms shaped like a hash digest. @@ -1835,23 +1839,20 @@ class DBRomsHandler(DBBaseHandler): # mixed-direction pair forces a filesort. tiebreaker = Rom.id.desc() if descending else Rom.id.asc() - relevance = self._build_fulltext_relevance(search_term) if search_term else None - if relevance: - relevance_clause = _fulltext_match(relevance).desc() - # Only the FULLTEXT engines rank: relevance breaks an explicit sort's - # ties, or leads (with name breaking its ties) when no sort is picked. - order_clause = DialectCase( - postgresql=order_clause, - mysql=( - ClauseList(order_clause, relevance_clause) - if order_by - else ClauseList(relevance_clause, order_clause) - ), - ) + sort_clauses: list[Any] = [order_clause] + phrases = self._build_search_phrases(search_term) if search_term else [] + if phrases: + # Relevance breaks an explicit sort's ties, or leads (with name + # breaking its ties) when no sort is picked. + relevance_clause = _search_relevance(phrases).desc() + if order_by: + sort_clauses.append(relevance_clause) + else: + sort_clauses.insert(0, relevance_clause) return [ clause - for clause in (nulls_last_clause, order_clause, tiebreaker) + for clause in (nulls_last_clause, *sort_clauses, tiebreaker) if clause is not None ] @@ -2446,18 +2447,46 @@ class DBRomsHandler(DBBaseHandler): return rom_user - def _lock_rom_row(self, rom_id: int, session: Session) -> None: - """Serialise writers of one rom's files so each size total counts the others'.""" - # Taken before the file write, whose foreign key check would otherwise - # share-lock the row first and deadlock two writers on MariaDB. - session.execute( - select(Rom.id).where(Rom.id == rom_id).with_for_update(key_share=True) + def _lock_rom_file_and_roms( + self, rom_file_id: int, other_rom_ids: Iterable[int], session: Session + ) -> set[int] | None: + """Lock a file's owning rom and `other_rom_ids`, then the file row. + + Returns: + Every rom id locked, or None if the file does not exist. + + Raises: + RomFileOwnerChangedError: a concurrent move changed the owner first. + """ + # All rom locks go in one sorted batch before the file lock, the order + # folder conversion writes in, so no two writers can wait on each other. + owner = session.scalar(select(RomFile.rom_id).where(RomFile.id == rom_file_id)) + if owner is None: + return None + locked = {owner, *other_rom_ids} + self._lock_rom_rows(locked, session) + confirmed = session.scalar( + select(RomFile.rom_id).where(RomFile.id == rom_file_id).with_for_update() ) + if confirmed is None: + return None + if confirmed not in locked: + raise RomFileOwnerChangedError(rom_file_id) + return locked + + def _lock_rom_rows(self, rom_ids: Iterable[int], session: Session) -> None: + """Serialise writers of these roms' files so each size total counts the others'.""" + # Taken before the file write, whose foreign key check would otherwise + # share-lock the row first; in id order so two moves cannot deadlock. + for rom_id in sorted(set(rom_ids)): + session.execute( + select(Rom.id).where(Rom.id == rom_id).with_for_update(key_share=True) + ) def _recompute_fs_size_bytes(self, rom_id: int, session: Session) -> None: """Re-derive the size the gallery sorts on from the rom's file rows.""" # Summed inside the UPDATE, which MariaDB reads with locks rather than - # from the transaction snapshot; the caller holds `_lock_rom_row`. + # from the transaction snapshot; the caller holds `_lock_rom_rows`. total = ( select(func.coalesce(func.sum(RomFile.file_size_bytes), 0)) .where(RomFile.rom_id == rom_id) @@ -2477,10 +2506,18 @@ class DBRomsHandler(DBBaseHandler): rom_file: RomFile, session: Session = INJECTED_SESSION, ) -> RomFile: - self._lock_rom_row(rom_file.rom_id, session) + rom_ids = ( + self._lock_rom_file_and_roms(rom_file.id, [rom_file.rom_id], session) + if rom_file.id is not None + else None + ) + if rom_ids is None: + rom_ids = {rom_file.rom_id} + self._lock_rom_rows(rom_ids, session) merged = session.merge(rom_file) session.flush() - self._recompute_fs_size_bytes(merged.rom_id, session) + for rom_id in sorted(rom_ids): + self._recompute_fs_size_bytes(rom_id, session) return merged def _apply_scanned_rom_file( @@ -2716,13 +2753,10 @@ class DBRomsHandler(DBBaseHandler): data: dict[str, Any], session: Session = INJECTED_SESSION, ) -> RomFile | None: - resized_rom_id = ( - session.scalar(select(RomFile.rom_id).where(RomFile.id == id)) - if "file_size_bytes" in data - else None - ) - if resized_rom_id is not None: - self._lock_rom_row(resized_rom_id, session) + rom_ids: set[int] = set() + if data.keys() & {"file_size_bytes", "rom_id"}: + new_owner = [data["rom_id"]] if "rom_id" in data else [] + rom_ids = self._lock_rom_file_and_roms(id, new_owner, session) or set() session.execute( update(RomFile) @@ -2731,8 +2765,8 @@ class DBRomsHandler(DBBaseHandler): .execution_options(synchronize_session="evaluate") ) - if resized_rom_id is not None: - self._recompute_fs_size_bytes(resized_rom_id, session) + for rom_id in sorted(rom_ids): + self._recompute_fs_size_bytes(rom_id, session) return session.scalars(select(RomFile).filter_by(id=id)).one_or_none() @begin_session @@ -2858,12 +2892,11 @@ class DBRomsHandler(DBBaseHandler): if rom_id is not None: clauses.append(Rom.id == rom_id) if search: - like = f"%{escape_like(search.lower())}%" clauses.append( or_( - func.lower(TrackMeta.title).like(like, escape=LIKE_ESCAPE_CHAR), - func.lower(TrackMeta.artist).like(like, escape=LIKE_ESCAPE_CHAR), - func.lower(TrackMeta.album).like(like, escape=LIKE_ESCAPE_CHAR), + TrackMeta.title.icontains(search, autoescape=True), + TrackMeta.artist.icontains(search, autoescape=True), + TrackMeta.album.icontains(search, autoescape=True), ) ) if artist and exclude_field != "artist": @@ -3055,11 +3088,7 @@ class DBRomsHandler(DBBaseHandler): where.append(func.length(func.trim(col)) > 0) if search: target = cast(col, String) if field == "years" else col - where.append( - func.lower(target).like( - f"%{escape_like(search.lower())}%", escape=LIKE_ESCAPE_CHAR - ) - ) + where.append(target.icontains(search, autoescape=True)) count_col = func.count().label("count") base = ( select(col.label("value"), count_col) @@ -3237,11 +3266,7 @@ class DBRomsHandler(DBBaseHandler): max_duration=max_duration, ) if search: - where.append( - func.lower(Platform.name).like( - f"%{escape_like(search.lower())}%", escape=LIKE_ESCAPE_CHAR - ) - ) + where.append(Platform.name.icontains(search, autoescape=True)) count_col = func.count().label("count") base = self._music_facet_joins( select( @@ -3304,13 +3329,12 @@ class DBRomsHandler(DBBaseHandler): max_duration=max_duration, ) if search: - like = f"%{escape_like(search.lower())}%" where.append( or_( - func.lower(Rom.name).like(like, escape=LIKE_ESCAPE_CHAR), - func.lower(TrackMeta.title).like(like, escape=LIKE_ESCAPE_CHAR), - func.lower(TrackMeta.artist).like(like, escape=LIKE_ESCAPE_CHAR), - func.lower(TrackMeta.album).like(like, escape=LIKE_ESCAPE_CHAR), + Rom.name.icontains(search, autoescape=True), + TrackMeta.title.icontains(search, autoescape=True), + TrackMeta.artist.icontains(search, autoescape=True), + TrackMeta.album.icontains(search, autoescape=True), ) ) count_col = func.count().label("count") @@ -3350,16 +3374,16 @@ class DBRomsHandler(DBBaseHandler): id: int, session: Session = INJECTED_SESSION, ) -> None: - rom_id = session.scalar(select(RomFile.rom_id).where(RomFile.id == id)) - if rom_id is None: + rom_ids = self._lock_rom_file_and_roms(id, [], session) + if rom_ids is None: return - self._lock_rom_row(rom_id, session) session.execute( delete(RomFile) .where(RomFile.id == id) .execution_options(synchronize_session="evaluate") ) - self._recompute_fs_size_bytes(rom_id, session) + for rom_id in sorted(rom_ids): + self._recompute_fs_size_bytes(rom_id, session) # Note management methods def _rom_notes_query( @@ -3381,7 +3405,10 @@ class DBRomsHandler(DBBaseHandler): if search: query = query.filter( - or_(RomNote.title.contains(search), RomNote.content.contains(search)) + or_( + RomNote.title.contains(search, autoescape=True), + RomNote.content.contains(search, autoescape=True), + ) ) if tags: diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 2adc59772..1f58a5795 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -1,10 +1,11 @@ import asyncio import os import sys +import threading from collections.abc import AsyncIterator from contextlib import asynccontextmanager from enum import Enum -from typing import Any, Final +from typing import Any, Final, cast from uuid import uuid4 from redis import Redis @@ -74,11 +75,46 @@ def __get_sync_cache() -> Redis: return client -def __get_async_cache() -> AsyncRedis: - if IS_PYTEST_RUN: +_LOOP_CLIENT_ATTR: Final = "_romm_fake_async_redis" + + +class _PerLoopFakeAsyncRedis: + """A fake async client per event loop, or per thread outside one, over one fake server.""" + + # The TestClient's loop and a test's asyncio.run loop use the cache at once, + # and an asyncio.Lock in a pool they share binds to just one of them. + def __init__(self, server: Any) -> None: + self._server = server + self._by_thread = threading.local() + + def _new_client(self) -> Any: from fakeredis import FakeAsyncRedis - return FakeAsyncRedis(server=_fake_server) + return FakeAsyncRedis(server=self._server) + + def _client(self) -> Any: + try: + loop = asyncio.get_running_loop() + except RuntimeError: + client = getattr(self._by_thread, "client", None) + if client is None: + client = self._by_thread.client = self._new_client() + return client + # Held on the loop, not in a map keyed by it: the client's asyncio + # objects reference the loop, so such a map would never let one go. + client = getattr(loop, _LOOP_CLIENT_ATTR, None) + if client is None: + client = self._new_client() + setattr(loop, _LOOP_CLIENT_ATTR, client) + return client + + def __getattr__(self, name: str) -> Any: + return getattr(self._client(), name) + + +def __get_async_cache() -> AsyncRedis: + if IS_PYTEST_RUN: + return cast(AsyncRedis, _PerLoopFakeAsyncRedis(_fake_server)) # A separate client that auto-decodes responses is needed client = AsyncRedis.from_url(REDIS_URL, decode_responses=True) diff --git a/backend/tests/endpoints/roms/test_notes.py b/backend/tests/endpoints/roms/test_notes.py index f2f669969..bfc6c12bc 100644 --- a/backend/tests/endpoints/roms/test_notes.py +++ b/backend/tests/endpoints/roms/test_notes.py @@ -1,4 +1,4 @@ -"""Author identity on the note responses, which no note row stores itself.""" +"""Note responses: author identity, deletion and search.""" from fastapi import status from fastapi.testclient import TestClient @@ -58,3 +58,25 @@ def test_delete_note_removes_it_once(client: TestClient, access_token: str, rom: # Nothing left to match, so the handler reports no rows deleted. again = client.delete(url, headers=_auth(access_token)) assert again.status_code == status.HTTP_404_NOT_FOUND + + +def test_note_search_matches_wildcards_literally( + client: TestClient, access_token: str, rom: Rom +): + for title in ("100% run", "1000 coins"): + client.post( + f"/api/roms/{rom.id}/notes", + headers=_auth(access_token), + json={"title": title, "content": "", "is_public": False}, + ) + + def search(term: str) -> list[str]: + listed = client.get( + f"/api/roms/{rom.id}/notes", + headers=_auth(access_token), + params={"search": term}, + ) + return sorted(n["title"] for n in listed.json()) + + assert search("100%") == ["100% run"] + assert search("1_0") == [] diff --git a/backend/tests/endpoints/test_audit_events.py b/backend/tests/endpoints/test_audit_events.py index 4057b497b..9726f504d 100644 --- a/backend/tests/endpoints/test_audit_events.py +++ b/backend/tests/endpoints/test_audit_events.py @@ -2,6 +2,7 @@ from datetime import datetime, timedelta, timezone from typing import Any from fastapi import status +from fastapi.testclient import TestClient from handler.auth import oauth_handler from handler.database import db_audit_event_handler, db_user_handler @@ -189,6 +190,26 @@ class TestFilters: assert _ids(target) == [zelda.id] assert _ids(address) == [from_lan.id] + def test_search_matches_wildcards_literally( + self, client: TestClient, access_token: str + ): + full_run = _add(None, target_name="100% run") + _add(None, target_name="1000 coins") + + percent = client.get( + "/api/audit-events", + params={"search": "100%"}, + headers=_auth(access_token), + ) + underscore = client.get( + "/api/audit-events", + params={"search": "1_0"}, + headers=_auth(access_token), + ) + + assert _ids(percent) == [full_run.id] + assert _ids(underscore) == [] + def test_pages_stay_pinned_to_max_id(self, client, access_token, admin_user): newest = _add(admin_user, minutes_ago=1) # Recorded after `newest` but happened before it, like a synced play. diff --git a/backend/tests/endpoints/test_music.py b/backend/tests/endpoints/test_music.py index 83a2aa6e5..a5675092a 100644 --- a/backend/tests/endpoints/test_music.py +++ b/backend/tests/endpoints/test_music.py @@ -296,6 +296,31 @@ def test_facet_years_typeahead(client: TestClient, access_token: str, music_libr assert {i["value"] for i in body["items"]} == {1991, 1992} +@pytest.mark.parametrize( + ("path", "key", "wildcard", "literal", "expected"), + [ + ("/api/music/artists", "value", "k_shiro", "oshi", {"Koshiro"}), + ("/api/music/years", "value", "19_1", "991", {1991}), + ("/api/music/platforms", "name", "g_nesis", "enes", {"genesis"}), + ("/api/music/games", "name", "s_nic", "oni", {"Sonic"}), + ], +) +def test_facet_search_matches_wildcards_literally( + client: TestClient, + access_token: str, + music_library: dict[str, Platform | Rom], + path: str, + key: str, + wildcard: str, + literal: str, + expected: set[str | int], +): + wild = client.get(path, params={"search": wildcard}, headers=_auth(access_token)) + assert wild.json()["total"] == 0 + found = client.get(path, params={"search": literal}, headers=_auth(access_token)) + assert {i[key] for i in found.json()["items"]} == expected + + @pytest.mark.parametrize( "path", ["/api/roms", "/api/music/tracks", "/api/music/artists"] ) diff --git a/backend/tests/handler/database/test_roms_fulltext_search.py b/backend/tests/handler/database/test_roms_fulltext_search.py new file mode 100644 index 000000000..c459152f8 --- /dev/null +++ b/backend/tests/handler/database/test_roms_fulltext_search.py @@ -0,0 +1,39 @@ +from unittest.mock import patch + +import pytest +from sqlalchemy import select +from sqlalchemy.engine import Dialect +from tests.sql_dialects import MARIADB_DIALECT, POSTGRESQL_DIALECT, compile_sql + +from handler.database import db_rom_handler, roms_handler +from models.rom import Rom +from utils.fulltext import DEFAULT_FULLTEXT_SETTINGS + + +@pytest.mark.parametrize( + ("dialect", "like_count", "has_match"), + [(MARIADB_DIALECT, 3, True), (POSTGRESQL_DIALECT, 9, False)], +) +def test_search_keeps_the_fulltext_index_for_indexable_words( + dialect: Dialect, like_count: int, has_match: bool +): + with patch.object( + roms_handler, "fulltext_settings", return_value=DEFAULT_FULLTEXT_SETTINGS + ): + query = db_rom_handler._filter_by_search_term(select(Rom.id), "final fantasy 7") + + sql = compile_sql(query, dialect, literal_binds=True) + + assert ("AGAINST ('+final* +fantasy*' IN BOOLEAN MODE)" in sql) is has_match + # MariaDB checks only "7" by LIKE; PostgreSQL checks every word. + assert sql.count("LIKE") == like_count + + +def test_search_uses_like_alone_while_the_settings_are_unreadable(): + with patch.object(roms_handler, "fulltext_settings", return_value=None): + query = db_rom_handler._filter_by_search_term(select(Rom.id), "final fantasy") + + sql = compile_sql(query, MARIADB_DIALECT, literal_binds=True) + + assert "+final*" not in sql + assert sql.count("LIKE") == 6 diff --git a/backend/tests/handler/database/test_roms_handler.py b/backend/tests/handler/database/test_roms_handler.py index 6f0360b9c..c3ba78035 100644 --- a/backend/tests/handler/database/test_roms_handler.py +++ b/backend/tests/handler/database/test_roms_handler.py @@ -19,6 +19,7 @@ from tests.factories import make_rom, make_save, make_state from tests.sql_dialects import MARIADB_DIALECT, POSTGRESQL_DIALECT, compile_sql from decorators.database import INJECTED_SESSION +from exceptions.database_exceptions import RomFileOwnerChangedError from handler.database import db_platform_handler, db_rom_handler from handler.database.base_handler import sync_engine, sync_session from handler.database.roms_handler import _filter_values_cache_version @@ -673,6 +674,35 @@ class TestRomFileSizeTotal: assert self._size(rom) == 1000 + def test_moving_a_file_updates_both_roms(self, rom: Rom, second_rom: Rom): + _add_rom_file(rom, "game.bin", 1000, RomFileCategory.GAME) + manual = _add_rom_file(rom, "manual.pdf", 200, RomFileCategory.MANUAL) + + db_rom_handler.update_rom_file(manual.id, {"rom_id": second_rom.id}) + + assert self._size(rom) == 1000 + assert self._size(second_rom) == 200 + + def test_merging_a_file_under_another_rom_updates_both( + self, rom: Rom, second_rom: Rom + ): + _add_rom_file(rom, "game.bin", 1000, RomFileCategory.GAME) + manual = _add_rom_file(rom, "manual.pdf", 200, RomFileCategory.MANUAL) + + db_rom_handler.add_rom_file( + RomFile( + id=manual.id, + rom_id=second_rom.id, + file_name=manual.file_name, + file_path=second_rom.fs_path, + file_size_bytes=manual.file_size_bytes, + category=manual.category, + ) + ) + + assert self._size(rom) == 1000 + assert self._size(second_rom) == 200 + class TestRomFileSizeSidecarInvalidation: """The size-sorted rom-id and char indexes are cached under the filter @@ -787,6 +817,53 @@ class TestRomFileSizeLocking: self._assert_locked_before(statements, "UPDATE rom_files") + def test_move_locks_its_roms_before_the_file( + self, rom: Rom, second_rom: Rom, statements: list[str] + ): + # Folder conversion writes the rom row before its file rows, so file + # writes lock in the same order. + game = _add_rom_file(rom) + statements.clear() + + db_rom_handler.update_rom_file(game.id, {"rom_id": second_rom.id}) + + file_lock = next( + i + for i, s in enumerate(statements) + if s.startswith("SELECT rom_files.rom_id") and s.endswith("FOR UPDATE") + ) + rom_locks = [ + i + for i, s in enumerate(statements) + if s.startswith("SELECT roms.id") and re.search(r"FOR (NO KEY )?UPDATE$", s) + ] + assert len(rom_locks) == 2 + assert max(rom_locks) < file_lock + + def test_an_owner_changed_meanwhile_fails_the_write(self): + session = MagicMock() + # The file moved from rom 1 to rom 2 before this transaction locked rom 1. + session.scalar.side_effect = [1, 2] + + with pytest.raises(RomFileOwnerChangedError): + db_rom_handler._lock_rom_file_and_roms(10, [3], session) + + def test_a_move_into_a_locked_rom_needs_no_more_locks(self): + session = MagicMock() + session.scalar.side_effect = [1, 3] + + locked = db_rom_handler._lock_rom_file_and_roms(10, [3], session) + + assert locked == {1, 3} + assert session.execute.call_count == 2 + + def test_a_vanished_file_locks_nothing_more(self): + session = MagicMock() + session.scalar.side_effect = [None] + + assert db_rom_handler._lock_rom_file_and_roms(10, [3], session) is None + session.execute.assert_not_called() + @pytest.mark.parametrize( ("dialect", "clause"), [(MARIADB_DIALECT, "FOR UPDATE"), (POSTGRESQL_DIALECT, "FOR NO KEY UPDATE")], @@ -795,7 +872,20 @@ class TestRomFileSizeLocking: # NO KEY UPDATE leaves other tables' foreign key checks on the row free. session = MagicMock() - db_rom_handler._lock_rom_row(7, session) + db_rom_handler._lock_rom_rows([7], session) (statement,) = session.execute.call_args.args assert compile_sql(statement, dialect).endswith(clause) + + def test_move_locks_both_roms_in_id_order(self, rom: Rom, second_rom: Rom): + # Two opposite moves take the locks in the same order, so they cannot + # deadlock. + session = MagicMock() + + db_rom_handler._lock_rom_rows([second_rom.id, rom.id, second_rom.id], session) + + locked = [ + call.args[0].compile().params["id_1"] + for call in session.execute.call_args_list + ] + assert locked == sorted({rom.id, second_rom.id}) diff --git a/backend/tests/handler/database/test_roms_metadata_sort.py b/backend/tests/handler/database/test_roms_metadata_sort.py index 8c7e7e9b9..807856e47 100644 --- a/backend/tests/handler/database/test_roms_metadata_sort.py +++ b/backend/tests/handler/database/test_roms_metadata_sort.py @@ -148,19 +148,21 @@ class TestMetadataSortQueryShape: ( POSTGRESQL_DIALECT, "asc", - "roms.generated_player_count ASC NULLS LAST, roms.id ASC", + "roms.generated_player_count ASC NULLS LAST, " + "CASE WHEN ((roms.name ILIKE", ), ( POSTGRESQL_DIALECT, "desc", - "roms.generated_player_count DESC NULLS LAST, roms.id DESC", + "roms.generated_player_count DESC NULLS LAST, " + "CASE WHEN ((roms.name ILIKE", ), ], ) def test_search_relevance_follows_the_null_placement_terms( self, dialect: sa.Dialect, order_dir: str, expected: str ): - """Relevance only ranks on the FULLTEXT engines, after the explicit sort.""" + """Relevance ranks after the explicit sort, on every engine.""" query, _ = db_rom_handler.get_roms_query( order_by="player_count", order_dir=order_dir, search_term="final fantasy" ) diff --git a/backend/tests/handler/test_db_handler.py b/backend/tests/handler/test_db_handler.py index b5e0f9b19..c2f2c19ca 100644 --- a/backend/tests/handler/test_db_handler.py +++ b/backend/tests/handler/test_db_handler.py @@ -7,7 +7,6 @@ from sqlalchemy import inspect as sa_inspect from sqlalchemy.exc import IntegrityError from tests.factories import make_rom, make_save, make_screenshot, make_state -from config import ROMM_DB_DRIVER from handler.auth import auth_handler from handler.database import ( db_platform_handler, @@ -232,20 +231,19 @@ def test_filter_by_search_term_multi_word_and_ranking(platform: Platform): # Only titles containing BOTH words appear (AND semantics). assert set(result_ids) == {ff.id, ff7.id, fantasy_final.id} - # Relevance ordering uses MATCH ... AGAINST, which only runs on - # MySQL/MariaDB; PostgreSQL falls back to name ordering, so the - # phrase-ranking assertions only hold on those drivers. - if ROMM_DB_DRIVER in ("mariadb", "mysql"): - # Exact-order phrase matches rank above the reversed-order match. - assert result_ids.index(ff.id) < result_ids.index(fantasy_final.id) - assert result_ids.index(ff7.id) < result_ids.index(fantasy_final.id) + # Exact-order phrase matches rank above the reversed-order match. + assert result_ids.index(ff.id) < result_ids.index(fantasy_final.id) + assert result_ids.index(ff7.id) < result_ids.index(fantasy_final.id) # The relevance ORDER BY must also survive the group_by_meta_id subquery # wrapping used by the gallery (each ROM here is its own group). grouped = db_rom_handler.get_roms_scalar( search_term="final fantasy", group_by_meta_id=True ) - assert {r.id for r in grouped} == {ff.id, ff7.id, fantasy_final.id} + grouped_ids = [r.id for r in grouped] + assert set(grouped_ids) == {ff.id, ff7.id, fantasy_final.id} + assert grouped_ids.index(ff.id) < grouped_ids.index(fantasy_final.id) + assert grouped_ids.index(ff7.id) < grouped_ids.index(fantasy_final.id) # An explicit sort takes priority over relevance: ordering by name asc puts # "Fantasy Final" first (relevance is only the tiebreaker here). @@ -256,6 +254,41 @@ def test_filter_by_search_term_multi_word_and_ranking(platform: Platform): assert explicit_ids.index(fantasy_final.id) < explicit_ids.index(ff.id) +@pytest.mark.parametrize( + ("search_term", "expected"), + [ + # "7" is too short for the FULLTEXT index. + ("final fantasy 7", {"Final Fantasy 7"}), + # "the" is an InnoDB stopword, "of" both short and a stopword. + ("the legend zelda", {"The Legend of Zelda"}), + ("legend of zelda", {"The Legend of Zelda"}), + # No word the index holds, so LIKE alone decides. + ("x-2", {"Final Fantasy X-2"}), + # The index holds "dr." as "dr", too short to require. + ("dr. mario", {"Dr. Mario"}), + # `_` is literal, not a LIKE wildcard. + ("x_2", set()), + ], +) +def test_filter_by_search_term_words_fulltext_cannot_index( + platform: Platform, search_term: str, expected: set[str] +): + for name in ( + "Final Fantasy 7", + "Final Fantasy X-2", + "Final Fantasy", + "Dr. Mario", + "The Legend of Zelda", + "Zelda II The Adventure of Link", + ): + # Spaced like a real dump, so the filename splits into the same words. + make_rom(platform, name, fs_stem=f"{name} (USA)") + + results = db_rom_handler.get_roms_scalar(search_term=search_term) + + assert {r.name for r in results} == expected + + def test_sibling_roms_empty_fs_name_no_tags_not_matched(platform: Platform): """ROMs with empty fs_name_no_tags should NOT be matched as siblings. diff --git a/backend/tests/handler/test_redis_handler.py b/backend/tests/handler/test_redis_handler.py index 3e2dc0804..ff14d6037 100644 --- a/backend/tests/handler/test_redis_handler.py +++ b/backend/tests/handler/test_redis_handler.py @@ -1,3 +1,6 @@ +import asyncio +import threading +from typing import Any from unittest.mock import MagicMock, PropertyMock, patch import pytest @@ -6,6 +9,7 @@ from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobEr from rq.job import Job, JobStatus from handler.redis_handler import ( + async_cache, cancel_job, get_job_func_name, get_job_kwargs, @@ -147,3 +151,34 @@ class TestHasLiveWorker: assert has_live_worker(low_prio_queue) is expected mock_all.assert_called_once_with(queue=low_prio_queue) + + +class TestAsyncCacheUnderTests: + def test_concurrent_threads_and_loops_never_share_a_pool(self): + """The TestClient's loop and a test's asyncio.run overlap across threads.""" + + async def running_loop_pool() -> Any: + return async_cache.connection_pool + + pools: dict[str, Any] = {} + + def other_thread() -> None: + pools["other thread, no loop"] = async_cache.connection_pool + pools["other thread, in a loop"] = asyncio.run(running_loop_pool()) + + thread = threading.Thread(target=other_thread) + thread.start() + thread.join() + pools["this thread, no loop"] = async_cache.connection_pool + pools["this thread, in a loop"] = asyncio.run(running_loop_pool()) + + assert len({id(pool) for pool in pools.values()}) == len(pools) + + def test_every_client_reads_the_one_keyspace(self): + async def read() -> Any: + return await async_cache.get("per-loop") + + asyncio.run(async_cache.set("per-loop", "1")) + value = asyncio.run(read()) + + assert value in ("1", b"1") diff --git a/backend/tests/utils/test_fulltext.py b/backend/tests/utils/test_fulltext.py new file mode 100644 index 000000000..642f3c90c --- /dev/null +++ b/backend/tests/utils/test_fulltext.py @@ -0,0 +1,146 @@ +from collections.abc import Iterator +from unittest.mock import MagicMock + +import pytest +from sqlalchemy import text +from sqlalchemy.exc import OperationalError + +from handler.database.base_handler import sync_engine +from utils import fulltext +from utils.database import is_postgresql +from utils.fulltext import ( + DEFAULT_FULLTEXT_SETTINGS, + FulltextSettings, + fulltext_settings, + read_fulltext_settings, + split_fulltext_words, +) + +IS_FULLTEXT_ENGINE = not is_postgresql(sync_engine) + + +@pytest.fixture(autouse=True) +def fresh_settings() -> Iterator[None]: + fulltext._server_fulltext_settings.cache_clear() + yield + fulltext._server_fulltext_settings.cache_clear() + + +def _conn_reporting( + min_token_size: int = 3, + *, + stopwords_enabled: bool = True, + user_table: str | None = None, + server_table: str | None = None, +) -> MagicMock: + conn = MagicMock() + conn.execute.return_value.one.return_value = ( + min_token_size, + 84, + int(stopwords_enabled), + user_table, + server_table, + ) + conn.scalars.return_value = ["Foo", "bar", None] + return conn + + +def _engine_connecting(conn: MagicMock) -> MagicMock: + engine = MagicMock() + engine.engine.name = "mariadb" + engine.connect.return_value.__enter__.return_value = conn + return engine + + +@pytest.mark.skipif(not IS_FULLTEXT_ENGINE, reason="InnoDB full-text only") +def test_reads_the_servers_settings(): + with sync_engine.connect() as conn: + min_token_size = conn.execute( + text("SELECT @@innodb_ft_min_token_size") + ).scalar_one() + settings = read_fulltext_settings(conn) + + assert settings.min_token_size == min_token_size + assert "the" in settings.stopwords + + +@pytest.mark.skipif(IS_FULLTEXT_ENGINE, reason="PostgreSQL has no FULLTEXT index") +def test_postgresql_uses_the_defaults(): + assert fulltext_settings(sync_engine) == DEFAULT_FULLTEXT_SETTINGS + + +def test_skips_fulltext_and_retries_when_the_server_is_unreachable(): + engine = _engine_connecting(MagicMock()) + engine.connect.side_effect = OperationalError("SELECT", {}, Exception("2013")) + + assert fulltext_settings(engine) is None + assert fulltext_settings(engine) is None + + assert engine.connect.call_count == 2 + + +def test_keeps_the_token_sizes_when_the_stopwords_are_unreadable(): + conn = _conn_reporting(4) + conn.scalars.side_effect = OperationalError("SELECT", {}, Exception("1227")) + + assert read_fulltext_settings(conn) == DEFAULT_FULLTEXT_SETTINGS._replace( + min_token_size=4 + ) + + +def test_reads_a_custom_stopword_table(): + conn = _conn_reporting(2, server_table="romm/stopwords") + + settings = read_fulltext_settings(conn) + + query = conn.scalars.call_args.args[0] + assert "FROM romm.stopwords" in str(query) + assert settings == FulltextSettings(2, 84, frozenset({"foo", "bar"})) + + +def test_prefers_the_user_stopword_table(): + conn = _conn_reporting(user_table="romm/mine", server_table="romm/stopwords") + + read_fulltext_settings(conn) + + assert "FROM romm.mine" in str(conn.scalars.call_args.args[0]) + + +def test_unreadable_custom_stopwords_skip_fulltext_and_retry(): + conn = _conn_reporting(server_table="romm/stopwords") + conn.scalars.side_effect = OperationalError("SELECT", {}, Exception("1142")) + + engine = _engine_connecting(conn) + + assert fulltext_settings(engine) is None + assert fulltext_settings(engine) is None + assert conn.scalars.call_count == 2 + + +def test_disabled_stopwords_leave_none(): + conn = _conn_reporting(stopwords_enabled=False) + + assert read_fulltext_settings(conn) == FulltextSettings(3, 84, frozenset()) + + +@pytest.mark.parametrize( + ("term", "expected"), + [ + ("final fantasy 7", (["final", "fantasy"], ["7"])), + ("the legend", (["legend"], ["the"])), + # InnoDB reads "dr." as the 2-letter token "dr". + ("dr. mario", (["mario"], ["dr."])), + ("pokemon: red", (["pokemon", "red"], [])), + ("spider-man x-2", (["spider", "man"], ["x-2"])), + ("mario's", (["mario's"], [])), + ("a" * 85, ([], ["a" * 85])), + ], +) +def test_split_fulltext_words(term: str, expected: tuple[list[str], list[str]]): + assert split_fulltext_words(term.split(), DEFAULT_FULLTEXT_SETTINGS) == expected + + +def test_split_fulltext_words_follows_the_token_size(): + settings = DEFAULT_FULLTEXT_SETTINGS._replace(min_token_size=2) + + assert split_fulltext_words(["ff", "of"], settings) == (["ff"], ["of"]) diff --git a/backend/tools/generate_test_data.py b/backend/tools/generate_test_data.py index 82065fe0d..3aeb51682 100644 --- a/backend/tools/generate_test_data.py +++ b/backend/tools/generate_test_data.py @@ -22,6 +22,7 @@ import os import random import sys import time +from collections.abc import Iterable from datetime import datetime, timedelta, timezone from typing import Any @@ -830,19 +831,23 @@ def main() -> int: from handler.auth import auth_handler from handler.database.base_handler import sync_engine + from utils.database import is_postgresql # Pin every connection to UTC so the random historical timestamps we # generate never land in a local DST gap that TIMESTAMP columns reject. + postgresql = is_postgresql(sync_engine) + @event.listens_for(sync_engine, "connect") def _session_utc(dbapi_conn: DBAPIConnection, _record: ConnectionPoolEntry) -> None: cur = dbapi_conn.cursor() try: - try: - cur.execute("SET time_zone = '+00:00'") # MySQL/MariaDB - except Exception: - cur.execute("SET TIME ZONE 'UTC'") # PostgreSQL + cur.execute( + "SET TIME ZONE 'UTC'" if postgresql else "SET time_zone = '+00:00'" + ) finally: cur.close() + # PostgreSQL's SET is transactional: the pool's rollback on return would undo it. + dbapi_conn.commit() pw_hash = auth_handler.get_password_hash(args.password) @@ -1028,6 +1033,8 @@ def main() -> int: bulk_insert(conn, Device, device_rows) bulk_insert(conn, ClientToken, token_rows) bulk_insert(conn, Firmware, firmware_rows) + if postgresql: + _advance_sequences(conn, (Platform, User, ClientToken, Firmware)) counts["platforms"] = len(platform_rows) counts["users"] = len(user_rows) counts["devices"] = len(device_rows) @@ -1447,6 +1454,10 @@ def main() -> int: bulk_insert(conn, Screenshot, shot_rows) bulk_insert(conn, RomNote, note_rows) bulk_insert(conn, DeviceSaveSync, dss_rows) + if postgresql: + _advance_sequences( + conn, (Rom, RomFile, RomUser, Save, State, Screenshot, RomNote) + ) counts["roms"] += len(rom_rows) counts["rom_files"] += len(file_rows) @@ -1576,6 +1587,10 @@ def main() -> int: bulk_insert(conn, SmartCollection, smart_rows) bulk_insert(conn, SyncSession, sync_rows) bulk_insert(conn, PlaySession, play_rows) + if postgresql: + _advance_sequences( + conn, (Collection, SmartCollection, SyncSession, PlaySession) + ) counts["collections"] = len(coll_rows) counts["collections_roms"] = len(coll_rom_rows) counts["smart_collections"] = len(smart_rows) @@ -1597,6 +1612,26 @@ def main() -> int: return 0 +def _advance_sequences(conn: Connection, models: Iterable[type[BaseModel]]) -> None: + """Move each PostgreSQL id sequence past the explicit ids inserted here.""" + # Unlike AUTO_INCREMENT, a sequence ignores explicit ids. The sequence's own + # last value keeps this from moving it back past ids the app already drew. + from sqlalchemy import text + + for model in models: + t = model.__tablename__ + # nosec B608 - table names come from the script's own models, not user input + conn.execute( + text( + "SELECT setval(s.seq, GREATEST(" # nosec B608 + f"(SELECT COALESCE(MAX(id), 0) FROM {t})," + " COALESCE(pg_sequence_last_value(s.seq), 0)) + 1, false)" + f" FROM (SELECT CAST(pg_get_serial_sequence('{t}', 'id') AS regclass)" + " AS seq) AS s" + ) + ) + + def _wipe(conn: Connection) -> None: """Delete all rows from the tables this script populates (FK-safe order).""" from sqlalchemy import text diff --git a/backend/utils/database.py b/backend/utils/database.py index f39fb68e5..5b34cac41 100644 --- a/backend/utils/database.py +++ b/backend/utils/database.py @@ -317,18 +317,6 @@ def epoch_ms_in_ranges( ) -LIKE_ESCAPE_CHAR = "\\" - - -def escape_like(term: str) -> str: - """Escape LIKE wildcards so a search term matches literally (pass escape=LIKE_ESCAPE_CHAR to like()).""" - return ( - term.replace(LIKE_ESCAPE_CHAR, LIKE_ESCAPE_CHAR * 2) - .replace("%", f"{LIKE_ESCAPE_CHAR}%") - .replace("_", f"{LIKE_ESCAPE_CHAR}_") - ) - - def safe_str_to_bool(value: Any, default: bool = False) -> bool: """Safely convert a value to bool, returning default if conversion fails.""" try: diff --git a/backend/utils/fulltext.py b/backend/utils/fulltext.py new file mode 100644 index 000000000..51151c23b --- /dev/null +++ b/backend/utils/fulltext.py @@ -0,0 +1,103 @@ +"""InnoDB's full-text settings, and how its parser splits search words.""" + +import functools +import re +from collections.abc import Iterable +from typing import NamedTuple + +from sqlalchemy import Connection, Engine, String +from sqlalchemy import column as sql_column +from sqlalchemy import select +from sqlalchemy import table as sql_table +from sqlalchemy import text +from sqlalchemy.exc import SQLAlchemyError + +from logger.logger import log +from utils.database import is_postgresql + +# The tokens InnoDB's parser reads out of a word: "dr." holds only "dr". +FULLTEXT_TOKEN_REGEX = re.compile(r"\w+(?:'\w+)*") + + +class FulltextSettings(NamedTuple): + min_token_size: int + max_token_size: int + stopwords: frozenset[str] + + +# InnoDB's defaults, for what the server won't report. The index skips +# stopwords, so a required `+the*` would match nothing. +DEFAULT_FULLTEXT_SETTINGS = FulltextSettings( + min_token_size=3, + max_token_size=84, + stopwords=frozenset( + "a about an are as at be by com de en for from how i in is it la of on or" + " that the this to und was what when where who will with www".split() + ), +) + + +def read_fulltext_settings(conn: Connection) -> FulltextSettings: + """The server's InnoDB full-text settings; raises if they can't be read.""" + min_size, max_size, stopwords_enabled, user_table, server_table = conn.execute( + text( + "SELECT @@innodb_ft_min_token_size, @@innodb_ft_max_token_size," + " @@innodb_ft_enable_stopword, @@innodb_ft_user_stopword_table," + " @@innodb_ft_server_stopword_table" + ) + ).one() + stopwords: frozenset[str] = frozenset() + if stopwords_enabled: + custom_table = user_table or server_table + schema, _, name = ( + custom_table or "information_schema/INNODB_FT_DEFAULT_STOPWORD" + ).rpartition("/") + query = select(sql_column("value", String)).select_from( + sql_table(name, schema=schema or None) + ) + try: + stopwords = frozenset(word.lower() for word in conn.scalars(query) if word) + except SQLAlchemyError as exc: + if custom_table: + raise + # MySQL needs PROCESS for INNODB_FT_DEFAULT_STOPWORD, which holds these. + log.warning(f"Using InnoDB's default full-text stopwords: {exc}") + stopwords = DEFAULT_FULLTEXT_SETTINGS.stopwords + return FulltextSettings(int(min_size), int(max_size), stopwords) + + +@functools.cache +def _server_fulltext_settings(engine: Engine) -> FulltextSettings: + with engine.connect() as conn: + return read_fulltext_settings(conn) + + +def fulltext_settings(engine: Engine) -> FulltextSettings | None: + """The server's InnoDB full-text settings, or None while they can't be read.""" + if is_postgresql(engine): + return DEFAULT_FULLTEXT_SETTINGS + try: + return _server_fulltext_settings(engine) + except SQLAlchemyError as exc: + # Left uncached, so a transient failure is retried on the next search. + log.warning(f"Can't read the full-text settings: {exc}") + return None + + +def split_fulltext_words( + words: Iterable[str], settings: FulltextSettings +) -> tuple[list[str], list[str]]: + """Words as (tokens a FULLTEXT index holds, words it can't hold).""" + indexed: list[str] = [] + unindexed: list[str] = [] + for word in words: + tokens = FULLTEXT_TOKEN_REGEX.findall(word) + if tokens and all( + settings.min_token_size <= len(token) <= settings.max_token_size + and token.lower() not in settings.stopwords + for token in tokens + ): + indexed.extend(tokens) + else: + unindexed.append(word) + return indexed, unindexed diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index f37217f53..519266b9e 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -439,6 +439,10 @@ Query SQL that differs between engines lives in `utils/sql_dialect.py` (`DialectCase` and the helpers built on it), which picks each engine's spelling when the statement compiles. Handlers don't branch on `ROMM_DB_DRIVER`. +`utils/fulltext.py` reads InnoDB's full-text token sizes and stopwords from the +server and splits search words the way its parser does, so a search can require +the words a FULLTEXT index holds and check the rest with `LIKE`. + ### Engine & Session Setup **Location:** `handler/database/base_handler.py` diff --git a/frontend/src/RomM.vue b/frontend/src/RomM.vue index 609177f9d..c619c5064 100644 --- a/frontend/src/RomM.vue +++ b/frontend/src/RomM.vue @@ -117,7 +117,7 @@ watch(