Source code for automated_document_parser.backup

"""Consistent, local-first backup and restore for ADP SQLite state."""

from __future__ import annotations

import hashlib
import json
import os
import shutil
import sqlite3
import tempfile
import uuid
from contextlib import closing
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

_FORMAT_VERSION = 1
_DATABASES = {
    "index": ("index.sqlite3", "document_vectors"),
    "jobs": ("jobs.sqlite3", "ingestion_jobs"),
}
_MANIFEST = "manifest.json"


def _utc_now() -> datetime:
    return datetime.now(UTC)


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def _validate_database(path: Path, expected_table: str) -> None:
    """Validate SQLite integrity and the expected ADP schema without mutation."""
    uri = f"{path.resolve().as_uri()}?mode=ro"
    try:
        with closing(sqlite3.connect(uri, uri=True)) as connection:
            result = connection.execute("PRAGMA quick_check").fetchone()
            if result is None or result[0] != "ok":
                raise ValueError(f"SQLite integrity check failed for {path.name}")
            table = connection.execute(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
                (expected_table,),
            ).fetchone()
            if table is None:
                raise ValueError(
                    f"{path.name} is missing the expected {expected_table} table"
                )
    except sqlite3.DatabaseError as exc:
        raise ValueError(f"Invalid SQLite database {path.name}: {exc}") from exc


def _copy_sqlite_online(source: Path, destination: Path) -> None:
    """Use SQLite's online backup API so committed WAL data is included."""
    source_uri = f"{source.resolve().as_uri()}?mode=ro"
    try:
        with (
            closing(sqlite3.connect(source_uri, uri=True)) as source_db,
            closing(sqlite3.connect(destination)) as destination_db,
        ):
            source_db.backup(destination_db, pages=256, sleep=0.05)
            result = destination_db.execute("PRAGMA quick_check").fetchone()
            if result is None or result[0] != "ok":
                raise ValueError(f"Backup integrity check failed for {source.name}")
    except sqlite3.DatabaseError as exc:
        raise ValueError(f"Unable to back up SQLite database {source}: {exc}") from exc
    destination.chmod(0o600)


def _read_manifest(backup_dir: Path) -> dict[str, Any]:
    manifest_path = backup_dir / _MANIFEST
    if (
        backup_dir.is_symlink()
        or not backup_dir.is_dir()
        or manifest_path.is_symlink()
        or not manifest_path.is_file()
    ):
        raise ValueError("Backup directory must contain a manifest.json file")
    try:
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise ValueError(f"Unable to read backup manifest: {exc}") from exc
    if (
        not isinstance(manifest, dict)
        or manifest.get("format_version") != _FORMAT_VERSION
    ):
        raise ValueError("Unsupported or invalid backup manifest format")
    databases = manifest.get("databases")
    if (
        not isinstance(databases, dict)
        or not databases
        or set(databases) - set(_DATABASES)
        or any(not isinstance(entry, dict) for entry in databases.values())
    ):
        raise ValueError("Backup manifest contains an invalid database inventory")
    if not isinstance(manifest.get("created_at"), str):
        raise TypeError("Backup manifest creation timestamp must be a string")
    try:
        datetime.fromisoformat(manifest["created_at"])
    except ValueError as exc:
        raise ValueError(
            "Backup manifest contains an invalid creation timestamp"
        ) from exc
    return manifest


def _verified_backup_files(
    backup_dir: Path, manifest: dict[str, Any]
) -> dict[str, Path]:
    verified: dict[str, Path] = {}
    for kind, (expected_name, expected_table) in _DATABASES.items():
        if kind not in manifest["databases"]:
            continue
        entry = manifest["databases"][kind]
        if entry.get("file") != expected_name:
            raise ValueError(f"Invalid backup entry for {kind} database")
        size_bytes = entry.get("size_bytes")
        checksum = entry.get("sha256")
        if (
            isinstance(size_bytes, bool)
            or not isinstance(size_bytes, int)
            or size_bytes < 0
            or not isinstance(checksum, str)
            or len(checksum) != 64
            or any(character not in "0123456789abcdef" for character in checksum)
        ):
            raise ValueError(f"Invalid size or checksum metadata for {kind} database")
        path = backup_dir / expected_name
        if path.is_symlink() or not path.is_file():
            raise ValueError(f"Backup database is missing or unsafe: {expected_name}")
        if path.stat().st_size != size_bytes:
            raise ValueError(f"Backup size verification failed: {expected_name}")
        if _sha256(path) != checksum:
            raise ValueError(f"Backup checksum verification failed: {expected_name}")
        _validate_database(path, expected_table)
        verified[kind] = path
    return verified


