wrolpi/wrolpi/config_version.py
lrnselfreliance 946043450e
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Database configs carry a version the database keeps too (#866)
* Benchmark every database config import (#865)

An opt-in test (WROLPI_CONFIG_BENCH=1) that builds a large library in bulk,
writes each config with its own dump_config, then times every import in
startup order: a steady pass (the database already matches) and a rebuild
(config-owned rows deleted, everything restored from the configs).  It
prints seconds, SQL statements and writes per import, and asserts the
rebuild restored every row so no timed import silently skipped its work.
WROLPI_CONFIG_BENCH_SCALE multiplies the row counts.

The baseline for the config import rework.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* Database configs carry a version the database keeps too

Step 1 of the config import rework.  A database config (tags, downloads,
channels, domains, playlists, repos, recently viewed) and the database now
each carry an integer version, so an import can tell which side is newer
without a clock (a Raspberry Pi's resets at boot):

- config_version (new table) holds the database's version of each config.
- An after_flush hook adds one to it for every config whose rows a flush
  changed, in the same transaction.  Each config registers what it owns
  (register_ownership): models, optionally only some columns, optionally
  only some rows (a Collection's kind; a Download's Collection's kind).
  Raw SQL writes to owned tables count explicitly.
- dump_config writes the database's version, read with the rows it saves;
  save() no longer adds one for these configs.
- An import compares versions first: file == database or newer imports
  with deletes; file older (the database changed and was not saved before a
  restart) saves the database instead of undoing that change; no database
  row (a config this code never imported) imports without deletes.  The
  import records the file's version last.
- The Import button and backup imports apply the file whatever its version
  (import_forced).

Importers only gate their existing deletes on the decision here; they are
otherwise unchanged.

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

* Config versions: keep unsaved rows after a no-delete import, count every owned write

Review fixes:

- An import without deletes (no database version yet) no longer records the
  file's version, which let the next startup delete the rows it had kept.
  The version stays unknown, and the database is saved into the file instead;
  a successful save records the version.  A save after a partial import is
  refused, so the version stays unknown until an import applies the whole file.
- An import removes the database's version while it runs, so its own writes
  do not count: one that fails partway no longer looks newer than the file
  and gets saved over it on the next startup.
- Playlists imported without deletes keep their database items in order; the
  file's other items are added after their neighbor from the file.
- A Download leaving a Channel or Repo counts for that Collection's config
  (collection_id loads its previous value).
- Bulk writes count: untagging, retrying Downloads, deleting a duplicate's
  Download, removing many items from a playlist.  Deleting Downloads by id
  counts channels.yaml/repos.yaml only for their Downloads.
- Only a playlist's items count for playlists.yaml (author and subject
  Collections have items too).  Collection kinds are looked up once per flush.

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

* Config versions count only the columns each config saves

A Repo's fetch (head_sha, last_fetch), a Channel's refresh (video_count,
info_json), a Collection's counts, and a Download attempt (attempts, error)
counted as config changes, so the next import of that config saved instead of
importing: a hand edit to repos.yaml was overwritten after any fetch.  Each
model now registers only the columns its config saves.

domains.yaml saves its domains' Downloads, which now count for it.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 14:58:18 -06:00

185 lines
7.8 KiB
Python

"""Which saved version of each database config the database is in step with.
A database config (tags.yaml, channels.yaml, ...) saves rows the database owns. Its file carries an integer
`version`; the database keeps one too, in `config_version`. Every change to rows a config owns adds one to that
config's database version, in the same transaction (`_count_config_changes`). `dump_config` writes the database's
version into the file it saves, and an import records the file's version once it has applied it.
So an import can tell which side is newer by comparing two integers (see `ConfigFile.import_decision`):
* file == database: in step. The file is current; import it, deleting what it no longer lists.
* file > database: the file is newer (a restored or wiped database, a copied config); import it the same way.
* file < database: the database changed and was not saved yet (e.g. WROLPi restarted first). Save the database
instead of importing the older file, which would undo those changes.
* no database row: not known yet (a config never imported by this code, or an import that did not finish).
Import without deleting, and leave the version unknown: the database may have rows the file does not list. Then
save them into the file; that save records its version (`ConfigFile.record_saved_version`).
Integers only: a Raspberry Pi has no clock that survives a reboot, so timestamps cannot order these.
"""
import json
from collections import defaultdict
from dataclasses import dataclass
from typing import Callable, Dict, FrozenSet, List, Optional, Set, Type
import sqlite3
from sqlalchemy import Column, Integer, String, event, inspect, text
from sqlalchemy.orm import Session
from wrolpi.common import Base
class ConfigVersion(Base):
__tablename__ = 'config_version'
name = Column(String, primary_key=True) # The config's file_name, e.g. "tags.yaml".
version = Column(Integer, nullable=False)
def __repr__(self):
return f'<ConfigVersion {self.name}={self.version}>'
@dataclass(frozen=True)
class Ownership:
config: str
model: Type
# Only changes to these columns count; None counts every column.
columns: Optional[FrozenSet[str]] = None
# Only rows this accepts belong to the config (e.g. Collections of one kind); None accepts every row.
row: Optional[Callable] = None
OWNERSHIPS: Dict[Type, List[Ownership]] = defaultdict(list)
def register_ownership(config: str, model: Type, columns: Set[str] = None, row: Callable = None):
"""Declare that `config` (a file_name) saves `model`'s rows, so changing them makes the database newer than
the config file until it is saved again."""
OWNERSHIPS[model].append(Ownership(config, model, frozenset(columns) if columns else None, row))
def versioned_config_names() -> Set[str]:
return {o.config for ownerships in OWNERSHIPS.values() for o in ownerships}
def _owners(obj, changed: bool) -> Set[str]:
"""The configs that save `obj`. `changed`: only those whose columns of an updated row changed; otherwise (an
inserted or deleted row) only those whose columns have a value."""
names = set()
for ownership in OWNERSHIPS.get(type(obj), ()):
# Columns first: `row` may query (e.g. `collection_kind`).
if changed:
state = inspect(obj)
columns = ownership.columns or [i.key for i in state.mapper.column_attrs]
if not any(state.attrs[i].history.has_changes() for i in columns):
continue
elif ownership.columns and all(getattr(obj, i) is None for i in ownership.columns):
# e.g. a FileGroup that was never viewed is not in recently_viewed.yaml.
continue
if ownership.row and not ownership.row(obj):
continue
names.add(ownership.config)
return names
_COLLECTION_KINDS = 'config_version_collection_kinds'
@event.listens_for(Session, 'after_flush')
def _count_config_changes(session: Session, flush_context):
"""Add one to the database version of each config whose rows this flush changed, in the same transaction.
Only existing rows are counted: a config without a row is not known yet, and its next import creates the row.
Raw SQL writes to owned tables are not seen here; they must call `count_config_change`."""
if not OWNERSHIPS:
return
names = set()
session.info[_COLLECTION_KINDS] = dict()
try:
for obj in session.new:
names |= _owners(obj, changed=False)
for obj in session.deleted:
names |= _owners(obj, changed=False)
for obj in session.dirty:
names |= _owners(obj, changed=True)
finally:
del session.info[_COLLECTION_KINDS]
if names:
count_config_change(session, *names)
def count_config_change(session: Session, *names: str):
"""Add one to these configs' database versions (only those which have one)."""
params = {f'n{i}': name for i, name in enumerate(names)}
placeholders = ', '.join(f':{i}' for i in params)
session.connection().execute(
text(f'UPDATE config_version SET version = version + 1 WHERE name IN ({placeholders})'), params)
def count_config_change_curs(curs, *names: str):
"""`count_config_change` for a raw `sqlite3` cursor, in its transaction."""
placeholders = ', '.join('?' for _ in names)
try:
curs.execute(f'UPDATE config_version SET version = version + 1 WHERE name IN ({placeholders})', names)
except sqlite3.OperationalError as e:
# A migration older than config_version runs this code too.
if 'no such table' not in str(e):
raise
def collection_kinds(obj) -> Set[str]:
"""The kinds of the Collections `obj` (e.g. a Download) belongs to, and belonged to before this flush (moving
it out of a Collection changes that Collection's config too), read on its flush's connection."""
ids = {i for i in inspect(obj).attrs.collection_id.history.deleted if i}
if obj.collection_id:
ids.add(obj.collection_id)
if not ids:
return set()
session = Session.object_session(obj)
# A Collection's kind never changes: look each up once per flush (a playlist import writes thousands of items).
kinds = session.info.get(_COLLECTION_KINDS, dict())
if missing := ids - kinds.keys():
rows = session.connection().execute(
text('SELECT id, kind FROM collection WHERE id IN (SELECT value FROM json_each(:ids))'),
{'ids': json.dumps(sorted(missing))})
kinds.update(dict.fromkeys(missing))
kinds.update(rows.all())
return {kinds[i] for i in ids} - {None}
def get_config_version(session: Session, name: str) -> Optional[int]:
row = session.connection().execute(
text('SELECT version FROM config_version WHERE name = :name'), {'name': name}).first()
return row[0] if row else None
def delete_config_version(session: Session, name: str):
session.connection().execute(text('DELETE FROM config_version WHERE name = :name'), {'name': name})
def create_config_version(session: Session, name: str, version: int):
"""Record `version` unless the database already has one."""
session.connection().execute(
text('INSERT INTO config_version (name, version) VALUES (:name, :version) ON CONFLICT (name) DO NOTHING'),
{'name': name, 'version': version})
def set_config_version(session: Session, name: str, version: int):
session.connection().execute(
text('INSERT INTO config_version (name, version) VALUES (:name, :version) '
'ON CONFLICT (name) DO UPDATE SET version = excluded.version'),
{'name': name, 'version': version})
IMPORT = 'import'
IMPORT_WITHOUT_DELETES = 'import_without_deletes'
SAVE = 'save'
def decide(file_version: int, db_version: Optional[int]) -> str:
"""The table in this module's docstring."""
if db_version is None:
return IMPORT_WITHOUT_DELETES
if file_version < db_version:
return SAVE
return IMPORT