Files
romm/backend/handler/database/base_handler.py
alexcastgonz 81b617459b fix(db): bump client token and device last-used timestamps without a prior read (#5384)
* fix(db): bump client token and device last-used timestamps without a prior read

update_last_used() and update_last_seen_debounced() read the row with
session.get() and then updated it in the same transaction. When two requests
with the same Client API Token ran concurrently and both passed the debounce
check, the second UPDATE hit MariaDB error 1020 (Record has changed since last
read), so a read-only GET returned HTTP 500. Make each a single conditional
UPDATE that only touches the row when the debounce window has passed.

Fixes #5379

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test(db): code-review fixes for last-used race tests

Reuse the executed_statements fixture, scope race listeners to
sync_engine, add the device race test, drop an unused fixture, and
apply trunk fmt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(db): simplify pass on last-used race fix

Share the race hook as tests/db_race_stubs.run_before_first, look tokens
up by id in tests, trim duplicated docstrings, and state the handler
comment as current behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(db): humanizer pass on last-used handler comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(db): run MariaDB and MySQL sessions at READ COMMITTED

MariaDB 11.6+ turns on innodb_snapshot_isolation, so at REPEATABLE READ any
transaction that reads a row and then writes it fails with error 1020
("Record has changed since last read") when another transaction committed
to that row in between. READ COMMITTED, PostgreSQL's default, takes a fresh
snapshot per statement and removes the whole class of failures.

A server logging binlog_format=STATEMENT refuses InnoDB writes below
REPEATABLE READ, so its sessions keep the default and log a warning once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(auth): skip last-used and last-active writes inside the debounce window

Client-token auth bumped the token, the device and the user on every
request, the user with an undebounced UPDATE plus a re-SELECT. The token's
loaded last_used_at now gates the token and device bumps, and
set_last_active checks the loaded last_active and bumps through a
debounced conditional UPDATE, so a request inside the window writes
nothing and takes no row lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-29 12:23:31 -04:00

100 lines
3.3 KiB
Python

import functools
import logging
import time
from typing import Any, cast
from sqlalchemy import Connection, CursorResult, Result, create_engine, event
from sqlalchemy.orm import sessionmaker
from config import DB_POOL_RECYCLE_SECONDS, DEV_SQL_ECHO
from config.config_manager import ConfigManager
from logger.logger import log
from models import load_all_models
# A ping on a socket the server already closed blocks the worker until TCP gives
# up, so `pool_pre_ping` alone is not enough.
sync_engine = create_engine(
ConfigManager.get_db_engine(),
pool_pre_ping=True,
pool_recycle=DB_POOL_RECYCLE_SECONDS,
echo=False,
)
sync_session = sessionmaker(bind=sync_engine, expire_on_commit=False)
@functools.cache
def _warn_statement_binlog() -> None:
log.warning(
"binlog_format is STATEMENT, so database sessions stay at REPEATABLE READ; "
"concurrent writes may fail with 'Record has changed since last read'"
)
def read_committed(dbapi_connection: Any, connection_record: Any) -> None:
"""Run the session at READ COMMITTED, unless statement binary logging forbids it."""
cursor = dbapi_connection.cursor()
try:
cursor.execute("SELECT @@log_bin, @@binlog_format")
log_bin, binlog_format = cursor.fetchone()
# InnoDB refuses every write below REPEATABLE READ under STATEMENT logging.
if log_bin and binlog_format == "STATEMENT":
_warn_statement_binlog()
else:
cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
finally:
cursor.close()
dbapi_connection.commit()
# MariaDB 11.6+ at REPEATABLE READ fails a write to a row the transaction read
# before another one committed to it (error 1020). PostgreSQL defaults to this.
if sync_engine.dialect.name in ("mariadb", "mysql"):
event.listen(sync_engine, "connect", read_committed)
# Disable SQLAlchemy logging as echo will print the queries
logging.getLogger("sqlalchemy.engine.Engine").handlers = [logging.NullHandler()]
if DEV_SQL_ECHO:
@event.listens_for(sync_engine, "before_cursor_execute")
def before_cursor_execute(
conn: Connection,
cursor: Any,
statement: str,
parameters: Any,
context: Any,
executemany: bool,
) -> None:
context._query_start_time = time.time()
print("--------START--------")
print(f"SQL: {statement}")
print(f"Parameters: {parameters}")
@event.listens_for(sync_engine, "after_cursor_execute")
def after_cursor_execute(
conn: Connection,
cursor: Any,
statement: str,
parameters: Any,
context: Any,
executemany: bool,
) -> None:
total_time = time.time() - context._query_start_time
print(f"Execution time: {total_time:.4f} seconds")
print("--------END--------")
class DBBaseHandler: ...
def affected_rows(result: Result[*tuple[Any, ...]]) -> int:
"""How many rows an UPDATE or DELETE run through `Session.execute` matched."""
# Session.execute is typed to return Result, but DML gets a CursorResult.
return cast(CursorResult[*tuple[Any, ...]], result).rowcount
# A process may load one model, whose relationships name others by string, and
# the mappers configure only once every one of them is loaded.
load_all_models()