Files
romm/backend/decorators/database.py
Zach Clendenen b1f4ac4888 fix(db): keep iterated query results away from the cyclic GC (#5068)
* fix(roms): read filter values with .all() so the GC never frees the cursor

Looping over the filter-values Result directly makes SQLAlchemy 2.1 memoize
an iterator closure that captures the Result, which puts the CursorResult,
its execution context and the mariadb cursor in a reference cycle. The
cyclic GC then frees them on whatever thread triggers a collection, and
under concurrent gallery requests that segfaults the mariadb connector
(1.1.14, Python 3.14) inside the pool checkout. .all() never builds that
closure, so nothing is left for the GC.

* fix(roms): address pr-ready code review

* style(roms): pr-ready polish

* fix(db): read every iterated query result with .all()

The same reference cycle that segfaulted the filter values also hits smart
collection matching on every save, the screenshot binding check, playlist and
favourite adds, the recommendation reads and the stopword probe. The IGDB
related-games stream keeps yield_per and closes its Result with a with block.
A source scan test now fails on any Result iterated directly.

* fix(roms): address Greptile review

Keep gc.garbage entries that predate the filter-values cursor test: only the
objects this test collects are inspected and removed, so a runner that already
saves garbage keeps its list intact (Greptile, test_rom_facets.py).

* pr-ready: code-review fixes

Keep a generator's begin_session open until it finishes, read the
streamed IGDB scan by partition, and widen the iterated-Result guard to
names, unpacking, yield from and iterating methods.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* pr-ready: simplify

Share the app-source AST scan between the two guard tests, fold the
generator session's two branches into one nullcontext, and drop the
call-site comment the guard test already carries.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(db): flag iterated legacy session.query() results

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-03 10:06:49 -04:00

58 lines
1.8 KiB
Python

import functools
import inspect
from collections.abc import Callable, Iterator
from contextlib import nullcontext
from typing import Any, cast
from fastapi import HTTPException, status
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.orm import Session
from handler.database.base_handler import sync_session
from logger.logger import log
# Default for a `session` parameter that begin_session fills before the body runs.
INJECTED_SESSION = cast(Session, None)
def begin_session[**P, R](func: Callable[P, R]) -> Callable[P, R]:
if inspect.isgeneratorfunction(func):
return cast(Callable[P, R], _begin_generator_session(func))
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
# Reuse a caller-provided session so the handler can join an existing unit of work
if kwargs.get("session") is not None:
return func(*args, **kwargs)
try:
with sync_session.begin() as s:
kwargs["session"] = s
return func(*args, **kwargs)
except ProgrammingError as exc:
log.critical(str(exc))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)
) from exc
return wrapper
def _begin_generator_session[**P](
func: Callable[P, Iterator[Any]],
) -> Callable[P, Iterator[Any]]:
"""begin_session for a generator, whose session must outlive the first call."""
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Iterator[Any]:
caller_session = kwargs.get("session")
with (
nullcontext(caller_session)
if caller_session is not None
else sync_session.begin()
) as s:
kwargs["session"] = s
yield from func(*args, **kwargs)
return wrapper