def _prune_backups(destination: Path, *, retention_count: int) -> list[str]:
    if retention_count == 0:
        return []
    candidates: list[tuple[str, Path]] = []
    for child in destination.iterdir():
        if (
            not child.is_dir()
            or child.is_symlink()
            or not child.name.startswith("backup-")
        ):
            continue
        try:
            manifest = _read_manifest(child)
            created_at = manifest.get("created_at")
            if isinstance(created_at, str):
                candidates.append((created_at, child))
        except (OSError, ValueError):
            continue
    candidates.sort(key=lambda item: item[0], reverse=True)
    removed: list[str] = []
    for _, old_backup in candidates[retention_count:]:
        shutil.rmtree(old_backup)
        removed.append(old_backup.name)
    return removed


[docs] def create_backup( *, index_database: str | Path, jobs_database: str | Path, destination: str | Path, retention_count: int = 7, ) -> dict[str, Any]: """Create an atomic backup directory for all existing ADP SQLite stores. Each database is captured using SQLite's online backup API. The two databases are individually consistent, but are not a cross-database transaction snapshot. Missing, not-yet-created databases are omitted. """ if ( isinstance(retention_count, bool) or not isinstance(retention_count, int) or retention_count < 0 ): raise ValueError("retention_count must be a non-negative integer") sources = { "index": Path(index_database).expanduser(), "jobs": Path(jobs_database).expanduser(), } existing: dict[str, Path] = {} for kind, source in sources.items(): if source.is_symlink(): raise ValueError(f"Database path must be a regular file: {source}") if source.exists(): if not source.is_file(): raise ValueError(f"Database path must be a regular file: {source}") existing[kind] = source.resolve() if not existing: raise FileNotFoundError("No ADP SQLite databases exist at the configured paths") requested_root = Path(destination).expanduser() if requested_root.is_symlink(): raise ValueError("Backup destination must not be a symlink") root = requested_root.resolve() root.mkdir(parents=True, exist_ok=True, mode=0o700) if not root.is_dir(): raise ValueError("Backup destination must be a directory, not a symlink") stage = Path(tempfile.mkdtemp(prefix=".adp-backup-", dir=root)) stage.chmod(0o700) stamp = _utc_now().strftime("%Y%m%dT%H%M%SZ") final = root / f"backup-{stamp}-{uuid.uuid4().hex[:8]}" try: entries: dict[str, dict[str, Any]] = {} for kind, source in existing.items(): filename, expected_table = _DATABASES[kind] _validate_database(source, expected_table) target = stage / filename _copy_sqlite_online(source, target) _validate_database(target, expected_table) entries[kind] = { "file": filename, "size_bytes": target.stat().st_size, "sha256": _sha256(target), } manifest = { "format_version": _FORMAT_VERSION, "created_at": _utc_now().isoformat(timespec="microseconds"), "databases": entries, } manifest_path = stage / _MANIFEST manifest_path.write_text( json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) manifest_path.chmod(0o600) os.replace(stage, final) except Exception: shutil.rmtree(stage, ignore_errors=True) raise removed = _prune_backups(root, retention_count=retention_count) return { "backup": str(final), "created_at": manifest["created_at"], "databases": sorted(entries), "retention_count": retention_count, "removed_backups": removed, }
[docs] def restore_backup(*, backup: str | Path, target: str | Path) -> dict[str, Any]: """Verify a backup and atomically restore it into a new directory. The target must not already exist. Restored filenames are ``index.sqlite3`` and ``jobs.sqlite3`` so operators can explicitly map them to configured application database paths. """ requested_backup = Path(backup).expanduser() if requested_backup.is_symlink(): raise ValueError("Backup directory must not be a symlink") backup_dir = requested_backup.resolve() manifest = _read_manifest(backup_dir) verified = _verified_backup_files(backup_dir, manifest) requested_target = Path(target).expanduser() if requested_target.is_symlink(): raise ValueError("Restore target must not be a symlink") target_dir = requested_target.resolve() if target_dir.exists(): raise FileExistsError( f"Restore target already exists; refusing to overwrite: {target_dir}" ) target_dir.parent.mkdir(parents=True, exist_ok=True) stage = Path( tempfile.mkdtemp(prefix=f".{target_dir.name}.restore-", dir=target_dir.parent) ) stage.chmod(0o700) try: restored: dict[str, str] = {} for kind, source in verified.items(): destination = stage / _DATABASES[kind][0] shutil.copyfile(source, destination) destination.chmod(0o600) _validate_database(destination, _DATABASES[kind][1]) restored[kind] = str(target_dir / destination.name) shutil.copyfile(backup_dir / _MANIFEST, stage / _MANIFEST) (stage / _MANIFEST).chmod(0o600) os.rename(stage, target_dir) except Exception: shutil.rmtree(stage, ignore_errors=True) raise return {"restored_to": str(target_dir), "databases": restored}