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

168 lines
5.9 KiB
Python

from datetime import datetime, timedelta, timezone
from tests.db_race_stubs import run_before_first
from handler.database import db_device_handler
from models.device import Device
from models.user import User
from utils.datetime import to_utc
class TestGetDeviceByClientIdentifier:
def test_returns_device_for_matching_user_and_identifier(self, admin_user: User):
db_device_handler.add_device(
Device(
id="cid-device-1",
user_id=admin_user.id,
name="A",
client_device_identifier="install-abc",
)
)
found = db_device_handler.get_device_by_client_identifier(
user_id=admin_user.id,
client_device_identifier="install-abc",
)
assert found is not None
assert found.id == "cid-device-1"
def test_returns_none_for_unknown_identifier(self, admin_user: User):
db_device_handler.add_device(
Device(
id="cid-device-2",
user_id=admin_user.id,
client_device_identifier="install-abc",
)
)
found = db_device_handler.get_device_by_client_identifier(
user_id=admin_user.id,
client_device_identifier="does-not-exist",
)
assert found is None
def test_scopes_by_user(self, admin_user: User, editor_user: User):
db_device_handler.add_device(
Device(
id="cid-device-admin",
user_id=admin_user.id,
client_device_identifier="shared-identifier",
)
)
db_device_handler.add_device(
Device(
id="cid-device-editor",
user_id=editor_user.id,
client_device_identifier="shared-identifier",
)
)
admin_found = db_device_handler.get_device_by_client_identifier(
user_id=admin_user.id,
client_device_identifier="shared-identifier",
)
editor_found = db_device_handler.get_device_by_client_identifier(
user_id=editor_user.id,
client_device_identifier="shared-identifier",
)
assert admin_found is not None
assert editor_found is not None
assert admin_found.id == "cid-device-admin"
assert editor_found.id == "cid-device-editor"
def test_empty_identifier_returns_none(self, admin_user: User):
db_device_handler.add_device(
Device(
id="cid-device-3",
user_id=admin_user.id,
client_device_identifier=None,
)
)
found = db_device_handler.get_device_by_client_identifier(
user_id=admin_user.id,
client_device_identifier="",
)
assert found is None
class TestUpdateLastSeenDebounced:
def test_bumps_when_last_seen_is_null(self, admin_user: User):
device = db_device_handler.add_device(
Device(id="debounce-fresh", user_id=admin_user.id, last_seen=None)
)
db_device_handler.update_last_seen_debounced(device_id=device.id)
refreshed = db_device_handler.get_device_by_id(device.id)
assert refreshed is not None
assert refreshed.last_seen is not None
def test_bumps_when_last_seen_is_old(self, admin_user: User):
old = datetime.now(timezone.utc) - timedelta(minutes=10)
device = db_device_handler.add_device(
Device(id="debounce-old", user_id=admin_user.id, last_seen=old)
)
db_device_handler.update_last_seen_debounced(device_id=device.id)
refreshed = db_device_handler.get_device_by_id(device.id)
assert refreshed is not None
assert refreshed.last_seen is not None
# MariaDB returns naive datetimes; normalize to UTC for comparison
assert to_utc(refreshed.last_seen) > old
def test_skips_when_last_seen_within_debounce_window(self, admin_user: User):
recent = datetime.now(timezone.utc) - timedelta(minutes=1)
device = db_device_handler.add_device(
Device(id="debounce-recent", user_id=admin_user.id, last_seen=recent)
)
db_device_handler.update_last_seen_debounced(device_id=device.id)
refreshed = db_device_handler.get_device_by_id(device.id)
assert refreshed is not None
# Unchanged: still within the 5-minute debounce window
assert refreshed.last_seen is not None
assert abs((to_utc(refreshed.last_seen) - recent).total_seconds()) < 1
def test_noop_on_missing_device(self):
# Should not raise
db_device_handler.update_last_seen_debounced(device_id="does-not-exist")
def test_does_not_read_the_device_before_updating_it(
self, admin_user: User, executed_statements: list[str]
):
device = db_device_handler.add_device(
Device(id="debounce-no-read", user_id=admin_user.id, last_seen=None)
)
executed_statements.clear()
db_device_handler.update_last_seen_debounced(device_id=device.id)
statements = [s.lstrip().lower() for s in executed_statements]
assert [s for s in statements if s.startswith("select")] == []
assert any(s.startswith("update devices") for s in statements)
def test_survives_a_concurrent_request_committing_the_same_update(
self, admin_user: User
):
"""Guards against MariaDB error 1020, "Record has changed since last read"."""
device = db_device_handler.add_device(
Device(id="debounce-race", user_id=admin_user.id, last_seen=None)
)
with run_before_first(
"update devices",
lambda: db_device_handler.update_last_seen_debounced(device_id=device.id),
) as raced:
db_device_handler.update_last_seen_debounced(device_id=device.id)
assert raced
refreshed = db_device_handler.get_device_by_id(device.id)
assert refreshed is not None
assert refreshed.last_seen is not None