Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(backup): keep user-retained backups when taking the pre-migration backup (#7151)

LearningCircuitb4a1c309f3b9
diff --git a/changelog.d/+premigration-backup-retention.bugfix.md b/changelog.d/+premigration-backup-retention.bugfix.md
new file mode 100644
index 0000000000..74b9404282
--- /dev/null
+++ b/changelog.d/+premigration-backup-retention.bugfix.md
@@ -0,0 +1,15 @@
+The automatic backup taken before a database migration no longer deletes
+backups that your `backup.max_count` and `backup.max_age_days` settings would
+keep. It used to apply the built-in limits (one backup, seven days), so the
+first sign-in that ran a migration removed every older backup. It now reads
+your retention settings, and if they cannot be read before the migration, or
+are not whole numbers between 1 and the settings' maximums (30 backups, 90
+days), it deletes nothing, including stale temporary files.
+Removing older backups can no longer delete the backup that has just been
+written, whatever the retention values. For the regular backup (not the
+pre-migration one), an `LDR_BACKUP_MAX_AGE_DAYS` of 0 or less, or one too
+large to turn into a date (for example 1000000, "keep forever"), now turns
+off only the age limit: `backup.max_count` still applies and stale temporary
+files are still removed. For the regular backup, an `LDR_BACKUP_MAX_COUNT` of
+0 or less is treated as 1, so the newest backup is kept. A new backup is also
+kept, rather than deleted, if removing older backups fails.
diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md
index 67714fa13d..8e6111866d 100644
--- a/docs/deployment/upgrading.md
+++ b/docs/deployment/upgrading.md
@@ -89,11 +89,15 @@ Treat a user with no `Pre-migration backup created` line for that sign-in
as having no pre-migration backup, and rely on the offline backup for that
user's rollback.
-This pre-migration backup is not durable. Writing it removes the user's
-older automatic backups, and later events replace or delete it. A sign-in
-adds a login backup only when the user has no backup dated the current UTC
-day, so only the first sign-in on each later UTC day adds one; further
-sign-ins that day add nothing.
+This pre-migration backup is not durable. Writing it applies the user's
+`backup.max_count` and `backup.max_age_days` to their older automatic
+backups, so with the default `backup.max_count` of `1` it removes all of
+them; if those settings cannot be read before the migration, or are not
+whole numbers within the settings' ranges (1 to 30 backups, 1 to 90 days),
+it removes none. Later events replace or delete the pre-migration backup
+itself. A sign-in adds a login backup only when the user has no backup dated
+the current UTC day, so only the first sign-in on each later UTC day adds
+one; further sign-ins that day add nothing.
- With the default `backup.max_count` of `1`, the first login backup made on
a later UTC day replaces it with a copy of the upgraded database. A
diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.py
index 28f06e7f23..83f4d52228 100644
--- a/src/local_deep_research/database/backup/backup_service.py
+++ b/src/local_deep_research/database/backup/backup_service.py
@@ -142,8 +142,11 @@ class BackupService:
Args:
username: User's username
password: User's password (for encryption)
- max_backups: Maximum number of backup files to keep
- max_age_days: Delete backups older than this many days
+ max_backups: Maximum number of backup files to keep. A value
+ below 1 is treated as 1 when backups are pruned.
+ max_age_days: Delete backups older than this many days. Zero,
+ a negative value, or a value too large to turn into a date
+ means no age limit.
"""
self.username = username
self.password = password
@@ -155,7 +158,9 @@ class BackupService:
self.db_path = get_encrypted_database_path() / self.db_filename
self.backup_dir = get_user_backup_directory(username)
- def create_backup(self, force: bool = False) -> BackupResult:
+ def create_backup(
+ self, force: bool = False, prune: bool = True
+ ) -> BackupResult:
"""Create an encrypted backup of the user's database.
Uses sqlcipher_export() to create a safe, atomic backup that inherits
@@ -172,6 +177,12 @@ class BackupService:
Args:
force: If True, skip the daily limit check.
+ prune: If False, keep every existing backup instead of applying
+ this service's ``max_backups`` / ``max_age_days`` limits
+ after the new backup is written. Used by the pre-migration
+ backup when the user's own retention settings could not be
+ read or are out of range. With True, the new backup itself
+ is never deleted by this cleanup.
Returns:
BackupResult with success status and backup path
@@ -202,7 +213,7 @@ class BackupService:
)
start = time.perf_counter()
- result = self._create_backup_impl()
+ result = self._create_backup_impl(prune=prune)
elapsed_ms = (time.perf_counter() - start) * 1000
size_info = (
f"{result.size_bytes / (1024 * 1024):.1f}MB"
@@ -221,7 +232,7 @@ class BackupService:
)
return result
- def _create_backup_impl(self) -> BackupResult:
+ def _create_backup_impl(self, prune: bool = True) -> BackupResult:
"""Internal implementation of backup creation (must be called with lock held)."""
if not self.db_path.exists():
return BackupResult(
@@ -372,8 +383,19 @@ class BackupService:
f"Created backup for user: {backup_path.name} ({backup_size} bytes)"
)
- # Cleanup old backups (safe now - new backup is finalized)
- self._cleanup_old_backups()
+ # Cleanup old backups (safe now - new backup is finalized).
+ # The new backup is passed as ``keep`` so no retention value
+ # can delete it. A cleanup failure must not reach the except
+ # below, which would delete the backup that was just finalized.
+ if prune:
+ try:
+ self._cleanup_old_backups(keep=backup_path)
+ except Exception as cleanup_error:
+ logger.warning(
+ "Old-backup cleanup failed "
+ f"({type(cleanup_error).__name__}); keeping the new "
+ "backup"
+ )
return BackupResult(
success=True,
@@ -455,19 +477,91 @@ class BackupService:
logger.warning("Backup verification failed")
return False
- def _cleanup_old_backups(self) -> int:
+ def _age_cutoff(self) -> Optional[datetime]:
+ """Return the time before which backups are too old, or None.
+
+ None means no age limit. That is the case when ``max_age_days``
+ is zero or negative (``LDR_BACKUP_MAX_AGE_DAYS=0`` is a common way
+ to say "keep forever", and would otherwise put the cutoff at or
+ after now, so every backup would count as too old), and when it
+ cannot be turned into a date: an env override such as
+ ``LDR_BACKUP_MAX_AGE_DAYS=1000000`` or ``inf`` overflows the
+ subtraction, and ``nan`` or a non-number cannot be converted. The
+ count limit and stale ``.tmp`` removal still run.
+ """
+ try:
+ if self.max_age_days <= 0:
+ logger.info(
+ f"backup.max_age_days={self.max_age_days!r} is not "
+ "positive; not removing backups by age"
+ )
+ return None
+ return datetime.now(UTC) - timedelta(days=self.max_age_days)
+ except (OverflowError, ValueError, TypeError):
+ logger.warning(
+ f"backup.max_age_days={self.max_age_days!r} is out of "
+ "range; not removing backups by age"
+ )
+ return None
+
+ def _count_limit(self) -> Optional[float]:
+ """Return how many backups to keep, or None for no count limit.
+
+ A ``max_backups`` below 1 (``LDR_BACKUP_MAX_COUNT=0`` or a negative
+ value) is treated as 1, the settings' minimum: the newest backup is
+ always kept and older ones are still pruned, so the setting cannot
+ delete every backup and cannot silently stop limiting disk use.
+ A value that cannot be compared with a count (``nan`` or a
+ non-number) means no count limit, as with ``_age_cutoff``; ``inf``
+ also means no count limit.
+ """
+ limit = self.max_backups
+ try:
+ below_one = limit < 1
+ is_nan = limit != limit # only NaN is unequal to itself
+ except TypeError:
+ is_nan = True
+ else:
+ if below_one:
+ logger.warning(
+ f"backup.max_count={limit!r} is below 1; keeping only "
+ "the newest backup"
+ )
+ return 1
+ if is_nan:
+ logger.warning(
+ f"backup.max_count={limit!r} is not a usable number; not "
+ "removing backups by count"
+ )
+ return None
+ return limit
+
+ def _cleanup_old_backups(self, keep: Optional[Path] = None) -> int:
"""Remove old backups based on age and count limits.
- Also cleans up stale .tmp files from interrupted backups.
+ Also cleans up stale .tmp files from interrupted backups. A
+ ``max_age_days`` that is not positive or is out of range disables
+ only the age limit (see ``_age_cutoff``); the count limit still
+ applies. A ``max_backups`` below 1 is treated as 1 (see
+ ``_count_limit``).
+
+ Args:
+ keep: A backup that is never deleted and always takes the
+ first slot of the count limit. ``_create_backup_impl``
+ passes the backup it has just finalized, so cleanup can
+ never delete it, whatever the retention values or file
+ modification times are.
Returns:
Number of backups deleted
"""
deleted_count = 0
- cutoff_time = datetime.now(UTC) - timedelta(days=self.max_age_days)
- stale_tmp_cutoff = datetime.now(UTC) - timedelta(hours=1)
+ cutoff_time = self._age_cutoff()
+ count_limit = self._count_limit()
try:
+ stale_tmp_cutoff = datetime.now(UTC) - timedelta(hours=1)
+
# Clean up stale .tmp files from interrupted/crashed backups
for tmp_file in [
f
@@ -504,16 +598,25 @@ class BackupService:
if p.exists() and is_safe_glob_result(p, self.backup_dir)
]
+ # The backup to keep goes first, so it fills the first slot
+ # of the count limit even if another file has a later mtime.
+ if keep is not None:
+ kept = [p for p in backups if p == keep]
+ backups = kept + [p for p in backups if p != keep]
+
for i, backup in enumerate(backups):
should_delete = False
+ if keep is not None and backup == keep:
+ continue
+
# Delete if beyond max count
- if i >= self.max_backups:
+ if count_limit is not None and i >= count_limit:
should_delete = True
- reason = f"exceeds max count ({self.max_backups})"
+ reason = "exceeds max count"
- # Delete if too old
- else:
+ # Delete if too old (skipped when there is no age limit)
+ elif cutoff_time is not None:
try:
mtime = datetime.fromtimestamp(
backup.stat().st_mtime, tz=UTC
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 3704424d96..eb063e1986 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -268,6 +268,60 @@ def _remove_partial_user_db_files(db_path: Path) -> None:
logger.warning(f"Could not remove partial user DB artifact {path}")
+# Upper bounds of ``backup.max_count`` / ``backup.max_age_days``: the
+# ``max_value`` of each in defaults/default_settings.json (a test pins
+# these to that file). The settings UI and import enforce them, but env
+# overrides (LDR_BACKUP_MAX_*) do not, so a value above them is not trusted
+# here and the pre-migration backup then removes nothing.
+_BACKUP_MAX_COUNT_LIMIT = 30
+_BACKUP_MAX_AGE_DAYS_LIMIT = 90
+
+
+def _read_backup_retention(engine: Engine) -> Optional[tuple[int, int]]:
+ """Read ``backup.max_count`` / ``backup.max_age_days`` for a user DB.
+
+ Reads them the way the login backup does (``SettingsManager``, env
+ overrides included), but read-only: nothing is seeded or written into
+ a database that has not been migrated yet. Returns ``None`` when the
+ values cannot be read, are not positive integers, or exceed the
+ settings' own ``max_value``, so the caller can keep every existing
+ backup instead of guessing a limit.
+ """
+ try:
+ from ..settings.manager import SettingsManager
+
+ with sessionmaker(bind=engine)() as session:
+ sm = SettingsManager(session, seed_defaults=False)
+ max_count = sm.get_setting("backup.max_count", None)
+ max_age_days = sm.get_setting("backup.max_age_days", None)
+ except Exception as e:
+ logger.warning(
+ "Could not read backup retention settings before migration "
+ f"({type(e).__name__}); keeping all existing backups"
+ )
+ return None
+
+ values = []
+ for value, limit in (
+ (max_count, _BACKUP_MAX_COUNT_LIMIT),
+ (max_age_days, _BACKUP_MAX_AGE_DAYS_LIMIT),
+ ):
+ if isinstance(value, float) and value.is_integer():
+ value = int(value)
+ if (
+ isinstance(value, bool)
+ or not isinstance(value, int)
+ or not 1 <= value <= limit
+ ):
+ logger.warning(
+ "Backup retention settings are not integers within their "
+ "allowed range; keeping all existing backups"
+ )
+ return None
+ values.append(value)
+ return values[0], values[1]
+
+
class DatabaseManager:
"""Manages encrypted SQLCipher databases for each user."""
@@ -1524,9 +1578,26 @@ class DatabaseManager:
try:
from .backup.backup_service import BackupService
- result = BackupService(
- username=username, password=password
- ).create_backup(force=True)
+ # Apply the user's own retention settings, the same
+ # ones the login backup uses. The library defaults
+ # (keep 1, max 7 days) would delete backups the user
+ # chose to keep. If the settings cannot be read from
+ # the not-yet-migrated schema, or are not positive
+ # integers within the settings' maximums, delete
+ # nothing.
+ retention = _read_backup_retention(engine)
+ if retention is None:
+ result = BackupService(
+ username=username, password=password
+ ).create_backup(force=True, prune=False)
+ else:
+ max_backups, max_age_days = retention
+ result = BackupService(
+ username=username,
+ password=password,
+ max_backups=max_backups,
+ max_age_days=max_age_days,
+ ).create_backup(force=True)
if result.success:
logger.info(
f"Pre-migration backup created: {result.backup_path}"
diff --git a/tests/database/backup/test_backup_service.py b/tests/database/backup/test_backup_service.py
index 24e042fef2..e2db70fa86 100644
--- a/tests/database/backup/test_backup_service.py
+++ b/tests/database/backup/test_backup_service.py
@@ -2604,7 +2604,8 @@ class TestBackupEdgeCases:
def test_cleanup_with_zero_max_backups(
self, mock_db_filename, mock_backup_dir, mock_db_path, tmp_path
):
- """Should delete all backups when max_backups is 0."""
+ """max_backups=0 is treated as 1: the newest backup is kept and
+ the rest are deleted (it must not delete every backup)."""
backup_dir = tmp_path / "backups"
backup_dir.mkdir()
@@ -2626,8 +2627,8 @@ class TestBackupEdgeCases:
)
deleted_count = service._cleanup_old_backups()
- assert deleted_count == 3
- assert len(list(backup_dir.glob("ldr_backup_*.db"))) == 0
+ assert deleted_count == 2
+ assert len(list(backup_dir.glob("ldr_backup_*.db"))) == 1
@patch(
"local_deep_research.database.backup.backup_service.get_encrypted_database_path"
diff --git a/tests/database/backup/test_premigration_backup_retention.py b/tests/database/backup/test_premigration_backup_retention.py
new file mode 100644
index 0000000000..157df64cc0
--- /dev/null
+++ b/tests/database/backup/test_premigration_backup_retention.py
@@ -0,0 +1,382 @@
+"""The pre-migration backup must not delete backups the user chose to keep.
+
+``DatabaseManager._open_user_database_cold`` writes a forced backup before
+running pending migrations. It used to build ``BackupService`` with the
+library defaults (keep 1 backup, max 7 days), so the cleanup after that
+backup deleted every older backup, ignoring the user's
+``backup.max_count`` / ``backup.max_age_days``. These tests drive the real
+open path with real SQLCipher files and check which backups survive.
+"""
+
+import os
+import time
+import uuid
+
+import pytest
+
+import local_deep_research.database.initialize as init_mod
+
+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")
+
+DAY = 24 * 60 * 60
+
+
+def manager(tmp_path, monkeypatch):
+ from local_deep_research.database.encrypted_db import DatabaseManager
+
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")
+ monkeypatch.delenv("LDR_BACKUP_MAX_COUNT", raising=False)
+ monkeypatch.delenv("LDR_BACKUP_MAX_AGE_DAYS", raising=False)
+ mgr = DatabaseManager()
+ if not mgr.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode)")
+ monkeypatch.setattr(mgr, "_run_phase2_rekey", lambda *a, **k: None)
+ yield mgr
+ mgr.close_all_databases()
+
+
+def _plant_backups(username, ages_days):
+ """Create fake backup files with the given ages; return their paths."""
+ from local_deep_research.config.paths import get_user_backup_directory
+
+ backup_dir = get_user_backup_directory(username)
+ now = time.time()
+ paths = []
+ for i, age in enumerate(ages_days):
+ path = backup_dir / f"ldr_backup_20200101_00000{i}.db"
+ path.write_bytes(b"older backup")
+ mtime = now - age * DAY
+ os.utime(path, (mtime, mtime))
+ paths.append(path)
+ return backup_dir, paths
+
+
+def _reopen_with_pending_migration(manager, monkeypatch, username, password):
+ manager.close_user_database(username)
+ monkeypatch.setattr(
+ "local_deep_research.database.alembic_runner.needs_migration",
+ lambda *a, **k: True,
+ )
+ monkeypatch.setattr(init_mod, "initialize_database", lambda *a, **k: None)
+ assert manager.open_user_database(username, password) is not None
+
+
+ ("max_count", "max_age_days", "ages", "kept", "pruned"),
+ [
+ # Age pruning: the 10-day backup is inside both limits and must
+ # survive (it would not under the 7-day default or with the two
+ # values swapped); the 40-day one is inside max_count=5 and is
+ # removed only by max_age_days=30.
+ pytest.param(5, 30, [1, 10, 40], [0, 1], [2], id="age"),
+ # Count pruning: all planted backups are inside max_age_days; the
+ # new backup plus the two newest fill max_count=3.
+ pytest.param(3, 30, [1, 2, 4, 5], [0, 1], [2, 3], id="count"),
+ ],
+)
+def test_premigration_backup_applies_user_retention_settings(
+ manager, monkeypatch, max_count, max_age_days, ages, kept, pruned
+):
+ """The pre-migration backup prunes with the user's backup.max_count and
+ backup.max_age_days, each passed through to BackupService."""
+ from local_deep_research.settings.manager import SettingsManager
+
+ username = f"premig_{uuid.uuid4().hex[:8]}"
+ password = "PreMigration-Pw-1!" # noqa: S105
+ engine = manager.create_user_database(username, password)
+ with manager.get_session(username) as session:
+ sm = SettingsManager(session)
+ assert sm.set_setting("backup.max_count", max_count)
+ assert sm.set_setting("backup.max_age_days", max_age_days)
+ assert engine is not None
+
+ backup_dir, planted = _plant_backups(username, ages)
+ _reopen_with_pending_migration(manager, monkeypatch, username, password)
+
+ remaining = set(backup_dir.glob("ldr_backup_*.db"))
+ new = remaining - set(planted)
+ assert len(new) == 1, "the pre-migration backup was not written"
+ for i in kept:
+ assert planted[i] in remaining, (
+ f"pre-migration backup deleted the {ages[i]}-day-old backup, "
+ "which the user's retention settings keep"
+ )
+ for i in pruned:
+ assert planted[i] not in remaining, (
+ f"the {ages[i]}-day-old backup is outside the user's retention "
+ "settings but was kept"
+ )
+
+
+def test_premigration_backup_survives_huge_max_age_days_override(
+ manager, monkeypatch
+):
+ """An env override such as LDR_BACKUP_MAX_AGE_DAYS=1000000 ("keep
+ forever") is above the setting's maximum, so the pre-migration backup
+ does not trust it: the new backup is kept and nothing is pruned."""
+ username = f"premig_{uuid.uuid4().hex[:8]}"
+ password = "PreMigration-Pw-3!" # noqa: S105
+ manager.create_user_database(username, password)
+ monkeypatch.setenv("LDR_BACKUP_MAX_AGE_DAYS", "1000000")
+
+ backup_dir, planted = _plant_backups(username, [1, 20])
+ _reopen_with_pending_migration(manager, monkeypatch, username, password)
+
+ remaining = set(backup_dir.glob("ldr_backup_*.db"))
+ assert len(remaining - set(planted)) == 1, (
+ "the pre-migration backup was deleted after it was written"
+ )
+ assert set(planted) <= remaining
+
+
+def test_cleanup_failure_keeps_the_finalized_backup(manager, monkeypatch):
+ """BackupService itself (the login backup path): if removing older
+ backups raises, the backup that was just finalized is kept and the
+ result is still a success."""
+ from local_deep_research.database.backup.backup_service import (
+ BackupService,
+ )
+
+ def _failing_cleanup(self, *args, **kwargs):
+ raise RuntimeError("cleanup failed")
+
+ monkeypatch.setattr(BackupService, "_cleanup_old_backups", _failing_cleanup)
+ username = f"premig_{uuid.uuid4().hex[:8]}"
+ password = "PreMigration-Pw-4!" # noqa: S105
+ manager.create_user_database(username, password)
+ backup_dir, planted = _plant_backups(username, [1])
+
+ result = BackupService(
+ username=username,
+ password=password,
+ max_backups=5,
+ max_age_days=7,
+ ).create_backup(force=True)
+
+ assert result.success, result.error
+ assert result.backup_path is not None and result.backup_path.exists()
+ assert planted[0].exists()
+
+
+ "max_age_days",
+ [740_000, 1_000_000, 999_999_999, float("inf"), float("nan")],
+ ids=["740000", "1000000", "999999999", "inf", "nan"],
+)
+def test_out_of_range_max_age_days_still_applies_max_count(
+ manager, max_age_days
+):
+ """BackupService itself (the login backup path): a max_age_days that
+ cannot be turned into a date (e.g. LDR_BACKUP_MAX_AGE_DAYS=1000000,
+ "keep forever") disables only the age limit. The count limit must
+ still prune, and stale .tmp files must still be removed; otherwise
+ every daily backup is kept until the disk fills."""
+ from local_deep_research.database.backup.backup_service import (
+ BackupService,
+ )
+
+ username = f"premig_{uuid.uuid4().hex[:8]}"
+ password = "PreMigration-Pw-5!" # noqa: S105
+ manager.create_user_database(username, password)
+ backup_dir, planted = _plant_backups(username, [1, 2, 3, 4])
+ stale_tmp = backup_dir / "ldr_backup_20200101_000009.db.tmp"
+ stale_tmp.write_bytes(b"interrupted backup")
+ old = time.time() - 2 * 60 * 60
+ os.utime(stale_tmp, (old, old))
+
+ result = BackupService(
+ username=username,
+ password=password,
+ max_backups=2,
+ max_age_days=max_age_days,
+ ).create_backup(force=True)
+
+ assert result.success, result.error
+ remaining = set(backup_dir.glob("ldr_backup_*.db"))
+ assert result.backup_path in remaining
+ assert remaining == {result.backup_path, planted[0]}, (
+ "max_count=2 was not applied: expected the new backup and the "
+ "newest planted one only"
+ )
+ assert not stale_tmp.exists(), "stale .tmp file was not removed"
+
+
+ ("max_backups", "max_age_days", "kept"),
+ [
+ # max_age_days <= 0 ("keep forever"): no age limit, so every
+ # planted backup is inside max_count=5 and is kept.
+ pytest.param(5, 0, [0, 1, 2], id="age-0"),
+ pytest.param(5, -1, [0, 1, 2], id="age-negative"),
+ pytest.param(5, -30.5, [0, 1, 2], id="age-negative-float"),
+ # max_count < 1 is treated as 1: the new backup is the one kept.
+ pytest.param(0, 7, [], id="count-0"),
+ pytest.param(-1, 7, [], id="count-negative"),
+ pytest.param(0, 0, [], id="both-0"),
+ pytest.param(-3, -3, [], id="both-negative"),
+ ],
+)
+def test_non_positive_retention_never_deletes_the_new_backup(
+ manager, max_backups, max_age_days, kept
+):
+ """BackupService itself (the login backup path passes the raw
+ settings and env overrides): LDR_BACKUP_MAX_AGE_DAYS=0 or a negative
+ value means no age limit, and LDR_BACKUP_MAX_COUNT=0 or a negative
+ value is treated as 1. Neither may delete the backup just written."""
+ from local_deep_research.database.backup.backup_service import (
+ BackupService,
+ )
+
+ username = f"premig_{uuid.uuid4().hex[:8]}"
+ password = "PreMigration-Pw-6!" # noqa: S105
+ manager.create_user_database(username, password)
+ backup_dir, planted = _plant_backups(username, [1, 2, 3])
+
+ result = BackupService(
+ username=username,
+ password=password,
+ max_backups=max_backups,
+ max_age_days=max_age_days,
+ ).create_backup(force=True)
+
+ assert result.success, result.error
+ assert result.backup_path is not None and result.backup_path.exists(), (
+ "the sign-in backup deleted the backup it had just written"
+ )
+ remaining = set(backup_dir.glob("ldr_backup_*.db"))
+ assert remaining == {result.backup_path} | {planted[i] for i in kept}
+
+
+def test_new_backup_kept_when_an_older_file_has_a_later_mtime(manager):
+ """The new backup always takes the first slot of the count limit, even
+ when another backup file's mtime is later (clock skew, a restored or
+ copied file), so max_count=1 prunes the other file, not the new one."""
+ from local_deep_research.database.backup.backup_service import (
+ BackupService,
+ )
+
+ username = f"premig_{uuid.uuid4().hex[:8]}"
+ password = "PreMigration-Pw-7!" # noqa: S105
+ manager.create_user_database(username, password)
+ backup_dir, planted = _plant_backups(username, [-1])
+
+ result = BackupService(
+ username=username,
+ password=password,
+ max_backups=1,
+ max_age_days=7,
+ ).create_backup(force=True)
+
+ assert result.success, result.error
+ assert result.backup_path is not None and result.backup_path.exists(), (
+ "cleanup deleted the backup it had just written"
+ )
+ assert set(backup_dir.glob("ldr_backup_*.db")) == {result.backup_path}
+
+
+def test_nan_max_backups_means_no_count_limit(manager):
+ """A max_count that is NaN cannot be compared with a count, so, like an
+ unusable max_age_days, it turns off only the count limit; the age
+ limit still prunes."""
+ from local_deep_research.database.backup.backup_service import (
+ BackupService,
+ )
+
+ username = f"premig_{uuid.uuid4().hex[:8]}"
+ password = "PreMigration-Pw-8!" # noqa: S105
+ manager.create_user_database(username, password)
+ backup_dir, planted = _plant_backups(username, [1, 2, 3, 20])
+
+ result = BackupService(
+ username=username,
+ password=password,
+ max_backups=float("nan"),
+ max_age_days=7,
+ ).create_backup(force=True)
+
+ assert result.success, result.error
+ remaining = set(backup_dir.glob("ldr_backup_*.db"))
+ assert remaining == {result.backup_path, *planted[:3]}
+
+
+def test_premigration_backup_keeps_all_when_settings_unreadable(
+ manager, monkeypatch
+):
+ """Without a readable settings table the retention limits are unknown,
+ so the pre-migration backup deletes nothing."""
+ monkeypatch.setattr(init_mod, "initialize_database", lambda *a, **k: None)
+ monkeypatch.setattr(
+ "local_deep_research.database.alembic_runner.needs_migration",
+ lambda *a, **k: False,
+ )
+ username = f"premig_{uuid.uuid4().hex[:8]}"
+ password = "PreMigration-Pw-2!" # noqa: S105
+ manager.create_user_database(username, password)
+
+ backup_dir, planted = _plant_backups(username, [1, 2, 20])
+ _reopen_with_pending_migration(manager, monkeypatch, username, password)
+
+ remaining = set(backup_dir.glob("ldr_backup_*.db"))
+ assert set(planted) <= remaining, (
+ "pre-migration backup deleted backups although the user's "
+ "retention settings could not be read"
+ )
+ assert len(remaining - set(planted)) == 1
+
+
+ ("values", "expected"),
+ [
+ ({"backup.max_count": 4, "backup.max_age_days": 30}, (4, 30)),
+ ({"backup.max_count": 4.0, "backup.max_age_days": 30.0}, (4, 30)),
+ ({"backup.max_count": 0, "backup.max_age_days": 30}, None),
+ ({"backup.max_count": 4, "backup.max_age_days": None}, None),
+ ({"backup.max_count": "4", "backup.max_age_days": 30}, None),
+ ({"backup.max_count": True, "backup.max_age_days": 30}, None),
+ ({"backup.max_count": 30, "backup.max_age_days": 90}, (30, 90)),
+ ({"backup.max_count": 31, "backup.max_age_days": 30}, None),
+ ({"backup.max_count": 4, "backup.max_age_days": 91}, None),
+ ({"backup.max_count": 4, "backup.max_age_days": 1_000_000}, None),
+ ],
+)
+def test_read_backup_retention_rejects_unusable_values(
+ monkeypatch, values, expected
+):
+ from local_deep_research.database import encrypted_db
+ from local_deep_research.settings.manager import SettingsManager
+
+ monkeypatch.setattr(
+ SettingsManager,
+ "get_setting",
+ lambda self, key, default=None, check_env=True: values[key],
+ )
+ engine = encrypted_db.create_engine("sqlite://")
+ try:
+ assert encrypted_db._read_backup_retention(engine) == expected
+ finally:
+ engine.dispose()
+
+
+def test_retention_limits_match_default_settings():
+ """The helper's ceilings are the settings' own max_value."""
+ import json
+ from pathlib import Path
+
+ from local_deep_research.database import encrypted_db
+
+ defaults_path = (
+ Path(encrypted_db.__file__).resolve().parent.parent
+ / "defaults"
+ / "default_settings.json"
+ )
+ defaults = json.loads(defaults_path.read_text(encoding="utf-8"))
+ assert (
+ defaults["backup.max_count"]["max_value"]
+ == encrypted_db._BACKUP_MAX_COUNT_LIMIT
+ )
+ assert (
+ defaults["backup.max_age_days"]["max_value"]
+ == encrypted_db._BACKUP_MAX_AGE_DAYS_LIMIT
+ )
diff --git a/tests/deployment/test_upgrade_rollback_docs.py b/tests/deployment/test_upgrade_rollback_docs.py
index 39e15f277d..6e7fb195f5 100644
--- a/tests/deployment/test_upgrade_rollback_docs.py
+++ b/tests/deployment/test_upgrade_rollback_docs.py
@@ -132,6 +132,39 @@ def test_guide_explains_how_to_keep_the_pre_migration_backup():
)
+def test_guide_says_the_pre_migration_backup_applies_the_users_retention():
+ """Writing the pre-migration backup prunes by the user's own settings.
+
+ ``encrypted_db`` reads ``backup.max_count`` and ``backup.max_age_days``
+ with ``_read_backup_retention`` before the migration and builds
+ ``BackupService`` with them. If they cannot be read, or are not whole
+ numbers within the settings' ranges, it writes the backup with
+ ``prune=False``. So the guide must not say that writing it always
+ removes the user's older automatic backups: with a raised
+ ``backup.max_count`` it keeps those inside the user's limits.
+ ``tests/database/backup/test_premigration_backup_retention.py`` pins
+ the code side; the ranges below come from the same constants.
+ """
+ from local_deep_research.database import encrypted_db
+
+ text = _prose(GUIDE)
+ stale = "Writing it removes the user's older automatic backups"
+ assert stale not in text, (
+ "writing the pre-migration backup prunes by the user's own "
+ "backup.max_count and backup.max_age_days, not unconditionally"
+ )
+ for phrase in (
+ "Writing it applies the user's `backup.max_count` and "
+ "`backup.max_age_days` to their older automatic backups",
+ "with the default `backup.max_count` of `1` it removes all of them",
+ "if those settings cannot be read before the migration, or are not "
+ "whole numbers within the settings' ranges "
+ f"(1 to {encrypted_db._BACKUP_MAX_COUNT_LIMIT} backups, 1 to "
+ f"{encrypted_db._BACKUP_MAX_AGE_DAYS_LIMIT} days), it removes none",
+ ):
+ assert phrase in text, f"upgrading.md lost {phrase!r}"
+
+
def test_guide_warns_that_a_first_sign_in_past_midnight_loses_the_backup():
"""The pre-migration backup's file name is stamped before its export.
@@ -270,7 +303,9 @@ def test_login_backup_is_skipped_while_a_backup_dated_today_exists(
The guide counts login backups per later UTC day, not per sign-in. That
holds only while ``create_backup(force=False)`` skips when a file dated
the current UTC day exists, and runs when the newest file is from an
- earlier day (the midnight case).
+ earlier day (the midnight case). The guide's "replaces it" also needs
+ that login backup to prune older backups, so the fake records the
+ ``prune`` flag ``create_backup`` passes to ``_create_backup_impl``.
"""
from datetime import UTC, datetime, timedelta
@@ -281,8 +316,8 @@ def test_login_backup_is_skipped_while_a_backup_dated_today_exists(
calls = []
- def fake_impl(self):
- calls.append(self.username)
+ def fake_impl(self, prune=True):
+ calls.append((self.username, prune))
return BackupResult(success=True)
from local_deep_research.database.backup import backup_service
@@ -308,15 +343,16 @@ def test_login_backup_is_skipped_while_a_backup_dated_today_exists(
yesterday = (frozen - timedelta(days=1)).strftime("%Y%m%d")
(tmp_path / f"ldr_backup_{yesterday}_235959.db").write_bytes(b"x")
svc.create_backup(force=False)
- assert calls == ["rollback-doc-user"], (
+ assert calls == [("rollback-doc-user", True)], (
"a login backup must run when the newest file is from an earlier "
- "UTC day"
+ "UTC day, and must prune older backups (prune=True); otherwise it "
+ "never replaces the pre-migration backup the guide warns about"
)
today = frozen.strftime("%Y%m%d")
(tmp_path / f"ldr_backup_{today}_000001.db").write_bytes(b"x")
svc.create_backup(force=False)
- assert calls == ["rollback-doc-user"], (
+ assert calls == [("rollback-doc-user", True)], (
"a second sign-in on the same UTC day made another login backup; "
"the guide's per-day counting is then wrong"
)