Files
romm/backend/tests/handler/test_dump_store.py
Georges-Antoine Assi ec1684d2af perf(metadata): serve the metadata dumps and fixtures from SQLite files (#5844)
* perf(metadata): serve the metadata dumps and fixtures from SQLite files

The LaunchBox and Switch TitleDB stores sat in valkey, which keeps every
byte resident: about 300MB on an instance with both imported, against
roughly 1MB for an empty server. Every read is an exact-key lookup and
nothing writes between imports, so they now live in read-only SQLite
files under RESOURCES_BASE_PATH/metadata, where the OS page cache holds
only the pages lookups touch.

A build writes a temporary file and renames it over the previous one,
so readers see the old store or the new one and never a partial import.
That replaces the initial-import flag and the schema stamp: the store
revision is part of the file name. A failed import keeps serving the
previous file.

The startup fixture indexes (MAME, ScummVM, Sony serials, known BIOS)
no longer get copied into valkey on every boot. They build on first use
into a file under the cache path, named after a hash of the JSON.

Startup deletes the old valkey keys and any file of an older revision,
and queues a rebuild when a store had data, so an upgrade refills
LaunchBox and TitleDB on its own. nginx returns 404 for the metadata
folder, since /assets/romm/resources is otherwise served without auth.

Measured against the real dumps: LaunchBox builds in 22s into 263MB on
disk, TitleDB in 1.2s into 54MB, the fixtures in 0.2s into 8MB. A hit
costs 10-23us including decompression, a miss about 7us.

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

* pr-ready: code-review

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

* pr-ready: simplify

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

* pr-ready: review-polish

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

* pr-ready: prose

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

* pr-ready: prose (code-review fixes)

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

* Keep the previous metadata store when a dump comes out empty

A LaunchBox or TitleDB build that writes no rows to its main table now
fails with EmptyDumpError instead of swapping an empty store over a
populated one.

Each store keeps one connection per process behind a lock instead of one
per thread. A build closes it once it swaps the file in, and any other
process closes its own on its next lookup, so a replaced file's disk
space is released instead of held by idle threads.

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

* Address Greptile review: trim DumpStore comments

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

* Restore valkey's own snapshot policy by default

The hourly default (48259b3a9, #3980) kept valkey from rewriting the
hundreds of MB of LaunchBox and TitleDB data it held. With those moved to
SQLite files, a snapshot holds only sessions, queues and query caches, so
an unset REDIS_SAVE_POLICY now leaves valkey's stock policy in place and
loses less on a crash. An empty value still disables snapshots.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:49:15 -05:00

263 lines
8.7 KiB
Python

import json
import os
import sqlite3
import threading
import time
from pathlib import Path
from typing import Any
import pytest
from handler import dump_store
from handler.dump_store import (
_ZSTD_MAGIC,
COMPRESS_MIN_BYTES,
STALE_BUILD_SECONDS,
DumpStore,
EmptyDumpError,
decode,
encode,
)
BIG_RECORD = {"Name": "Chrono Trigger", "Overview": "A long summary. " * 100}
SMALL_RECORD = "12345"
class TestEncode:
def test_compresses_a_record_worth_compressing(self):
stored = encode(BIG_RECORD)
assert stored.startswith(_ZSTD_MAGIC)
assert len(stored) < len(json.dumps(BIG_RECORD).encode())
def test_leaves_a_short_value_as_plain_json(self):
stored = encode(SMALL_RECORD)
assert stored == b'"12345"'
@pytest.mark.parametrize("payload_size", [2, COMPRESS_MIN_BYTES - 1])
def test_stores_a_payload_under_the_threshold_verbatim(self, payload_size: int):
# The threshold applies to the serialized payload, quotes included.
value = "x" * (payload_size - 2)
stored = encode(value)
assert not stored.startswith(_ZSTD_MAGIC)
assert json.loads(stored) == value
def test_compresses_a_payload_at_the_threshold(self):
value = "x" * (COMPRESS_MIN_BYTES - 2)
assert encode(value).startswith(_ZSTD_MAGIC)
def test_each_write_is_a_standalone_frame(self):
first, second = encode(BIG_RECORD), encode(BIG_RECORD)
assert first == second
assert decode(second) == BIG_RECORD
class TestDecode:
@pytest.mark.parametrize("value", [BIG_RECORD, SMALL_RECORD, [], {}, 0])
def test_round_trips_whatever_encode_wrote(self, value: Any):
assert decode(encode(value)) == value
def test_reads_a_plain_json_value(self):
"""A payload under the threshold is stored as JSON, so reads accept it."""
stored = encode(SMALL_RECORD)
assert not stored.startswith(_ZSTD_MAGIC)
assert decode(stored) == SMALL_RECORD
@pytest.mark.parametrize("missing", [None, b""])
def test_returns_nothing_for_an_absent_key(self, missing: bytes | None):
assert decode(missing) is None
@pytest.fixture
def store(tmp_path: Path) -> DumpStore:
return DumpStore(tmp_path, "games", "v2", ("titles", "ids"))
def _build(store: DumpStore, rows: dict[str, dict[str, Any]]) -> None:
with store.build() as writer:
for table, records in rows.items():
for key, value in records.items():
writer.put(table, key, value)
class TestDumpStoreReads:
def test_reads_back_what_a_build_wrote(self, store: DumpStore):
_build(store, {"titles": {"1": BIG_RECORD}, "ids": {"a": SMALL_RECORD}})
assert store.get("titles", "1") == BIG_RECORD
assert store.get("ids", "a") == SMALL_RECORD
def test_a_missing_key_reads_as_none(self, store: DumpStore):
_build(store, {"titles": {"1": BIG_RECORD}})
assert store.get("titles", "2") is None
assert store.get("ids", "1") is None
def test_a_store_never_built_reads_as_none(self, store: DumpStore):
assert not store.exists()
assert store.get("titles", "1") is None
def test_a_file_that_cannot_be_opened_reads_as_none(
self, store: DumpStore, monkeypatch: pytest.MonkeyPatch
):
_build(store, {"titles": {"1": SMALL_RECORD}})
def refuse(*_args: Any, **_kwargs: Any) -> None:
raise sqlite3.OperationalError("unable to open database file")
monkeypatch.setattr(sqlite3, "connect", refuse)
assert store.get("titles", "1") is None
def test_an_unknown_table_is_refused(self, store: DumpStore):
with pytest.raises(ValueError, match="no table"):
store.get("users; DROP TABLE titles", "1")
def test_a_later_write_of_a_key_wins(self, store: DumpStore):
_build(store, {"titles": {"1": "first"}})
with store.build() as writer:
writer.put("titles", "1", "first")
writer.put("titles", "1", "second")
assert store.get("titles", "1") == "second"
def test_writes_span_several_batches(
self, store: DumpStore, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setattr(dump_store, "WRITE_BATCH_SIZE", 3)
_build(store, {"titles": {str(i): i for i in range(10)}})
assert [store.get("titles", str(i)) for i in range(10)] == list(range(10))
def test_reads_from_another_thread(self, store: DumpStore):
_build(store, {"titles": {"1": SMALL_RECORD}})
results: list[Any] = []
thread = threading.Thread(
target=lambda: results.append(store.get("titles", "1"))
)
thread.start()
thread.join()
assert results == [SMALL_RECORD]
assert store.get("titles", "1") == SMALL_RECORD
class TestDumpStoreBuild:
def test_a_rebuild_is_picked_up_by_an_open_reader(self, store: DumpStore):
_build(store, {"titles": {"1": "old"}})
assert store.get("titles", "1") == "old"
_build(store, {"titles": {"1": "new"}})
assert store.get("titles", "1") == "new"
def test_a_rebuild_closes_the_replaced_file(self, store: DumpStore):
_build(store, {"titles": {"1": "old"}})
store.get("titles", "1")
assert store._conn is not None
old_conn = store._conn[1]
_build(store, {"titles": {"1": "new"}})
assert store._conn is None
with pytest.raises(sqlite3.ProgrammingError, match="closed"):
old_conn.execute("SELECT 1")
def test_a_swap_by_another_process_closes_the_replaced_file(
self, store: DumpStore, tmp_path: Path
):
_build(store, {"titles": {"1": "old"}})
store.get("titles", "1")
assert store._conn is not None
old_conn = store._conn[1]
other = DumpStore(tmp_path, "games", "v2", store.tables)
_build(other, {"titles": {"1": "new"}})
assert store.get("titles", "1") == "new"
with pytest.raises(sqlite3.ProgrammingError, match="closed"):
old_conn.execute("SELECT 1")
def test_a_build_missing_its_required_rows_keeps_the_previous_file(
self, tmp_path: Path
):
store = DumpStore(tmp_path, "games", "v2", ("titles", "ids"), "titles")
_build(store, {"titles": {"1": "old"}})
with pytest.raises(EmptyDumpError):
_build(store, {"ids": {"a": SMALL_RECORD}})
assert store.get("titles", "1") == "old"
assert store.get("ids", "a") is None
assert list(store.directory.iterdir()) == [store.path]
def test_an_unknown_required_table_is_refused(self, tmp_path: Path):
with pytest.raises(ValueError, match="no table"):
DumpStore(tmp_path, "games", "v2", ("titles",), "ids")
def test_the_file_appears_only_once_the_build_finishes(self, store: DumpStore):
with store.build() as writer:
writer.put("titles", "1", SMALL_RECORD)
writer.flush()
assert not store.exists()
assert store.exists()
def test_a_failed_build_keeps_the_previous_file(self, store: DumpStore):
_build(store, {"titles": {"1": "old"}})
with pytest.raises(RuntimeError), store.build() as writer:
writer.put("titles", "1", "new")
raise RuntimeError("dump went bad")
assert store.get("titles", "1") == "old"
assert list(store.directory.iterdir()) == [store.path]
def test_a_build_drops_the_files_of_other_revisions(
self, store: DumpStore, tmp_path: Path
):
older = tmp_path / "games.v1.sqlite"
older.write_bytes(b"")
other_store = tmp_path / "gamesdb.v1.sqlite"
other_store.write_bytes(b"")
_build(store, {"titles": {"1": SMALL_RECORD}})
assert not older.exists()
assert other_store.exists()
def test_a_build_clears_abandoned_temporary_files(
self, store: DumpStore, tmp_path: Path
):
abandoned = tmp_path / ".games.v2.sqlite.dead.tmp"
abandoned.write_bytes(b"")
stale = time.time() - STALE_BUILD_SECONDS - 1
os.utime(abandoned, (stale, stale))
recent = tmp_path / ".games.v2.sqlite.live.tmp"
recent.write_bytes(b"")
_build(store, {"titles": {"1": SMALL_RECORD}})
assert not abandoned.exists()
assert recent.exists()
class TestDropOtherRevisions:
def test_returns_the_files_it_deleted(self, store: DumpStore, tmp_path: Path):
older = tmp_path / "games.v1.sqlite"
older.write_bytes(b"")
assert store.drop_other_revisions() == [older]
assert not older.exists()
def test_a_missing_directory_has_nothing_to_drop(self, tmp_path: Path):
store = DumpStore(tmp_path / "absent", "games", "v2", ("titles",))
assert store.drop_other_revisions() == []