Source code for s365b.core.generation

"""Catalog generation: never reclaim space the catalog does not know about.

Retention deletes repository data that no catalog entry refers to. That is
only safe if the catalog database knows everything in the repository. It
does not after a database loss (a new server connected to an existing
repository) or after restoring an older database dump: data written since
looks unreferenced, and reclaiming it would delete those backups.

So each repository has a generation, a counter kept twice: in the database
(``repository.generation``) and in the repository (``generation/``). Every
catalog commit that may point at newly written content raises the
database's number in the same transaction, then writes it to the
repository. A dump taken before that commit therefore holds a lower number
than the repository: restored, it is recognised as behind, and retention
keeps every pack (it still prunes catalog entries, which only touches the
database). Content written but never committed (a crash between flushing
and committing) is referenced by no database at all, so reclaiming it is
safe.

The repository keeps one file per number written, and reading takes the
highest: two writers finishing out of order cannot lower it.

One gap remains: if the process dies between a commit and writing the
repository's number, and a dump from just before that commit is restored,
the difference goes unnoticed. What it exposes is only the content that
one lost commit stored (possibly several items): the restored database
refers to none of it, so it can be reclaimed. The next backup reads those
items again from the state saved before, but only as they are at the source
then: a version since changed or deleted there is not recovered. Writing
the number before the commit would close the gap but open a worse one: a
commit that then fails would leave the repository ahead, and retention
stopped until a newer dump is restored, which does not exist.

Backups do not raise the number while the repository is ahead: that would
hide the mismatch.
"""

from __future__ import annotations

from sqlalchemy import update
from sqlalchemy.ext.asyncio import AsyncSession

from s365b.core.logging import get_logger
from s365b.db.models import RepositoryConfig
from s365b.db.session import Database
from s365b.storage import Repository

[docs] log = get_logger(__name__)
[docs] async def bump(s: AsyncSession, repository_fk: int, on_disk: int) -> int | None: """Raise the database's generation within a catalog commit. Call it last in the transaction (it holds the repository's row until the commit), then write the result with :meth:`Repository.write_generation` once the transaction has committed. Args: s: The session of the catalog commit. repository_fk: Repository row ID. on_disk: The repository's generation, read before the transaction. Returns: The new generation, or ``None`` if the repository is ahead of this database and was left alone. """ # One UPDATE: it locks the row against other writers' raises only (FOR NO # KEY UPDATE), not against the key locks new versions take on it. new = ( await s.execute( update(RepositoryConfig) .where(RepositoryConfig.id == repository_fk, RepositoryConfig.generation >= on_disk) .values(generation=RepositoryConfig.generation + 1) .returning(RepositoryConfig.generation) ) ).scalar_one_or_none() if new is None: row = await s.get(RepositoryConfig, repository_fk) log.warning( "repository.catalog_behind", repository=row.name if row else repository_fk, catalog=row.generation if row else None, repository_generation=on_disk, ) return new
[docs] async def catalog_behind(db: Database, repository_fk: int, repo: Repository) -> int | None: """Whether the repository holds data newer than this database knows. Args: db: Database. repository_fk: Repository row ID. repo: The open repository. Returns: The repository's generation if it is ahead of the database, else ``None``. """ on_disk = await repo.read_generation() async with db.session() as s: row = await s.get(RepositoryConfig, repository_fk) assert row is not None # noqa: S101 - caller checked return on_disk if on_disk > row.generation else None
[docs] async def mark_connected(repo: Repository) -> None: """Mark a repository connected to a new database as holding unknown data. A repository from before generations has none; if it holds data, it is given generation 1, so that this database (generation 0) is behind. Args: repo: The repository just connected. """ if repo.stats().packs and await repo.read_generation() == 0: await repo.write_generation(1)