Files
romm/backend/tests/handler/database/test_buffered_results.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

131 lines
4.0 KiB
Python

import ast
from tests.app_sources import app_sources
RESULT_METHODS = {"execute", "query", "scalars"}
RESULT_VIEWS = {"scalars", "mappings", "tuples", "unique", "columns"}
# Builders a legacy `session.query(...)` chains through before it is iterated.
QUERY_BUILDERS = {
"distinct",
"execution_options",
"filter",
"filter_by",
"group_by",
"join",
"limit",
"offset",
"options",
"order_by",
"outerjoin",
"where",
"yield_per",
}
CONSUMERS = {
"all",
"any",
"dict",
"enumerate",
"filter",
"frozenset",
"iter",
"list",
"map",
"max",
"min",
"next",
"set",
"sorted",
"sum",
"tuple",
"zip",
}
# Methods that iterate their argument, as in `ids.update(session.scalars(...))`.
ITERATING_METHODS = {"extend", "join", "union", "update"}
type Parents = dict[ast.AST, ast.AST]
def _view_root(node: ast.AST, parents: Parents) -> ast.AST:
"""The outermost `.scalars()`-like view or Query builder chained onto `node`."""
while (
isinstance(attr := parents.get(node), ast.Attribute)
and attr.attr in RESULT_VIEWS | QUERY_BUILDERS
and isinstance(call := parents.get(attr), ast.Call)
):
node = call
return node
def _is_iterated(node: ast.AST, parents: Parents) -> bool:
parent = parents.get(node)
if isinstance(parent, (ast.For, ast.comprehension)):
return parent.iter is node
if isinstance(parent, (ast.YieldFrom, ast.Starred)):
return True
if isinstance(parent, ast.Assign):
return any(isinstance(t, (ast.Tuple, ast.List)) for t in parent.targets)
if isinstance(parent, ast.Call) and node in parent.args:
func = parent.func
return (isinstance(func, ast.Name) and func.id in CONSUMERS) or (
isinstance(func, ast.Attribute) and func.attr in ITERATING_METHODS
)
return False
def _bound_name(node: ast.AST, parents: Parents) -> str | None:
"""The name `node` is bound to by `with ... as name` or an assignment."""
parent = parents.get(node)
target: ast.AST | None = None
if isinstance(parent, ast.withitem):
target = parent.optional_vars
elif isinstance(parent, ast.Assign) and len(parent.targets) == 1:
target = parent.targets[0]
elif isinstance(parent, (ast.AnnAssign, ast.NamedExpr)):
target = parent.target
return target.id if isinstance(target, ast.Name) else None
def _scope(node: ast.AST, parents: Parents) -> ast.AST:
while not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Module)):
node = parents[node]
return node
def _iterated_results(tree: ast.AST) -> list[int]:
"""Lines where a query Result is iterated, directly or through a name."""
parents = {
child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)
}
lines = []
for node in ast.walk(tree):
if not (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Attribute)
and node.func.attr in RESULT_METHODS
and node.args
):
continue
outer = _view_root(node, parents)
if _is_iterated(outer, parents):
lines.append(node.lineno)
elif name := _bound_name(outer, parents):
if any(
isinstance(use, ast.Name)
and use.id == name
and isinstance(use.ctx, ast.Load)
and _is_iterated(_view_root(use, parents), parents)
for use in ast.walk(_scope(outer, parents))
):
lines.append(node.lineno)
return lines
def test_query_results_are_not_left_for_the_gc():
# An iterated Result sits in a cycle the GC frees on another thread, segfaulting
# mariadb. Closing it only helps ORM results; `.all()`/`.partitions()` make none.
offenders = []
for relative, tree in app_sources():
offenders += [f"{relative}:{line}" for line in _iterated_results(tree)]
assert offenders == []